docs: honest README + quickstart, and a Starlight documentation site
CI / build (pull_request) Has been cancelled

Bring the README in line with what shipped and fill the gaps a technical
reader comparing frameworks needs: the busboy peer dep and dual build, a
Routing section with its limits, an explicit "bring your own auth" scope
note, why legacy decorators is a design choice (not laziness), and CalVer
beta versioning.

Add a full Astro Starlight docs site under website/ — getting started,
concepts, per-feature guides, and an API reference — migrated from the
tested quickstart so the examples stay accurate.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-07-07 12:02:17 -05:00
1 parent d6c5cee0ee
commit 654c0563fc
24 files changed
+8275 -7

No files matched your search

+39 -6
View File
@@ -2,10 +2,13 @@
> A calm, type-safe HTTP framework for Node. Your API is an explicit **dependency graph** you can see, slice, and trust — not a mutable bag threaded through positional middleware.
`@green-tea/core` — **beta**, RC-track. One runtime dependency: `reflect-metadata` (`ws` is an optional peer, only for WebSocket/mesh).
`@green-tea/core` — **beta**, RC-track. One runtime dependency: `reflect-metadata`. Two optional peers you install only if you use them: `ws` (WebSocket / mesh) and `busboy` (multipart uploads).
```bash
npm install @green-tea/core reflect-metadata
# optional, only if you use them:
npm install ws # WebSocket routes (@Ws) and mesh
npm install busboy # multipart/form-data file uploads
```
---
@@ -77,9 +80,10 @@ Beta shipped the parts a real API needs, without growing the runtime dependency
- **Secure by default.** `nosniff`, `X-Frame-Options`, `Referrer-Policy`, HSTS-when-secure — on every response, opt-out with one flag.
- **CORS** with a guarded preflight and the credentials-never-`*` rule enforced for you.
- **Validation via [Standard Schema](https://standardschema.dev).** `@body(schema)` accepts zod, valibot, or arktype — you bring the validator, the core stays zero-dep. Invalid input → `422` with per-field issues; the parsed value reaches your handler typed.
- **Real body parsing.** JSON, urlencoded, and `multipart/form-data` file uploads (`@body()` → `{ fields, files }`), size-capped (`413`) against DoS.
- **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS.
- **Graceful shutdown.** `app.close()` drains in-flight requests, closes live streams and mesh links.
- **Testable by construction.** `createApp({ overrides: { db: fakeDb } })` swaps any node in one line.
- **Dual ESM + CommonJS.** Ships both builds behind an `exports` map — `import` and `require` both resolve, with matching type declarations.
## Benchmarks
@@ -103,7 +107,7 @@ Every framework here can serve `/users/:id`. The difference shows up as the app
| **Real-time** | bolt on `ws`/`sse` libs | plugins | separate Gateway + adapter | separate engine | **return an `AsyncIterable`** — SSE, ndjson & WebSocket, one primitive |
| **Cross-service calls** | HTTP client / gRPC by hand | HTTP client / gRPC | Microservices transport + message patterns | — | **`@needs('x')` resolves on another node** |
| **Plugin can break your pipeline?** | yes (deletes your body parser) | encapsulated, but hooks are global | interceptor order matters | yes | **no** — plugins only `bus.on` + `scope.add` |
| **Runtime deps** | minimal | minimal | heavy (rxjs, reflect-metadata, …) | Express + InversifyJS | **`reflect-metadata` only** (`ws` optional) |
| **Runtime deps** | minimal | minimal | heavy (rxjs, reflect-metadata, …) | Express + InversifyJS | **`reflect-metadata` only** (`ws`, `busboy` optional) |
### Read it as a story
@@ -170,18 +174,45 @@ The handler signature declares exactly what it wants — in any order, nothing m
| `@param(...)` | route params | `()` · `('id')` · `('id', schema)` |
| `@query(...)` | parsed query string | `()` · `('q')` · `(['a','b'])` · `(schema)` |
| `@body(...)` | parsed body (JSON / urlencoded / multipart) | `()` · `('field')` · `(schema)` |
| `@headers(...)` | request headers | `()` · `('authorization')` · `(schema)` |
| `@headers(...)` | request headers (whole bag or picked) | `()` · `('authorization')` · `(['a','b'])` · `(schema)` |
| `@header('name')` | one request header (singular alias of `@headers`) | `('x-trace')` · `('x-count', schema)` |
`@needs` keys are validated at boot: nothing provides the key → `createApp` throws with a clear error instead of serving `undefined`. Pass a Standard Schema (`@body(User)`) and the value is validated, coerced, and typed before your handler sees it.
> **Optional providers degrade, they don't crash.** A provider marked `optional: true` that throws on boot does **not** abort startup — it is left unregistered and logged. On `listen()` the app prints a one-line summary of what's running degraded, and the list is queryable via `app.degraded()`. Routes that actually need a degraded provider fail at request time, not at boot. This is deliberate (graceful degradation); wire an alert off `app.degraded()` or the `boot:provider:fail` bus event in production so a degraded start is never silent.
## Routing
Patterns match by segment: static, `:param` (one segment), and a trailing `:name*` **catch-all** that captures the rest of the path — slashes included — into `params.name`. When more than one route matches, the **most specific wins** (static ▸ `:param` ▸ catch-all), independent of registration order. A path that exists under a *different* method returns **`405` with an `Allow` header**, not `404`.
```typescript
@Get('/files/:path*') // /files/img/2026/logo.png → params.path = "img/2026/logo.png"
```
**Not yet** (post-beta, on the roadmap): regex / typed param constraints like `:id(\d+)`, and route matching is a linear scan — fine for typical route tables, but a radix-tree matcher for very large ones isn't built.
## Two layers
1. **Typed functional core (`flow`)** — `flow().step(...).step(...).handle(...)`; step outputs accumulate into the context type (`Acc & Out`). This is where the compile-time guarantee lives.
2. **Declarative decorator layer** — `@Provider/@Step/@Module/@Route/@Get/@Transformer` + argument decorators. Emits runtime metadata, builds and topologically sorts the graph, validates at boot.
## Why legacy decorators
green-tea uses **legacy** (experimental) decorators — you set `experimentalDecorators: true` in your `tsconfig`. This is a design decision, not inertia.
The framework's argument injection (`@param`, `@query`, `@body`, `@header`, `@needs`, `@ctx`, `@inbound`, `@abort`) relies on **parameter decorators** — and the TC39 standard decorators proposal (Stage 3) deliberately does **not** include them. There is no standards-track way to decorate a parameter today, so a handler like `handler(@param('id') id: string)` is only expressible with legacy decorators.
"Stage 3" also means *not finalized*: the proposal can still change before engines ship it. We track it, and if parameter injection ever gets a viable standard path we'll revisit. Until then, legacy decorators are the right tool for this API — not a shortcut. (We don't rely on `emitDecoratorMetadata`/`design:type` reflection; argument positions are recorded explicitly, so this is the only legacy surface we depend on.)
## Honest scope
green-tea is **beta**, on the road to a release candidate. Express and Fastify have a decade of ecosystem; NestJS has enterprise tooling and a huge plugin catalog. green-tea's mesh is a walking skeleton — distributed DI works, but discovery, load-balancing, and failover are not built yet. Pick green-tea for the model and the ergonomics, not the ecosystem — *yet*.
green-tea is **beta**, on the road to a release candidate. Express and Fastify have a decade of ecosystem; NestJS has enterprise tooling and a huge plugin catalog. Pick green-tea for the model and the ergonomics, not the ecosystem — *yet*.
**Bring your own auth (and friends).** green-tea ships transport security — TLS/wss, secure-by-default headers, CORS — but **not** authentication, authorization, rate-limiting, CSRF, or sessions. You compose those as steps and plugins (the `Authenticate` step in the quick look is the pattern). Unlike Express/Fastify, there is no off-the-shelf plugin ecosystem for them yet.
**Node only.** Runs on Node ≥ 18. Deno / Bun / edge runtimes (over web-standard `Request`/`Response`) are on the roadmap, not built — only `src/http/` is runtime-specific today.
**mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet.
## Docs & development
@@ -207,7 +238,9 @@ npm run bench # regenerate BENCHMARKS.md
## Versioning
green-tea uses **calendar versioning**: `YY.MM.PATCH` (e.g. `26.07.0` = the first release cut in July 2026, patch 0). A version tells you *when* it shipped; breaking changes are called out in the [CHANGELOG](./CHANGELOG.md).
green-tea uses **calendar versioning**: `YY.MM.PATCH` (e.g. `26.07.0` = the first release cut in July 2026, patch 0). A version tells you *when* it shipped, not how many breaking changes preceded it — those are always called out in the [CHANGELOG](./CHANGELOG.md).
**While in beta**, releases carry a `-beta.N` pre-release suffix on the calendar version (e.g. `26.07.0-beta.0`) and publish under the npm `beta` dist-tag — so a plain `npm install @green-tea/core` won't pick one up until the first stable calendar release. The API can still change between betas.
## License
+7 -1
View File
@@ -165,6 +165,9 @@ bounded buffer (`channel({ buffer: 100 })`, drop-oldest).
A **teacup** can depend on a token that physically lives on a **teapot**. Exports are
opt-in (`export: true`) and the control channel is gated by a shared secret.
> ⚠️ **mesh is alpha** — its API and wire protocol may change. It's gated behind `experimental: true`;
> `createApp` throws if you pass `mesh` without it. Don't ship it to production yet.
**Node A — teapot (exposes `config`, `auth`, and a route):**
```typescript
@@ -180,7 +183,7 @@ class Svc { @Get('/ping', { export: true }) ping() { return { pong: true }; } }
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth], controllers: [Svc] })
class TeapotModule {}
const teapot = createApp({ modules: [TeapotModule], mesh: { secret: 'shh' } });
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'shh' } });
await teapot.listen(3002);
```
@@ -199,6 +202,7 @@ class TeacupModule {}
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: 'ws://A-host:3002/__mesh__/control', secret: 'shh' }] },
});
await teacup.listen(3003);
@@ -309,6 +313,8 @@ to the WebSocket handshake (101/upgrade) response.
## 8. File uploads / multipart
> Multipart parsing uses the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency — install it with `npm i busboy`. A `multipart/form-data` request to a server without busboy installed returns `501`. (JSON and urlencoded need nothing extra.)
A request with `Content-Type: multipart/form-data` makes `@body()` resolve to `{ fields, files }`
instead of a plain object:
+53
View File
@@ -0,0 +1,53 @@
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';
// Docs site for @green-tea/core. Content lives in src/content/docs/**.
export default defineConfig({
site: 'https://green-tea.dev',
integrations: [
starlight({
title: 'green-tea',
description: 'A calm, type-safe HTTP framework for Node — your API is an explicit dependency graph.',
tableOfContents: { minHeadingLevel: 2, maxHeadingLevel: 3 },
sidebar: [
{
label: 'Start here',
items: [
{ label: 'Introduction', link: '/' },
{ label: 'Getting started', slug: 'getting-started' },
],
},
{
label: 'Concepts',
items: [
{ label: 'The dependency graph', slug: 'concepts/the-graph' },
{ label: 'The typed flow core', slug: 'concepts/flow' },
],
},
{
label: 'Guides',
items: [
{ label: 'Routing', slug: 'guides/routing' },
{ label: 'Dependency injection', slug: 'guides/dependency-injection' },
{ label: 'Argument decorators', slug: 'guides/arguments' },
{ label: 'Validation', slug: 'guides/validation' },
{ label: 'Streaming & real-time', slug: 'guides/streaming' },
{ label: 'File uploads', slug: 'guides/uploads' },
{ label: 'Transport security', slug: 'guides/security' },
{ label: 'Plugins & observability', slug: 'guides/plugins' },
{ label: 'Graph introspection', slug: 'guides/introspection' },
{ label: 'Testing', slug: 'guides/testing' },
{ label: 'Mesh (alpha)', slug: 'guides/mesh', badge: { text: 'alpha', variant: 'caution' } },
],
},
{
label: 'Reference',
items: [
{ label: 'Decorators', slug: 'reference/decorators' },
{ label: 'createApp options', slug: 'reference/createapp' },
],
},
],
}),
],
});
+6866
View File
File diff suppressed because it is too large. Load diff
+15
View File
@@ -0,0 +1,15 @@
{
"name": "green-tea-docs",
"type": "module",
"private": true,
"scripts": {
"dev": "astro dev",
"build": "astro build",
"preview": "astro preview"
},
"dependencies": {
"@astrojs/starlight": "^0.41.3",
"astro": "^7.0.6",
"sharp": "^0.35.3"
}
}
+7
View File
@@ -0,0 +1,7 @@
import { defineCollection } from 'astro:content';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';
export const collections = {
docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
};
+24
View File
@@ -0,0 +1,24 @@
---
title: The typed flow core
description: "The functional flow API where the compile-time dependency guarantee lives."
---
The [decorator layer](/guides/dependency-injection/) validates the graph at **boot**. The functional core, `flow`, validates it in the **type checker** — before the program ever runs.
```typescript
import { flow } from '@green-tea/core';
const pipeline = flow()
.step('db', () => ({ find: (id: string) => id }))
.step('user', (ctx) => ctx.db.find('u1')); // referencing a missing 'db' would not compile
```
Each `.step(name, fn)` adds its output to the accumulated context **type** (`Acc & Out`). The next step's `ctx` is typed with everything produced so far — so reading `ctx.db` compiles only because a previous step provided `db`. Reference a key nothing produced and it is a **compile error**, not a runtime `undefined`.
This is the strongest guarantee green-tea offers: the type *is* the dependency contract, checked statically. The decorator layer gives you the same graph with boot-time validation and the ergonomics of classes and decorators; `flow` gives you compile-time proof.
:::note
`npm run typecheck` in the repo includes a type-level test that asserts this accumulation behaves — a step that reads a missing key is expected to fail compilation.
:::
See [The dependency graph](/concepts/the-graph/) for how both layers describe the same model.
@@ -0,0 +1,47 @@
---
title: The dependency graph
description: "How green-tea models the request and boot pipeline as an explicit dependency graph."
---
Most frameworks make you keep the whole request in your head: which middleware ran, whether `req.user` exists by now, what order things fire in, which plugin quietly deleted your body parser. That bookkeeping is where bugs live.
green-tea puts the request **on the page**. You declare what each unit **needs** and **produces**; the framework computes the order, checks the wiring, and can print the whole thing.
## needs / provides
Every node declares its inputs and outputs:
- A **provider** produces an app-scope value (a database handle, a config object) — resolved once at boot and cached.
- A **step** reads the request context and merges new keys into it (authentication producing `user`, say) — runs per request.
- A **handler** (a route method) declares, through its argument decorators, exactly which keys it depends on.
green-tea builds a directed graph from these declarations and **topologically sorts** it. You never write "put this before that" — order is derived from `needs`/`provides`.
```typescript
@Step({ provides: 'user', needs: ['db', 'req'] }) // user depends on db and req
class Authenticate { /* ... */ }
```
## Why it matters
- **No ordering bugs.** There's no positional `app.use()` sequence to get wrong; the sort is the order.
- **Each route runs only its slice.** A route runs the transitive closure of what its handler `@needs` (plus always-run observer steps) — an auth step doesn't run on a public route.
- **Boot fails loudly.** If a handler needs a key nothing provides, `createApp` throws at boot with a "did you mean…?" hint — you never serve `undefined`.
- **You can read it.** `app.explain(route)` prints the ordered chain with origins; `app.graph()` / `GET /__graph__` render it as a diagram. See [Graph introspection](/guides/introspection/).
## Two layers
green-tea exposes the graph two ways:
1. **The typed functional core, [`flow`](/concepts/flow/)** — the compile-time guarantee. A handler that reads `ctx.user` fails to **compile** if no step produces `user`.
2. **The declarative decorator layer** — `@Provider` / `@Step` / `@Module` / `@Route` / `@Get` plus [argument decorators](/guides/arguments/). Emits runtime metadata, builds and sorts the graph, and validates at boot.
Both describe the same graph; pick the ergonomics you want.
## Why legacy decorators
green-tea uses **legacy** (experimental) TypeScript decorators — set `experimentalDecorators: true` in your `tsconfig`. This is a design decision, not inertia.
The argument-injection API (`@param`, `@query`, `@body`, `@header`, `@needs`, `@ctx`, `@inbound`, `@abort`) relies on **parameter decorators**, and the TC39 standard decorators proposal (Stage 3) deliberately does **not** include them. There is no standards-track way to decorate a parameter today, so `handler(@param('id') id: string)` is only expressible with legacy decorators.
"Stage 3" also means *not finalized* — the proposal can still change before engines ship it. green-tea tracks it and will revisit if parameter injection ever gets a standard path. It does **not** rely on `emitDecoratorMetadata` / `design:type` reflection — argument positions are recorded explicitly — so this is the only legacy surface it depends on.
@@ -0,0 +1,84 @@
---
title: Getting started
description: Install green-tea, configure TypeScript decorators, and build your first graph-based route.
---
## Install
```bash
npm install @green-tea/core reflect-metadata
# optional, only if you use them:
npm install ws # WebSocket routes (@Ws) and mesh
npm install busboy # multipart/form-data file uploads
```
green-tea targets **Node ≥ 18** and uses **legacy** TypeScript decorators. Enable them in your `tsconfig.json`:
```json
{
"compilerOptions": {
"experimentalDecorators": true,
"target": "es2020",
"moduleResolution": "node"
}
}
```
You do **not** need `emitDecoratorMetadata` — green-tea records argument positions explicitly. See [Why legacy decorators](/concepts/the-graph/#why-legacy-decorators) for the rationale.
## Your first app
A provider produces a value, a step transforms the request context, and a controller handler declares exactly what it needs:
```typescript
import {
createApp, Provider, Step, Route, Get, Module,
Unauthorized, needs, param,
} from '@green-tea/core';
@Provider({ provides: 'db' })
class Database {
provide() {
const users = { u1: { id: 'u1', name: 'Diego' } };
return { db: { find: (token: string) => users[token] ?? null } };
}
}
@Step({ provides: 'user', needs: ['db', 'req'] })
class Authenticate {
run(ctx) {
const user = ctx.db.find(ctx.req.headers['x-token']);
if (!user) throw new Unauthorized('invalid token'); // cut the request
return { user }; // continue
}
}
@Route('/users')
class UserController {
@Get('/:id')
getUser(@needs('user') user, @param('id') id) { // the signature IS the contract
return { requested: id, you: user };
}
}
@Module({ mountpoint: '/api', providers: [Database], steps: [Authenticate], controllers: [UserController] })
class ApiModule {}
const app = createApp({ modules: [ApiModule] });
console.log(app.explain('/api/users/:id')); // auditable: the ordered chain, with origins
app.listen(3000);
```
```bash
curl -H 'x-token: u1' http://localhost:3000/api/users/9
# {"requested":"9","you":{"id":"u1","name":"Diego"}}
```
The handler asked for `user` via `@needs('user')`. If nothing in the graph produced `user`, `createApp` would **throw at boot** with a "did you mean…" hint — you never serve `undefined`.
## Where to next
- [The dependency graph](/concepts/the-graph/) — the mental model behind everything.
- [Dependency injection](/guides/dependency-injection/) — providers, steps, and modules in depth.
- [Argument decorators](/guides/arguments/) — everything a handler can inject.
- [Streaming & real-time](/guides/streaming/) — SSE, WebSocket, and ndjson from one primitive.
@@ -0,0 +1,148 @@
---
title: Argument decorators
description: "Everything a handler can inject with needs, ctx, param, query, body, header, inbound, and abort."
---
A handler's signature declares exactly what it wants — in any order, nothing more. Each
parameter decorator injects one thing: a graph-produced value, part of the request envelope,
or a stream handle. Some decorators add a **dependency edge** to the graph (boot-validated);
most just read from the request.
## The decorators at a glance
| Decorator | Injects | Adds a graph dependency? | Forms |
|---|---|---|---|
| `@needs('user')` | a value produced by a provider/step (boot-validated) | **yes** | `('key')` |
| `@ctx()` | the whole accumulated context | no | `()` |
| `@param(...)` | route params | no | `()` · `('id')` · `('id', schema)` |
| `@query(...)` | parsed query string | no | `()` · `('q')` · `(['a','b'])` · `(schema)` |
| `@body(...)` | parsed body (JSON / urlencoded / multipart) | no | `()` · `('field')` · `(schema)` |
| `@headers(...)` | request headers (whole bag or picked) | no | `()` · `('authorization')` · `(['a','b'])` · `(schema)` |
| `@header('name')` | one request header (singular alias of `@headers`) | no | `('x-trace')` · `('x-count', schema)` |
| `@inbound()` | the incoming WS message channel | no (WS only) | `()` |
| `@abort()` | an `AbortSignal` that fires on disconnect | no (stream/WS) | `()` |
## `@needs` — a graph-produced value
`@needs('token')` injects a value a provider or step produces, and declares a dependency edge
in the graph. Its keys are **validated at boot**: if nothing provides the token, `createApp`
throws with a clear error instead of serving `undefined`.
```typescript
getUser(@needs('user') user: any, @param('id') id: string) {
return { requested: id, you: user };
}
```
See [Dependency injection](/guides/dependency-injection/) for how `needs`/`provides` build the
graph.
## `@ctx` — the whole context
`@ctx()` hands you the entire accumulated context — everything providers and steps have merged
in, plus built-ins. Use it to read values like `ctx.protocol` and `ctx.ip` (populated when
`trustProxy` is on).
## Envelope decorators — `@param`, `@query`, `@body`, `@headers`
These read from the parsed request. Each envelope decorator has **three access forms**:
- `@query()` — the whole object
- `@query('q')` — one key
- `@query(['q','date'])` — a subset
```typescript
@Get('/:id')
getUser(@param('id') id: string) { /* ... */ }
```
- **`@param`** reads route params. It always needs a name to say which param it binds
(`@param('id')`).
- **`@query`** reads the parsed query string. Query values are always strings on the wire — a
schema is often the coercion point (see below).
- **`@body`** reads the parsed body. It handles `application/json`,
`application/x-www-form-urlencoded`, and `multipart/form-data` (see the multipart note).
- **`@headers`** reads request headers — the whole bag (`@headers()`), one key
(`@headers('authorization')`), or a subset (`@headers(['a','b'])`).
## `@header` — one header, singular alias
`@header('name')` is the singular alias of `@headers`: it picks exactly one request header.
```typescript
who(@header('x-trace') trace: string) { /* ... */ }
```
It also accepts a schema in slot 2 — `@header('x-count', schema)`.
## Schema forms — validation & coercion
`@body`, `@query`, `@headers`, and `@param` accept an optional **Standard Schema** (zod,
valibot, arktype, …). The value the handler receives is the schema's **parsed/coerced output**,
already typed:
```typescript
create(@body(CreateUser) user: { email: string }) {
return { created: user.email };
}
```
:::note[Access shape (asymmetry)]
`@param('id', Schema)` takes the **key in slot 1** and the schema in slot 2 — `@param` always
needs a name to say which route param it binds. `@body(Schema)`, `@query(Schema)`, and
`@headers(Schema)` take the schema as their **only** argument, validating the whole parsed
object.
:::
A failing schema short-circuits the request with **422**. See [Validation](/guides/validation/)
for the full contract (fail-fast order, error shape, async schemas, and caveats).
## Multipart access asymmetry
A request with `Content-Type: multipart/form-data` makes `@body()` resolve to `{ fields, files }`
instead of a plain object.
:::caution[Access note]
For multipart, `@body('title')` returns `undefined` — the value lives at `body.fields.title`,
not `body.title`, unlike JSON/urlencoded where `@body('title')` picks the value directly. Use
`@body()` and read `.fields` / `.files`, or key into the envelope itself with `@body('fields')`
/ `@body('files')`.
:::
```typescript
upload(@body() form: MultipartBody) {
const name = form.fields.name; // string | string[]
const avatar = form.files.avatar; // UploadedFile | UploadedFile[]
return { name, size: Array.isArray(avatar) ? undefined : avatar?.size };
}
```
## Stream decorators — `@inbound` and `@abort`
These are for streaming handlers:
- **`@inbound()`** (WS only) gives you the incoming WebSocket message channel — the client's
messages to consume. A `@Ws` handler returns the **outbound** channel.
- **`@abort()`** (stream / WS) hands you an `AbortSignal` that fires on disconnect, so you can
tear down work when the client goes away.
```typescript
@Ws('/echo')
echo(@inbound() incoming: AsyncIterable<string>) {
const out = channel<string>();
(async () => {
for await (const msg of incoming) out.push(`echo: ${msg}`);
out.close();
})();
return out;
}
```
See [Streaming](/guides/streaming/) for SSE, WebSocket duplex, and channels.
## Where to go next
- How injected values are produced: [Dependency injection](/guides/dependency-injection/).
- The mental model: [The graph](/concepts/the-graph/).
- Validating and coercing injected values: [Validation](/guides/validation/).
- The full API surface: [Decorator reference](/reference/decorators/).
@@ -0,0 +1,146 @@
---
title: Dependency injection
description: "Providers, steps, and modules, and how values flow through the graph."
---
In green-tea the request pipeline is an explicit **dependency graph**. You declare what each
piece needs and produces; the framework computes the order, validates the wiring at boot, and
runs only the slice a route actually depends on. You never write "put this before that."
There are three building blocks:
- A **provider** is an app-scope singleton — constructed once, its value memoized for the
lifetime of the app.
- A **step** runs per request and transforms the context.
- A **module** sets a mountpoint and wires providers, steps, and controllers together.
A handler's **argument decorators are its dependency declaration** — ask for what you want, in
any order. If you `@needs` a token nothing produces, you get a **boot error**, not an
`undefined` at runtime.
## The full example
```typescript
import 'reflect-metadata';
import { createApp, Provider, Step, Route, Get, Module, Unauthorized, needs, param } from '@green-tea/core';
@Provider({ provides: 'db' })
class Database {
provide() { return { db: { find: (id: string) => ({ id, name: 'Diego' }) } }; }
}
@Step({ provides: 'user', needs: ['db', 'req'] })
class Authenticate {
run(ctx: any) {
const user = ctx.db.find(ctx.req.headers['x-token']);
if (!user) throw new Unauthorized('bad token'); // throw = short-circuit the pipeline
return { user }; // return = continue, merge into ctx
}
}
@Route('/users')
class UserController {
@Get('/:id')
getUser(@needs('user') user: any, @param('id') id: string) {
return { requested: id, you: user }; // auto-serialized as JSON
}
}
@Module({ mountpoint: '/api', providers: [Database], steps: [Authenticate], controllers: [UserController] })
class ApiModule {}
const app = createApp({ modules: [ApiModule] });
await app.listen(3000);
// GET /api/users/9 (header x-token) → { "requested": "9", "you": { "id": "...", "name": "Diego" } }
await app.close(); // graceful shutdown: drains in-flight requests, closes streams + mesh links
```
## `@Provider` — app-scope, memoized
A provider produces a value once, when the app boots, and reuses it for every request. Its
`provide()` method returns an object whose keys become tokens in the graph — here `db`.
```typescript
@Provider({ provides: 'db' })
class Database {
provide() { return { db: { find: (id: string) => ({ id, name: 'Diego' }) } }; }
}
```
Because it's app-scope, a provider is the right home for things you build once and share:
database clients, config, connection pools.
:::note
An optional provider (`optional: true`) that throws on boot does **not** abort startup — it is
left unregistered and logged, and the failure surfaces at request time for routes that need it.
Query the degraded set with `app.degraded()` or listen for the `boot:provider:fail` bus event.
:::
## `@Step` — request-scope, transforms the context
A step runs once per request. Its `run(ctx)` receives the accumulated context and either:
- **returns an object** → the pipeline continues and the object is merged into `ctx`, or
- **throws** → the request short-circuits (here `Unauthorized` becomes a `401`).
```typescript
@Step({ provides: 'user', needs: ['db', 'req'] })
class Authenticate {
run(ctx: any) {
const user = ctx.db.find(ctx.req.headers['x-token']);
if (!user) throw new Unauthorized('bad token'); // throw = short-circuit the pipeline
return { user }; // return = continue, merge into ctx
}
}
```
This step `provides: 'user'` and `needs: ['db', 'req']` — so green-tea knows the `db` provider
and the built-in `req` must resolve before it runs, and it topologically sorts accordingly.
## How `needs` / `provides` build the graph
Every node declares what it **produces** (`provides`) and what it **consumes** (`needs`). The
framework reads those declarations and computes a topological order — you never specify
ordering by hand. A handler's argument decorators extend the same graph: `@needs('user')` on a
parameter is a dependency edge exactly like a step's `needs`.
Because the graph is explicit, **each route runs only the transitive closure of its handler's
`@needs`** — nothing else.
:::caution[Per-route execution]
A route that doesn't `@needs('user')` does **not** run the `Authenticate` step. A cross-cutting
*enforcement* step (e.g. auth that throws `401`) only protects routes that actually `@needs`
its token. To run something on **every** route regardless of needs (logging, audit, a global
guard), add it as a **plugin step** via `scope.add({ ..., provides: [] })` — steps that produce
nothing run unconditionally. Don't rely on a token-providing step to guard routes that don't
declare it.
:::
## `@Module` — mountpoint and wiring
A module ties everything together: a `mountpoint` prefix for the routes, and the lists of
`providers`, `steps`, and `controllers` that belong to it.
```typescript
@Module({ mountpoint: '/api', providers: [Database], steps: [Authenticate], controllers: [UserController] })
class ApiModule {}
```
Pass modules to `createApp({ modules: [ApiModule] })` to assemble the app.
## Boot validation of `@needs`
The payoff of declaring dependencies is that the wiring is checked before a single request is
served. When you `@needs` a token, green-tea verifies some provider or step actually produces
it. If nothing does, **`createApp` throws with a clear error** instead of letting your handler
receive `undefined`. Boot fails loudly, so you never serve `undefined`.
## Where to go next
- New to green-tea? Start with [Getting started](/getting-started/).
- The mental model behind all of this: [The graph](/concepts/the-graph/).
- Everything a handler can inject: [Argument decorators](/guides/arguments/) and the
[decorator reference](/reference/decorators/).
- Coerce and validate injected values with Standard Schema: [Validation](/guides/validation/).
- Return an `AsyncIterable` to push data over time: [Streaming](/guides/streaming/).
@@ -0,0 +1,55 @@
---
title: Graph introspection
description: "explain, graph, toMermaid, and the graph endpoint."
---
Because the request/boot pipeline is an explicit [dependency graph](/concepts/the-graph/),
you can inspect it directly — visualize the whole thing, or explain exactly which nodes a
single route runs.
## Visualize with Mermaid
`app.toMermaid()` renders a flowchart of every node and route. `app.toDOT()` produces the
same graph as Graphviz DOT.
```typescript
console.log(app.toMermaid()); // flowchart diagram of all nodes and routes
```
Enable a live `GET /__graph__` endpoint — it renders an HTML viewer with Mermaid, or the
raw Mermaid source with `Accept: text/plain`:
```typescript
const app = createApp({ modules: [ApiModule], devGraph: true });
// GET /__graph__ → HTML viewer
// GET /__graph__ (text/plain) → raw Mermaid source
```
:::caution
`devGraph` exposes your graph structure over HTTP. Keep it on in development; leave it off
in production.
:::
## Explain a route
`app.explain(route)` returns the exact execution chain for one route — the ordered nodes,
each with its kind, origin, and declared `needs`/`provides`:
```typescript
const e = app.explain('/api/users/:id');
// { pattern, method, transport, chain: [{ name, kind, origin, needs, provides }, ...] }
console.log(e.chain.map((n) => `${n.kind}:${n.name}`));
// → ['provider:db', 'step:user', 'handler:getUser']
```
The chain is the transitive closure of the handler's `@needs` — the same set the framework
actually runs for that route, and nothing more.
`app.graph()` returns the underlying graph structure programmatically if you'd rather walk
it yourself than render it.
## Degraded optional providers
`app.degraded()` returns the names of optional providers that are running in a **degraded**
state — for example, an optional dependency that failed to initialize but didn't abort boot.
Use it as a health signal to surface partial availability.
+67
View File
@@ -0,0 +1,67 @@
---
title: Mesh (alpha)
description: "Distributed dependency injection over a secret-gated WebSocket control channel."
---
:::caution[Alpha]
Mesh is **alpha** — its API and wire protocol may change between releases, and discovery, load-balancing, and failover are not built. It is gated behind an explicit opt-in: `createApp({ mesh, experimental: true })`, and `createApp` **throws** if you configure `mesh` without `experimental: true`. **Don't ship mesh to production yet.**
:::
A **teacup** can depend on a token that physically lives on another node — a **teapot**. `@needs('billing')` resolves the same whether `billing` runs in this process or on a remote one. There's no gRPC layer or message-pattern DSL: there's the [graph](/concepts/the-graph/), and some nodes happen to live elsewhere.
Exports are opt-in (`export: true`) and the control channel is gated by a shared secret.
## Node A — teapot (exposes `config`, `auth`, and a route)
```typescript
@Provider({ provides: 'config', export: true })
class Config { provide() { return { config: { region: 'mx', tier: 'pro' } }; } }
@Step({ provides: 'auth', needs: [], export: true })
class Auth { run(ctx: any) { return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; } }
@Route('/svc')
class Svc { @Get('/ping', { export: true }) ping() { return { pong: true }; } }
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth], controllers: [Svc] })
class TeapotModule {}
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'shh' } });
await teapot.listen(3002);
```
## Node B — teacup (uses `config` + `auth` with no local providers)
```typescript
@Route('/local')
class LocalCtl {
@Get('/who')
who(@needs('config') config: any, @needs('auth') auth: any) {
return { config, auth }; // both resolved by RPC to the teapot
}
}
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: 'ws://A-host:3002/__mesh__/control', secret: 'shh' }] },
});
await teacup.listen(3003);
// GET B:3003/api/local/who (x-token: abc)
// → { "config": { "region": "mx", "tier": "pro" }, "auth": { "token": "abc" } }
```
## How it resolves
`@needs('config' | 'auth')` validates at boot because the teapot announced them in its **manifest** on connect. Scope determines the RPC cost:
- A **provider** export is **app-scope** — resolved once and cached.
- A **step** export is **request-scope** — one RPC per request, carrying the request envelope.
Remote tokens become synthetic nodes in the local graph with RPC-backed runners, so the rest of the pipeline is unchanged. For non-mesh apps `createApp` stays synchronous; mesh apps defer graph finalization to `listen()` so remote scopes can join first.
:::note[Skeleton limitations (by design)]
No discovery, load-balancing, or failover yet; app-scope remote values are not reconciled on reconnect; the request envelope omits `req.url`.
:::
@@ -0,0 +1,58 @@
---
title: Plugins & observability
description: "Extending the app safely via bus.on and scope.add."
---
A plugin is a function that receives the app's API at boot. It gets exactly two
capabilities: **observe** the running system through `bus.on(...)`, and **extend its own
scope** through `scope.add(...)`. That's the whole surface — and it's deliberately narrow.
```typescript
const logger = (api: any) => {
api.bus.on('request:step:enter', (p: any) => console.log(`→ ${p.name}`));
api.bus.on('stream:open', (p: any) => console.log(`stream open ${p.name}`));
api.bus.on('mesh:rpc:error', (p: any) => console.error('mesh rpc failed', p.error));
};
const app = createApp({ modules: [ApiModule], plugins: [logger] });
```
## Isolation is structural
A plugin can add steps and providers to **its own scope** via `scope.add(...)`. It
**cannot** reorder or delete another scope's steps. The graph — not a policy check —
enforces this: each scope owns its nodes, and a plugin has no handle on anyone else's.
There's no ordering hook to abuse and no step registry to mutate. If you want a plugin to
influence execution, it does so by contributing a node with declared `needs`/`provides`,
and the framework computes where that node lands.
:::note
Because execution is per-route (a route runs only the transitive closure of its handler's
`@needs`), a plugin step that should run on **every** route must produce nothing — add it
with `provides: []`. A step that produces no token has nothing to gate on, so the framework
runs it unconditionally. See [The graph](/concepts/the-graph/) for how the closure is
computed.
:::
## Lifecycle & request events
Subscribe to events on the `Bus` to observe boot, per-request execution, streaming, and
mesh activity without touching the pipeline itself:
```typescript
api.bus.on('boot:provider:ready', (p: any) => { /* ... */ });
api.bus.on('request:step:enter', (p: any) => { /* ... */ });
api.bus.on('request:step:exit', (p: any) => { /* ... */ });
```
The full event vocabulary:
- `boot:provider:*` — provider lifecycle during boot
- `request:step:*` — a step entering/exiting during a request
- `stream:open | stream:close | stream:error` — SSE/WS stream lifecycle
- `mesh:connect | mesh:disconnect | mesh:rpc:error` — mesh link and RPC activity
- `plugin:mounted` — a plugin finished mounting
Observation is read-only: handlers see the event payload but can't alter control flow. To
change behavior, contribute a node to your scope — see
[Dependency injection](/guides/dependency-injection/).
@@ -0,0 +1,64 @@
---
title: Routing
description: "Route patterns, the catch-all, specificity precedence, and 405 handling."
---
Routes are declared with method decorators on a `@Route`-prefixed controller. Patterns are matched **by segment**.
## Method decorators
| Decorator | Method / transport |
|---|---|
| `@Get` `@Post` `@Put` `@Patch` `@Delete` | 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` |
```typescript
@Route('/users')
class Users {
@Get('/:id') get(@param('id') id: string) { /* ... */ }
@Post('/') create(@body() data: unknown) { /* ... */ }
}
```
The path a route matches is `joinPath(module.mountpoint, route.path)` — a controller under `@Module({ mountpoint: '/api' })` with `@Route('/users')` + `@Get('/:id')` serves `/api/users/:id`.
## Pattern segments
- **Static** — `users` matches exactly.
- **`:param`** — matches exactly one segment; the decoded value lands in `params.name` (`@param('id')`).
- **`:name*` catch-all** — a trailing segment that captures the **rest of the path, slashes included**, into `params.name`.
```typescript
@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 = ""`).
## 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.
```typescript
@Get('/a/b') // wins for /a/b
@Get('/a/:id') // wins for /a/x
@Get('/a/:rest*') // wins for /a/x/y
```
## 404 vs 405
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](/guides/security/).
:::
## 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.
See [Streaming & real-time](/guides/streaming/) for `@Sse` / `@Ws` / `@Stream`, and [Argument decorators](/guides/arguments/) for everything a handler can read from a request.
+101
View File
@@ -0,0 +1,101 @@
---
title: Transport security
description: "TLS and wss, secure-by-default headers, CORS, and trustProxy."
---
Four `createApp` options cover TLS, proxying, CORS, and response headers: `tls`,
`trustProxy`, `cors`, and `security`. See the [`createApp` reference](/reference/createapp/)
for the full option list.
## TLS (native https/wss)
```typescript
import { readFileSync } from 'fs';
const app = createApp({
modules: [App],
tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') },
});
```
When `tls` is set the server serves https, and WebSocket upgrades become wss on the same
port — no other changes.
## `trustProxy`
```typescript
const app = createApp({ modules: [App], trustProxy: true });
```
Behind a reverse proxy, reads `X-Forwarded-Proto` / `X-Forwarded-For` to populate
`ctx.protocol` (`'http' | 'https'`) and `ctx.ip` (read via `@ctx()`). Off by default —
forwarded headers are ignored (and spoofable) until you opt in. It trusts the immediate hop
unconditionally; there's no CIDR allowlist yet.
## CORS
Off unless `origins` is set.
```typescript
const app = createApp({
modules: [App],
cors: { origins: 'https://app.example.com', credentials: true },
});
```
`origins` accepts `string | string[] | '*' | (origin) => boolean`. A preflight `OPTIONS`
request (with `Access-Control-Request-Method`) is auto-answered with 204.
- With `credentials: true`, the server **never** sends `Access-Control-Allow-Origin: *` — it
echoes the concrete allowed origin (or blocks the request).
:::caution[Reflect-any foot-gun]
`origins: '*'` together with `credentials: true` reflects *any* origin with credentials
attached. Only combine them if you truly intend an open credentialed API; prefer an explicit
allowlist.
:::
## `security` (headers, ON by default)
Applied to every HTTP response. Disable everything with `security: false`, or override
individual headers with an options object.
| Header | Default |
|---|---|
| `X-Content-Type-Options` | `nosniff` |
| `X-Frame-Options` | `SAMEORIGIN` |
| `Referrer-Policy` | `no-referrer` |
| `X-DNS-Prefetch-Control` | `off` |
| `Strict-Transport-Security` | `max-age=15552000` (180d) — **only when the connection is secure** (native TLS, or `trustProxy` + `X-Forwarded-Proto: https`); no `includeSubDomains`/`preload` |
| `Content-Security-Policy` | not set — pass `security: { csp: "..." }` |
```typescript
const app = createApp({ modules: [App], security: { csp: "default-src 'self'" } });
```
:::note[Scope caveat]
`security` and `cors` headers apply to HTTP responses; they do **not** apply to the
WebSocket handshake (101/upgrade) response.
:::
:::caution[TLS + trustProxy]
HSTS is emitted only when the connection is judged secure. With `trustProxy: true` that
judgement trusts the incoming `X-Forwarded-Proto` header — so a client that spoofs
`X-Forwarded-Proto: http` past a permissive proxy can make the server treat the request as
insecure and **suppress the HSTS header**. Only enable `trustProxy` behind a proxy that
strips and sets forwarded headers itself, and terminate TLS where you control that hop.
:::
## Defaults
| Option | Default |
|---|---|
| `tls` | off (plain http/ws) |
| `trustProxy` | off |
| `cors` | off (same-origin only) |
| `security` | ON (HSTS only when the connection is secure) |
## Related
- [`createApp` reference](/reference/createapp/) — every construction option
- [File uploads / multipart](/guides/uploads/) — request-body handling
@@ -0,0 +1,114 @@
---
title: Streaming & real-time
description: "SSE, ndjson, and WebSocket duplex from one AsyncIterable primitive."
---
Most stacks treat "push data over time" as a bolt-on: Express reaches for a `ws` or SSE library, Fastify for a plugin, NestJS for a separate **WebSocket Gateway** with its own adapter and decorators. That's a second mental model, a second error surface, glued to your HTTP app.
green-tea has one model: an **`AsyncIterable`**. A handler that returns a sequence of values over time *is* a stream — the same shape you'd return from any function. You **declare the mode** with a decorator; the framework handles framing, backpressure, cleanup, and disconnects.
## One primitive, four modes
| Declare | Direction | Transport | Reach for it when |
|---|---|---|---|
| `@Sse` | server → client | `text/event-stream` | live updates to a browser (`EventSource`) |
| `@Ws` | duplex | WebSocket | chat, collaboration — anything two-way |
| `@Stream` | negotiated | SSE / ndjson / WS, picked from the client's `Accept` / `Upgrade` | one handler, the client chooses |
| *(plain return)* | server → client | SSE or ndjson by `Accept` | programmatic streaming over `fetch` |
The primitive never changes — it's always an `AsyncIterable`. What changes is **direction and framing**, and you declare which. That's the difference between each iterable green-tea hands you:
- **`@Sse` / plain return** — you return **one** iterable: the *outbound* stream. Each `yield` becomes an SSE event, or an ndjson line.
- **`@Ws` (duplex)** — **two** iterables. `@inbound()` gives you the client's *incoming* messages to consume; the one you **return** is the *outbound* stream to the client. `@abort()` hands you an `AbortSignal` for teardown.
- **`@Stream`** — you write the handler once; the client's request decides whether it arrives as SSE, ndjson, or a WebSocket. No branching in your code.
:::note
Streaming bypasses the response transformer — the transport frames each value directly, handles backpressure, and cleans up on disconnect. See [arguments](/guides/arguments/) for the full list of argument decorators, including the stream-only `@inbound()` and `@abort()`.
:::
## Streaming — SSE
Return an `AsyncIterable` and the pipeline streams it (the transformer is bypassed; the transport frames it, handles backpressure, and cleans up on disconnect).
```typescript
import { Route, Sse } from '@green-tea/core';
@Route('/feed')
class FeedController {
@Sse('/ticks')
ticks() {
return (async function* () {
for (let n = 1; n <= 3; n++) yield { tick: n };
})();
}
}
// GET /feed/ticks (Accept: text/event-stream)
// data: {"tick":1}
// data: {"tick":2}
// data: {"tick":3}
```
`@Stream(path)` negotiates the transport by header (`Accept: text/event-stream` → SSE, `Upgrade: websocket` → WS, else ndjson chunked).
## Streaming — WebSocket duplex
A WS handler receives the **inbound** channel and returns the **outbound** channel — a step that consumes one channel and produces another.
```typescript
import { Route, Ws, inbound, channel } from '@green-tea/core';
@Route('/chat')
class ChatController {
@Ws('/echo')
echo(@inbound() incoming: AsyncIterable<string>) {
const out = channel<string>();
(async () => {
for await (const msg of incoming) out.push(`echo: ${msg}`);
out.close();
})();
return out;
}
}
```
`channel<T>()` is a multicast `AsyncIterable` with `push` / `close` / `fail` and an optional bounded buffer (`channel({ buffer: 100 })`, drop-oldest).
:::note[WebSocket needs the `ws` peer]
`@Ws` (and mesh) require the optional [`ws`](https://github.com/websockets/ws) peer dependency — `npm i ws`. SSE, ndjson, and plain HTTP need nothing extra.
:::
## Fan-out — `channel()` and `rooms`
Fan-out is a primitive too: `channel()` is a **multicast** `AsyncIterable` (bounded, drop-oldest) so one source feeds many subscribers, and `rooms` are named broadcast hubs — publish once, every connection in the room receives it.
```typescript
@Route('/live')
class Live {
@Sse('/prices') // one iterable out — each yield is an event
prices() {
return (async function* () {
while (true) { yield { btc: await getPrice() }; await sleep(1000); }
})();
}
@Ws('/echo') // duplex — consume @inbound, return the outbound stream
echo(@inbound() incoming: AsyncIterable<string>) {
const out = channel<string>();
(async () => { for await (const m of incoming) out.push(`echo: ${m}`); out.close(); })();
return out;
}
}
```
Same `@Route`, same handler shape, same `AsyncIterable` — real-time is not a separate framework you also have to learn.
`rooms` is the built-in shared `Rooms` primitive (one instance app-wide). A typical chat handler pumps the `@inbound()` channel into `rooms.room(name)` and returns that same room as its outbound channel, so every joined socket multicasts to the others. A handshake `@Step` can read `?token=` and throw `Unauthorized` — which closes the socket with code **4401** (`4000 + status`). See [security](/guides/security/) for handshake authentication.
## The one rule to remember
```
return a VALUE → buffered response (transformer → JSON)
return an AsyncIterable → stream (SSE / WS)
```
Return a value and you get a buffered JSON response; return an `AsyncIterable` and you get a stream. That's the whole contract.
@@ -0,0 +1,33 @@
---
title: Testing
description: "Swap any node with createApp overrides for fast, isolated tests."
---
Any provider or step is addressable by its **token**, so you can swap it for a test double
at construction time — no monkey-patching, no module rewiring.
## Override tokens in tests
Pass `overrides` to `createApp`. Each key is a token; each value is either a plain object
(wrapped as `{ token: value }`) or a function runner:
```typescript
const app = createApp({
modules: [ApiModule],
overrides: {
db: { find: () => ({ id: 'test-user' }) }, // plain object — wrapped as { db: value }
user: () => ({ user: { id: 'stub' } }), // function runner
},
});
```
Overrides replace **only** the named token's runner; the rest of the graph is untouched. The
route still runs its full closure — you've just substituted what one node produces.
:::note
An override for an unknown token throws. The set of tokens is validated against the real
graph, so a typo'd or stale override is a construction-time error, not a silent no-op.
:::
This pairs well with [`app.explain(route)`](/guides/introspection/) — explain the chain to
see which tokens a route actually depends on, then override exactly those.
@@ -0,0 +1,64 @@
---
title: File uploads
description: "multipart parsing via the optional busboy peer dependency."
---
A request with `Content-Type: multipart/form-data` makes `@body()` resolve to `{ fields, files }` instead of a plain object.
:::caution[multipart needs the optional `busboy` peer]
Multipart parsing uses the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency — install it with `npm i busboy`. A `multipart/form-data` request to a server without busboy installed returns **`501`**. (JSON and urlencoded need nothing extra.)
:::
```typescript
import { Route, Post, body } from '@green-tea/core';
import type { MultipartBody } from '@green-tea/core';
@Route('/profile')
class ProfileController {
@Post('/avatar')
upload(@body() form: MultipartBody) {
const name = form.fields.name; // string | string[]
const avatar = form.files.avatar; // UploadedFile | UploadedFile[]
return { name, size: Array.isArray(avatar) ? undefined : avatar?.size };
}
}
```
`UploadedFile` is `{ filename, contentType, data: Buffer, size }` — the whole file is buffered in memory, no temp files.
:::note[Access asymmetry]
For multipart, `@body('title')` returns `undefined` — the value lives at `body.fields.title`, not `body.title`, unlike JSON/urlencoded where `@body('title')` picks the value directly. Use `@body()` and read `.fields`/`.files`, or key into the envelope itself with `@body('fields')` / `@body('files')`. See [arguments](/guides/arguments/) for how `@body()` behaves across content types.
:::
## Repeated fields — `bodyDuplicates`
By default, a repeated field name keeps the **last** value (`'last'`, matching urlencoded). Set `bodyDuplicates: 'array'` on `createApp` to accumulate repeats into a `string[]` instead — this applies to **both** urlencoded and multipart text fields:
```typescript
const app = createApp({ modules: [ApiModule], bodyDuplicates: 'array' });
```
Files under a repeated field name always become an array (`UploadedFile[]`), regardless of `bodyDuplicates`.
## Per-endpoint override
```typescript
@Post('/upload', { duplicates: 'array' })
upload(@body() form: MultipartBody) { /* ... */ }
```
Precedence: route `duplicates` → app `bodyDuplicates` → `'last'`.
## Limits
Uploaded files are held in memory, so they're bounded by the same `maxBodyBytes` limit as any other request body (over the limit → **413**). `maxParts` (default `1000`) caps the number of multipart parts per request:
```typescript
const app = createApp({ modules: [ApiModule], limits: { maxParts: 500 } });
```
A malformed multipart body (bad boundary, missing headers, truncated part) → **400**.
:::note
To validate parsed fields against a schema, pass a Standard Schema to `@body()` — see [validation](/guides/validation/).
:::
@@ -0,0 +1,84 @@
---
title: Validation
description: "Validate and coerce input with Standard Schema (zod, valibot, arktype)."
---
`@body`, `@query`, `@headers`, and `@param` accept an optional **Standard Schema**
(the [`~standard` interface](https://standardschema.dev) shared by zod, valibot, arktype,
and others). green-tea's core has **zero runtime dependency** on any of them — bring
whichever validator you already use.
```typescript
import { z } from 'zod';
import { Route, Post, body } from '@green-tea/core';
const CreateUser = z.object({ email: z.string().email() });
@Route('/users')
class UserController {
@Post('/')
create(@body(CreateUser) user: { email: string }) {
return { created: user.email };
}
}
```
## Parsed value replaces the argument; `ctx` stays raw
The value the handler receives is the schema's **parsed/coerced output**, not the raw
input — `ctx.body` (via `@ctx()` or a `@needs`-fed step) stays exactly what the transport
parsed. Query strings are always strings on the wire, so a schema is often the coercion
point:
```typescript
const ListQuery = z.object({ page: z.coerce.number() });
@Get('/list')
list(@query(ListQuery) q: { page: number }) {
return { page: q.page, isNum: typeof q.page === 'number' }; // GET /list?page=2 → true
}
```
## Where the schema goes (the one asymmetry)
:::note[Access shape]
`@param('id', Schema)` takes the key in slot 1 and the schema in slot 2 — `@param` always
needs a name to say which route param it binds. `@body(Schema)`, `@query(Schema)`, and
`@headers(Schema)` take the schema as their **only** argument, validating the whole parsed
object (all of `body`/`query`/`headers`).
:::
See [Argument decorators](/guides/arguments/) for the full slot semantics of each decorator.
## Failure: 422 with per-field issues
A failing schema short-circuits the request with **422**:
```json
{ "error": "Validation failed", "source": "body", "issues": [{ "path": "email", "message": "Invalid email" }] }
```
`source` is which envelope failed (`'body' | 'query' | 'params' | 'headers'`); `issues` is
the schema's issues flattened to `{ path, message }` (`path` is dot-joined).
## Caveats
- **Fail-fast.** Arguments validate in order; the **first** failing one throws — later args in
the same handler are not checked in that request.
- **Steps see raw input.** Only the resolved handler argument is coerced/validated; a `@Step`
reading the same data via `ctx.body`/`ctx.query`/etc. always sees the untouched value.
- **A throwing schema is a 500, not a 422.** The Standard Schema contract says `validate()`
returns `{ issues }` on failure — it isn't supposed to throw. If it does anyway, that
propagates as an uncaught error (→ 500), since it signals a bug in the schema, not user input.
- **Async schemas are awaited** — `validate()` returning a `Promise` works transparently.
:::note[Not covered yet]
Response/output validation, validating a `@Step`'s own inputs, and mesh remote-route
validation are all out of scope for this feature.
:::
## Related
- [Argument decorators](/guides/arguments/) — every slot decorator and its parsing rules
- [File uploads / multipart](/guides/uploads/) — how multipart bodies are parsed before validation
- [`createApp` reference](/reference/createapp/) — app construction options
+41
View File
@@ -0,0 +1,41 @@
---
title: green-tea
description: A calm, type-safe HTTP framework for Node — your API is an explicit dependency graph you can see, slice, and trust.
template: splash
hero:
tagline: Your API is an explicit dependency graph you can see, slice, and trust — not a mutable bag threaded through positional middleware.
actions:
- text: Get started
link: /getting-started/
icon: right-arrow
variant: primary
- text: The idea
link: /concepts/the-graph/
icon: open-book
variant: minimal
---
import { Card, CardGrid } from '@astrojs/starlight/components';
## Less to hold in your head
Most frameworks make you keep the whole request in your head: which middleware ran, whether `req.user` exists by now, what fired in what order. green-tea puts the request **on the page** — you declare what each step _needs_ and _produces_, and the framework computes the order, type-checks the wiring, and can print the whole thing.
<CardGrid stagger>
<Card title="A graph, not a chain" icon="puzzle">
Declare `needs`/`provides`; green-tea topologically sorts it. No ordering bugs, no positional guesswork — each route runs only its slice of the graph.
</Card>
<Card title="The type is the contract" icon="approve-check">
In the typed `flow` core, a handler that reads `ctx.user` **fails to compile** if no step produces `user`. "It was undefined in prod" disappears at build time.
</Card>
<Card title="See the request before it runs" icon="magnifier">
`app.explain('/users/:id')` prints the ordered chain; `GET /__graph__` renders it as a live diagram. Onboarding and audits are reading, not archaeology.
</Card>
<Card title="One primitive for real-time" icon="rocket">
Return an `AsyncIterable` and the transport streams it — SSE, ndjson, or a WebSocket duplex — with backpressure and cleanup handled. No separate gateway.
</Card>
</CardGrid>
:::note[Beta]
green-tea is **beta**, on the RC track. One runtime dependency (`reflect-metadata`); `ws` and `busboy` are optional peers. [mesh](/guides/mesh/) is alpha and gated behind an explicit opt-in.
:::
@@ -0,0 +1,70 @@
---
title: createApp options
description: "Every option accepted by createApp and every method on the App it returns."
---
```typescript
const app = createApp(options);
```
## Options
| Option | Type | Default | Meaning |
|---|---|---|---|
| `modules` | `Ctor[]` | — | the `@Module` classes to wire (required) |
| `plugins` | `Plugin[]` | `[]` | plugins, each limited to `bus.on` + `scope.add` ([plugins](/guides/plugins/)) |
| `limits` | `RequestLimits` | see below | body-size and timeout ceilings |
| `devGraph` | `boolean` | `false` | mount `GET /__graph__` ([introspection](/guides/introspection/)) |
| `overrides` | `Record<string, unknown>` | — | swap any node by token ([testing](/guides/testing/)) |
| `tls` | `TlsOptions` | — | serve over https/wss |
| `trustProxy` | `boolean` | `false` | honor `X-Forwarded-*` for `ctx.protocol` / `ctx.ip` |
| `security` | `boolean \| SecurityOptions` | `true` | secure-by-default headers ([security](/guides/security/)) |
| `cors` | `CorsOptions` | — | CORS handling |
| `bodyDuplicates` | `'array' \| 'last'` | `'last'` | policy for repeated form fields |
| `mesh` | `MeshConfig` | — | distributed DI — **requires `experimental: true`** ([mesh](/guides/mesh/)) |
| `experimental` | `boolean` | `false` | opt in to alpha features (currently gates `mesh`) |
### `RequestLimits`
| Field | Default |
|---|---|
| `maxBodyBytes` | `1_000_000` (→ `413` when exceeded) |
| `requestTimeoutMs` | `30_000` |
| `headersTimeoutMs` | `10_000` |
| `keepAliveTimeoutMs` | `5_000` |
| `maxParts` | `1000` (multipart) |
### `TlsOptions`
`{ key, cert, ca?, passphrase? }` — `key`/`cert` are `Buffer | string`.
### `CorsOptions`
`{ origins, methods?, allowedHeaders?, exposedHeaders?, credentials?, maxAge? }`. `origins` is a string, array, `'*'`, or a `(origin) => boolean` predicate. `credentials: true` is never combined with `'*'`.
### `SecurityOptions`
`{ hsts?, frameOptions?, referrerPolicy?, noSniff?, dnsPrefetchControl?, csp? }`. HSTS is only emitted on secure connections. `csp` is opt-in.
### `MeshConfig`
`{ secret?, teapots?, timeoutMs? }` — `teapots` is `{ url, secret }[]`. See [Mesh](/guides/mesh/).
## The `App`
`createApp` returns an `App`:
| Member | Returns | Notes |
|---|---|---|
| `listen(port)` | `Promise<http.Server>` | boots providers, then serves |
| `close()` | `Promise<void>` | drains in-flight, closes streams + mesh links |
| `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 |
| `degraded()` | `string[]` | optional providers running degraded (empty until `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.
:::
@@ -0,0 +1,83 @@
---
title: Decorators
description: "Full reference for every class, method, and argument decorator."
---
Every decorator green-tea exports, grouped by where it applies. All require `experimentalDecorators: true` in your `tsconfig` — see [Why legacy decorators](/concepts/the-graph/#why-legacy-decorators).
## Structure
### `@Module(options)`
Marks a class as a module and records what it wires together.
```typescript
@Module({
mountpoint: '/api', // path prefix for this module's controllers (required)
providers: [Database], // app-scope @Provider classes
steps: [Authenticate], // request-scope @Step classes
controllers: [UserCtl], // @Route classes
})
class ApiModule {}
```
### `@Route(prefix)`
Marks a class as a controller; `prefix` is prepended to each route path.
## Providers & steps
### `@Provider(options)`
An app-scope value, built once at boot and cached, addressable by `provides`.
| Option | Type | Default | Meaning |
|---|---|---|---|
| `provides` | `string` | — | the token this provider produces (required) |
| `needs` | `string[]` | `[]` | tokens it depends on |
| `optional` | `boolean` | `false` | if it throws on boot, degrade instead of aborting ([details](/guides/dependency-injection/)) |
| `export` | `boolean` | `false` | expose over the mesh control channel ([mesh](/guides/mesh/)) |
### `@Step(options)`
A request-scope transform that merges keys into the context. Same options as `@Provider`.
### `@Transformer(fn)`
Method decorator. Turns a handler's return value into `{ status?, headers?, body }`. `JsonTransformer` is the default.
## Routes
Method decorators on a controller. All accept `(path, opts?)` where `opts = { export?: boolean, duplicates?: 'array' | 'last' }`.
| Decorator | Method | Transport |
|---|---|---|
| `@Get` `@Post` `@Put` `@Patch` `@Delete` | as named | buffered response |
| `@Sse` | GET | `text/event-stream` |
| `@Ws` | GET | WebSocket duplex |
| `@Stream` | GET | negotiated (SSE / ndjson / WS) |
```typescript
@Get('/ping', { export: true }) // exportable over mesh
@Post('/upload', { duplicates: 'array' }) // repeated form fields → arrays
```
See [Routing](/guides/routing/) for pattern matching and [Streaming](/guides/streaming/) for the transports.
## Arguments
A handler's signature declares exactly what it wants, in any order.
| Decorator | Injects | Forms |
|---|---|---|
| `@needs('user')` | a graph-produced value (boot-validated) | `('key')` |
| `@ctx()` | the whole accumulated context | `()` |
| `@param(...)` | route params | `()` · `('id')` · `('id', schema)` |
| `@query(...)` | parsed query string | `()` · `('q')` · `(['a','b'])` · `(schema)` |
| `@body(...)` | parsed body (JSON / urlencoded / multipart) | `()` · `('field')` · `(schema)` |
| `@headers(...)` | request headers (whole bag or picked) | `()` · `('authorization')` · `(['a','b'])` · `(schema)` |
| `@header('name')` | one request header (singular alias of `@headers`) | `('x-trace')` · `('x-count', schema)` |
| `@inbound()` | the incoming message stream (WebSocket) | `()` |
| `@abort()` | the request's `AbortSignal` | `()` |
Passing a [Standard Schema](/guides/validation/) validates and coerces the value before the handler sees it. Full details in [Argument decorators](/guides/arguments/).
+5
View File
@@ -0,0 +1,5 @@
{
"extends": "astro/tsconfigs/strict",
"include": [".astro/types.d.ts", "**/*"],
"exclude": ["dist"]
}