Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
813a29001b | ||
|
|
e0212d14e5 | ||
|
|
b72883c2ed | ||
|
|
489aa685bb | ||
|
|
c12be9a2f5 | ||
|
|
0541464093 |
No files matched your search
+2
-1
@@ -3,7 +3,8 @@
|
|||||||
All notable changes to `@green-tea/core` are documented here.
|
All notable changes to `@green-tea/core` are documented here.
|
||||||
|
|
||||||
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||||
green-tea uses calendar versioning: `YY.MM.PATCH`.
|
green-tea uses calendar versioning: `YY.M.PATCH` — the month is not zero-padded, since
|
||||||
|
npm treats versions as semver and semver forbids leading zeros.
|
||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
|||||||
@@ -35,7 +35,8 @@ Less to hold in your head. That's the tea.
|
|||||||
- **The pipeline is a graph, not a chain.** You never write "put this before that." You declare `needs`/`provides` and green-tea topologically sorts it. *Why it matters:* no ordering bugs, no positional guesswork, and each route runs only its slice of the graph (an auth step doesn't run on public routes).
|
- **The pipeline is a graph, not a chain.** You never write "put this before that." You declare `needs`/`provides` and green-tea topologically sorts it. *Why it matters:* no ordering bugs, no positional guesswork, and each route runs only its slice of the graph (an auth step doesn't run on public routes).
|
||||||
- **The type is the contract.** What a handler reads from the context *is* its dependency list. In the typed `flow` core, a handler that reads `ctx.user` **fails to compile** if no step produces `user`. *Why it matters:* whole classes of "it was undefined in prod" disappear at compile time.
|
- **The type is the contract.** What a handler reads from the context *is* its dependency list. In the typed `flow` core, a handler that reads `ctx.user` **fails to compile** if no step produces `user`. *Why it matters:* whole classes of "it was undefined in prod" disappear at compile time.
|
||||||
- **You can see the request before it runs.** `app.explain('/users/:id')` prints the ordered chain with origins; `app.graph()` / `GET /__graph__` render it as a live diagram; `app.openapi()` projects the same metadata into an OpenAPI 3.1 spec. *Why it matters:* onboarding, debugging, audits, and API docs are reading, not archaeology. (NestJS puts the graph behind a paid Devtools plan.)
|
- **You can see the request before it runs.** `app.explain('/users/:id')` prints the ordered chain with origins; `app.graph()` / `GET /__graph__` render it as a live diagram; `app.openapi()` projects the same metadata into an OpenAPI 3.1 spec. *Why it matters:* onboarding, debugging, audits, and API docs are reading, not archaeology. (NestJS puts the graph behind a paid Devtools plan.)
|
||||||
- **One primitive for real-time.** Return an `AsyncIterable` and the transport streams it — SSE, ndjson, or a WebSocket duplex — with backpressure and cleanup handled. *Why it matters:* no separate gateway, adapter, or library to bolt on.
|
- **One primitive for real-time.** Declare the transport — SSE, ndjson, or a WebSocket duplex — and return an `AsyncIterable`; backpressure and cleanup are handled. *Why it matters:* no separate gateway, adapter, or library to bolt on.
|
||||||
|
- **The same app runs on Node, Deno, Bun, and the edge.** One codebase, one import; you swap the entry point (`app.listen` → `serveDeno` / `serveBun` / `edgeHandler`) and nothing else. HTTP, SSE, and WebSocket — including rooms and channels — behave identically on all four. *Why it matters:* the graph model isn't a bet on one runtime's future, and no other opinionated/DI framework runs everywhere.
|
||||||
- **A remote dependency looks like a local one.** `@needs('billing')` resolves the same whether `billing` lives in this process or on another node (mesh, experimental). *Why it matters:* no gRPC layer or message-pattern DSL to learn — there's the graph, and some nodes happen to live elsewhere.
|
- **A remote dependency looks like a local one.** `@needs('billing')` resolves the same whether `billing` lives in this process or on another node (mesh, experimental). *Why it matters:* no gRPC layer or message-pattern DSL to learn — there's the graph, and some nodes happen to live elsewhere.
|
||||||
- **Plugins can't sabotage you.** A plugin gets `bus.on(...)` (observe) and `scope.add(...)` (extend its own scope). There is no API to reorder or delete another scope's steps. *Why it matters:* installing a plugin can't break your body parser.
|
- **Plugins can't sabotage you.** A plugin gets `bus.on(...)` (observe) and `scope.add(...)` (extend its own scope). There is no API to reorder or delete another scope's steps. *Why it matters:* installing a plugin can't break your body parser.
|
||||||
|
|
||||||
@@ -50,14 +51,15 @@ green-tea has one model: an **`AsyncIterable`**. A handler that returns a sequen
|
|||||||
| `@Sse` | server → client | `text/event-stream` | live updates to a browser (`EventSource`) |
|
| `@Sse` | server → client | `text/event-stream` | live updates to a browser (`EventSource`) |
|
||||||
| `@Ws` | duplex | WebSocket | chat, collaboration — anything two-way |
|
| `@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 |
|
| `@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:
|
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.
|
- **`@Sse`** — 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.
|
- **`@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.
|
- **`@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.
|
||||||
|
|
||||||
|
**Your wire contract is what you declared, never what you happened to return.** A buffered route that returns an iterable, or a streaming route that returns a plain value, fails loudly with a `TransportMismatchError` — green-tea will not quietly switch a route's transport because of a return type. Refactoring a handler's internals can't change how it talks to the client.
|
||||||
|
|
||||||
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.
|
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
|
```typescript
|
||||||
@@ -91,6 +93,7 @@ Beta shipped the parts a real API needs, without growing the runtime dependency
|
|||||||
- **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.
|
- **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 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.
|
- **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.
|
||||||
- **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response.
|
- **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response.
|
||||||
|
- **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency.
|
||||||
- **Graceful shutdown.** `app.close()` drains in-flight requests, closes live streams and mesh links.
|
- **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.
|
- **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.
|
- **Dual ESM + CommonJS.** Ships both builds behind an `exports` map — `import` and `require` both resolve, with matching type declarations.
|
||||||
@@ -117,6 +120,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 |
|
| **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** |
|
| **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` |
|
| **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` |
|
||||||
|
| **Runs on** | Node | Node | Node | Node | **Node · Deno · Bun · edge** — same code, swap the entry point |
|
||||||
| **Runtime deps** | minimal | minimal | heavy (rxjs, reflect-metadata, …) | Express + InversifyJS | **`reflect-metadata` only** (`ws`, `busboy` optional) |
|
| **Runtime deps** | minimal | minimal | heavy (rxjs, reflect-metadata, …) | Express + InversifyJS | **`reflect-metadata` only** (`ws`, `busboy` optional) |
|
||||||
|
|
||||||
### Read it as a story
|
### Read it as a story
|
||||||
@@ -220,21 +224,22 @@ green-tea is **beta**, on the road to a release candidate. Express and Fastify h
|
|||||||
|
|
||||||
**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.
|
**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.
|
**Runtimes differ in what they can offer.** Node ≥ 18, Deno, and Bun run everything. On the edge (Cloudflare Workers) there is no `app.listen()`, no filesystem — so `@Html` file/template modes and `static` serving are unavailable — and mesh does not run there at all (the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which `nodejs_compat` doesn't provide). Workers also require the `nodejs_compat` flag.
|
||||||
|
|
||||||
**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.
|
**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
|
## Docs & development
|
||||||
|
|
||||||
- **[Quickstart](./docs/quickstart.md)** — install + concrete examples (routes/DI, `flow`, validation, uploads, SSE, WebSocket, mesh, plugins).
|
- **[green-tea.expressive-tea.io/docs](https://green-tea.expressive-tea.io/docs)** — getting started, concepts (the graph, `flow`), and guides: routing, DI, validation, uploads, streaming, HTML, security, errors, introspection, OpenAPI, plugins, mesh, runtimes, testing.
|
||||||
- **[Architecture](./docs/architecture.md)** — the mental map (layers, request lifecycle, mesh) as diagrams.
|
- **[matcha](https://github.com/Expressive-Tea/matcha)** — the CLI. `matcha new` scaffolds a project (Node, Deno, or Bun), `matcha create` generates and auto-wires controllers/steps/providers/modules, `matcha run` detects your runtime and watches. A standalone Rust binary — no JS runtime needed to install it.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm install
|
npm install
|
||||||
npm test # vitest
|
npm test # vitest (Node); test:deno / test:bun / test:edge for the other runtimes
|
||||||
npm run typecheck # tsc --noEmit (includes the compile-time-guarantee type test)
|
npm run typecheck # tsc --noEmit (includes the compile-time-guarantee type test)
|
||||||
npm run build # emit dist/
|
npm run build # emit dist/ (tsup: dual ESM + CJS)
|
||||||
npm run bench # regenerate BENCHMARKS.md
|
npm run bench # regenerate BENCHMARKS.md
|
||||||
|
npm run docs:dev # the documentation site (website/)
|
||||||
```
|
```
|
||||||
|
|
||||||
## Roadmap
|
## Roadmap
|
||||||
@@ -244,7 +249,9 @@ npm run bench # regenerate BENCHMARKS.md
|
|||||||
- ✅ **streams** — SSE / ndjson / WebSocket duplex over a multicast `AsyncIterable` channel, with backpressure and cleanup.
|
- ✅ **streams** — SSE / ndjson / WebSocket duplex over a multicast `AsyncIterable` channel, with backpressure and cleanup.
|
||||||
- ✅ **graph introspection** — `explain` / `graph` / `toMermaid` / `GET /__graph__`.
|
- ✅ **graph introspection** — `explain` / `graph` / `toMermaid` / `GET /__graph__`.
|
||||||
- ✅ **mesh (walking skeleton)** — `teapot`/`teacup` distributed DI over a secret-gated WS control channel. A BEAM/OTP-style cluster, *not* microservices.
|
- ✅ **mesh (walking skeleton)** — `teapot`/`teacup` distributed DI over a secret-gated WS control channel. A BEAM/OTP-style cluster, *not* microservices.
|
||||||
- **next** — API freeze + first published release, mesh sub-specs (discovery, load-balancing, failover), runtime adapters (Deno / Bun / edge over web-standard `Request`/`Response`), official plugins.
|
- ✅ **runs everywhere** — Node, Deno, Bun, and Cloudflare Workers over web-standard `Request`/`Response`, with identical WebSocket behaviour on all four.
|
||||||
|
- ✅ **HTML** — `@Html` (string / file / template), a built-in template engine with a bring-your-own `viewEngine` hook, and `static` serving.
|
||||||
|
- **next** — API freeze + first published release, mesh sub-specs (discovery, load-balancing, failover), official plugins, router regex constraints and a radix-tree matcher.
|
||||||
|
|
||||||
## Versioning
|
## Versioning
|
||||||
|
|
||||||
|
|||||||
@@ -1,115 +0,0 @@
|
|||||||
# green-tea — Architecture
|
|
||||||
|
|
||||||
> The request and boot are an explicit **dependency graph**, not a mutable middleware chain.
|
|
||||||
> You declare *what* you need; the framework computes the order. The graph can extend in
|
|
||||||
> **time** (streams) and across **machines** (mesh).
|
|
||||||
|
|
||||||
## The four layers
|
|
||||||
|
|
||||||
```mermaid
|
|
||||||
flowchart TB
|
|
||||||
subgraph L3["#3 MESH — the graph crosses machines"]
|
|
||||||
direction LR
|
|
||||||
teacup["teacup (consumer)"] -- "WS RPC" --> teapot["teapot (host)"]
|
|
||||||
end
|
|
||||||
subgraph L2["#2 STREAMS — the graph emits over time"]
|
|
||||||
sse["SSE / ndjson"]:::n
|
|
||||||
ws["WebSocket duplex"]:::n
|
|
||||||
end
|
|
||||||
subgraph L15["#1.5 ARG DECORATORS — the handler declares its deps"]
|
|
||||||
sig["handler signature = dependency declaration"]:::n
|
|
||||||
end
|
|
||||||
subgraph L1["#1 CORE — graph DI + boot + router + pipeline + flow"]
|
|
||||||
core["Providers · Steps · Routes · Transformers · Container · Bus"]:::n
|
|
||||||
end
|
|
||||||
L3 --> L2 --> L15 --> L1
|
|
||||||
classDef n fill:#f6f8fa,stroke:#aaa;
|
|
||||||
```
|
|
||||||
|
|
||||||
## Building blocks
|
|
||||||
|
|
||||||
```mermaid
|
|
||||||
flowchart LR
|
|
||||||
Provider["@Provider\n(app scope · singleton)"]:::p
|
|
||||||
Step["@Step\n(request scope · per call)"]:::s
|
|
||||||
Route["@Route + @Get/@Post/@Sse/@Ws/@Stream"]:::r
|
|
||||||
Transformer["@Transformer\nvalue → ResponseShape"]:::t
|
|
||||||
Container["Container.resolve()\nasync · transport-agnostic"]:::c
|
|
||||||
Bus["Bus\nlifecycle events"]:::b
|
|
||||||
|
|
||||||
Provider --> Container
|
|
||||||
Step --> Container
|
|
||||||
Route --> Transformer
|
|
||||||
Container -. "remote binding (mesh)" .-> Provider
|
|
||||||
classDef p fill:#e7f5ff,stroke:#4dabf7;
|
|
||||||
classDef s fill:#fff3bf,stroke:#f59f00;
|
|
||||||
classDef r fill:#ebfbee,stroke:#40c057;
|
|
||||||
classDef t fill:#f3f0ff,stroke:#7950f2;
|
|
||||||
classDef c fill:#fff0f6,stroke:#e64980;
|
|
||||||
classDef b fill:#f1f3f5,stroke:#868e96;
|
|
||||||
```
|
|
||||||
|
|
||||||
## Request lifecycle
|
|
||||||
|
|
||||||
```mermaid
|
|
||||||
sequenceDiagram
|
|
||||||
participant C as Client
|
|
||||||
participant H as http.ts (transport)
|
|
||||||
participant P as Pipeline
|
|
||||||
participant G as Graph (providers/steps)
|
|
||||||
participant T as Transformer
|
|
||||||
|
|
||||||
C->>H: HTTP request
|
|
||||||
H->>H: matchRoute(method, path)
|
|
||||||
H->>P: runPipeline(seed = req envelope)
|
|
||||||
P->>G: providers (cached) + steps (topo order)
|
|
||||||
Note over G: each step merges into ctx;<br/>throw = short-circuit, return = continue
|
|
||||||
P->>P: handler(args resolved from ctx)
|
|
||||||
alt returns a value
|
|
||||||
P->>T: transformer → {status, headers, body}
|
|
||||||
T-->>C: buffered response
|
|
||||||
else returns an AsyncIterable
|
|
||||||
P-->>C: stream (SSE / ndjson / WS), backpressure + cleanup
|
|
||||||
else @needs a remote token
|
|
||||||
G-->>C: RPC to teapot, value spliced into ctx
|
|
||||||
end
|
|
||||||
```
|
|
||||||
|
|
||||||
## The unifying rule
|
|
||||||
|
|
||||||
```mermaid
|
|
||||||
flowchart TD
|
|
||||||
Q{"what does the handler return /\nwhere does a token live?"}
|
|
||||||
Q -->|"a value"| A["buffered (transformer → JSON)"]
|
|
||||||
Q -->|"an AsyncIterable"| B["stream (SSE / WS)"]
|
|
||||||
Q -->|"a token with no local provider"| D["RPC to a teapot (mesh)"]
|
|
||||||
```
|
|
||||||
|
|
||||||
One question — *"what produces this token and where does it live?"* — answers local DI,
|
|
||||||
streaming, and distribution. That single seam is why green-tea isn't "Express with decorators":
|
|
||||||
**the graph is the product.**
|
|
||||||
|
|
||||||
## Mesh walking skeleton (spec #3)
|
|
||||||
|
|
||||||
```mermaid
|
|
||||||
flowchart LR
|
|
||||||
subgraph A["Node A — teapot"]
|
|
||||||
ea["@Provider({export:true})\n@Step({export:true})\n@Get('/x',{export:true})"]
|
|
||||||
mc["control channel\n/__mesh__/control\n(secret-gated)"]
|
|
||||||
end
|
|
||||||
subgraph B["Node B — teacup"]
|
|
||||||
bn["@needs('auth') with\nno local provider"]
|
|
||||||
lk["link: handshake → manifest\n→ synthetic graph nodes\nwith RPC runners"]
|
|
||||||
end
|
|
||||||
bn --> lk
|
|
||||||
lk -- "hello + secret" --> mc
|
|
||||||
mc -- "manifest {scopes, routes}" --> lk
|
|
||||||
lk -- "rpc-req {id, kind, name, ctx}" --> mc
|
|
||||||
mc -- "rpc-res {id, ok, result}" --> lk
|
|
||||||
```
|
|
||||||
|
|
||||||
- **Provider exported → app scope** (resolved once via RPC, cached).
|
|
||||||
- **Step exported → request scope** (RPC per request, carries the request envelope).
|
|
||||||
- **Route exported → proxy** (teacup forwards the request, teapot runs the full pipeline).
|
|
||||||
|
|
||||||
Deferred to mesh sub-specs: discovery/auto-registration, 2-way load-balancing, failover/health.
|
|
||||||
@@ -1,522 +0,0 @@
|
|||||||
# green-tea — Quickstart
|
|
||||||
|
|
||||||
A type-safe HTTP framework where the request/boot pipeline is an explicit **dependency
|
|
||||||
graph**. You declare what you need; the framework computes the order, validates it at boot,
|
|
||||||
and can extend the graph over time (streams) and across machines (mesh).
|
|
||||||
|
|
||||||
See [architecture.md](./architecture.md) for the mental map.
|
|
||||||
|
|
||||||
## Install
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm install @green-tea/core reflect-metadata
|
|
||||||
# ws is an OPTIONAL peer dependency — only needed for WebSocket / mesh on Node:
|
|
||||||
npm install ws # optional
|
|
||||||
```
|
|
||||||
|
|
||||||
`tsconfig.json` must enable decorator metadata:
|
|
||||||
|
|
||||||
```jsonc
|
|
||||||
{
|
|
||||||
"compilerOptions": {
|
|
||||||
"experimentalDecorators": true,
|
|
||||||
"emitDecoratorMetadata": true,
|
|
||||||
"target": "es2017",
|
|
||||||
"module": "commonjs"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Import `reflect-metadata` once at your entrypoint.
|
|
||||||
|
|
||||||
## 1. A route with dependency injection
|
|
||||||
|
|
||||||
A **provider** is an app-scope singleton. A **step** runs per request and transforms the
|
|
||||||
context. 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.
|
|
||||||
|
|
||||||
```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
|
|
||||||
```
|
|
||||||
|
|
||||||
> **Per-route execution (important).** Each route runs **only the providers/steps in the transitive
|
|
||||||
> closure of its handler's `@needs`** — nothing else. A route that doesn't `@needs('user')` does **not**
|
|
||||||
> run the `Authenticate` step. This means 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.
|
|
||||||
|
|
||||||
### Argument decorators
|
|
||||||
|
|
||||||
| Decorator | Reads from | Adds a graph dependency? |
|
|
||||||
|---|---|---|
|
|
||||||
| `@needs('user')` | a value produced by a provider/step | **yes** (boot-validated) |
|
|
||||||
| `@ctx()` | the whole accumulated context | no |
|
|
||||||
| `@param('id')` | route params | no |
|
|
||||||
| `@query('q')` | parsed query string | no |
|
|
||||||
| `@body()` | parsed JSON body | no |
|
|
||||||
| `@headers('x')` | request headers | no |
|
|
||||||
| `@inbound()` | the incoming WS message channel | no (WS only) |
|
|
||||||
| `@abort()` | an `AbortSignal` that fires on disconnect | no (stream/WS) |
|
|
||||||
|
|
||||||
Each envelope decorator has three forms: `@query()` (whole object), `@query('q')` (one key),
|
|
||||||
`@query(['q','date'])` (subset).
|
|
||||||
|
|
||||||
## 2. Compile-time guarantee with `flow`
|
|
||||||
|
|
||||||
The decorator layer validates the graph at boot. The functional core `flow` validates it in
|
|
||||||
the **type checker**:
|
|
||||||
|
|
||||||
```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
|
|
||||||
```
|
|
||||||
|
|
||||||
## 3. 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).
|
|
||||||
|
|
||||||
## 4. 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).
|
|
||||||
|
|
||||||
## 5. Mesh — distributed dependency injection
|
|
||||||
|
|
||||||
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
|
|
||||||
@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" } }
|
|
||||||
```
|
|
||||||
|
|
||||||
`@needs('config' | 'auth')` validates at boot because the teapot announced them in its
|
|
||||||
manifest on connect. A provider export is app-scope (resolved once, cached); a step export is
|
|
||||||
request-scope (RPC per request, carrying the request envelope).
|
|
||||||
|
|
||||||
> 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`.
|
|
||||||
|
|
||||||
## 6. Plugins & observability
|
|
||||||
|
|
||||||
```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] });
|
|
||||||
```
|
|
||||||
|
|
||||||
Lifecycle events: `boot:provider:*`, `request:step:*`, `stream:open|close|error`,
|
|
||||||
`mesh:connect|disconnect|rpc:error`, `plugin:mounted`.
|
|
||||||
|
|
||||||
## 7. Transport security
|
|
||||||
|
|
||||||
Four `createApp` options cover TLS, proxying, CORS, and response headers.
|
|
||||||
|
|
||||||
### 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).
|
|
||||||
- **Security warning:** `origins: '*'` together with `credentials: true` reflects *any*
|
|
||||||
origin with credentials attached — the classic reflect-any foot-gun. 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'" } });
|
|
||||||
```
|
|
||||||
|
|
||||||
**Scope caveat:** `security` and `cors` headers apply to HTTP responses; they do not apply
|
|
||||||
to the WebSocket handshake (101/upgrade) response.
|
|
||||||
|
|
||||||
### Defaults
|
|
||||||
|
|
||||||
| Option | Default |
|
|
||||||
|---|---|
|
|
||||||
| `tls` | off (plain http/ws) |
|
|
||||||
| `trustProxy` | off |
|
|
||||||
| `cors` | off (same-origin only) |
|
|
||||||
| `security` | ON (HSTS only when the connection is secure) |
|
|
||||||
|
|
||||||
## 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:
|
|
||||||
|
|
||||||
```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.
|
|
||||||
|
|
||||||
> **Access note (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')`.
|
|
||||||
|
|
||||||
### 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.
|
|
||||||
|
|
||||||
## 9. Validation
|
|
||||||
|
|
||||||
`@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 };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
> **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 (all of `body`/`query`/`headers`).
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
**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.
|
|
||||||
|
|
||||||
## Inspect & test the graph
|
|
||||||
|
|
||||||
### Visualize with Mermaid
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
console.log(app.toMermaid()); // flowchart diagram of all nodes and routes
|
|
||||||
```
|
|
||||||
|
|
||||||
Enable a live `GET /__graph__` endpoint (renders HTML with Mermaid, or plain-text with `Accept: text/plain`):
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
const app = createApp({ modules: [ApiModule], devGraph: true });
|
|
||||||
// GET /__graph__ → HTML viewer
|
|
||||||
// GET /__graph__ (text/plain) → raw Mermaid source
|
|
||||||
```
|
|
||||||
|
|
||||||
### Explain a route
|
|
||||||
|
|
||||||
```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']
|
|
||||||
```
|
|
||||||
|
|
||||||
### Override tokens in tests
|
|
||||||
|
|
||||||
Swap any provider or step token with a test double at construction time — no monkey-patching:
|
|
||||||
|
|
||||||
```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.
|
|
||||||
|
|
||||||
## Runnable examples
|
|
||||||
|
|
||||||
The `example/` directory holds end-to-end apps you can `node`-run and read top to bottom.
|
|
||||||
|
|
||||||
### CRUD — methods, query, JSON & urlencoded body
|
|
||||||
|
|
||||||
`@Get/@Post/@Put/@Patch/@Delete` over a provider-backed store. Filter via `@query('done')`,
|
|
||||||
read the payload via `@body()` — the same handler accepts both `application/json` and
|
|
||||||
`application/x-www-form-urlencoded` (the transport parses each into a plain object). Missing
|
|
||||||
rows throw `NotFound` (→ 404).
|
|
||||||
|
|
||||||
See [`example/crud.ts`](../example/crud.ts).
|
|
||||||
|
|
||||||
### Chat — rooms + handshake auth
|
|
||||||
|
|
||||||
A `@Step` reads `?token=` and `provides: 'user'`, throwing `Unauthorized` on a missing token —
|
|
||||||
which closes the socket with code **4401** (`4000 + status`). The `@Ws` 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. `rooms` is the built-in shared `Rooms`
|
|
||||||
primitive (one instance app-wide).
|
|
||||||
|
|
||||||
See [`example/chat.ts`](../example/chat.ts).
|
|
||||||
|
|
||||||
### GraphQL — query/mutation over POST, subscription over SSE
|
|
||||||
|
|
||||||
A schema built programmatically with `graphql` (a dev/example dependency — the core has no
|
|
||||||
runtime dep on it). `POST /graphql` runs queries and mutations through `graphql()`. The
|
|
||||||
`mutation` pushes each new message into `rooms.room('messages')`; the `@Sse('/stream')` route
|
|
||||||
calls `subscribe()` whose source **is** that room, guards the result with `isAsyncIterable`,
|
|
||||||
and returns it — the framework streams each `ExecutionResult` as an SSE `data:` frame. This is
|
|
||||||
the tie between GraphQL, green-tea streams, and the `rooms` primitive.
|
|
||||||
|
|
||||||
See [`example/graphql.ts`](../example/graphql.ts) — `npm install graphql` first.
|
|
||||||
|
|
||||||
## The one rule to remember
|
|
||||||
|
|
||||||
```
|
|
||||||
return a VALUE → buffered response (transformer → JSON)
|
|
||||||
return an AsyncIterable → stream (SSE / WS)
|
|
||||||
@needs a remote token → RPC to a teapot (mesh)
|
|
||||||
```
|
|
||||||
@@ -3,7 +3,8 @@ import starlight from '@astrojs/starlight';
|
|||||||
|
|
||||||
// Docs site for @green-tea/core. Content lives in src/content/docs/**.
|
// Docs site for @green-tea/core. Content lives in src/content/docs/**.
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
site: 'https://green-tea.dev',
|
site: 'https://green-tea.expressive-tea.io',
|
||||||
|
base: '/docs',
|
||||||
integrations: [
|
integrations: [
|
||||||
starlight({
|
starlight({
|
||||||
title: 'Green Tea.',
|
title: 'Green Tea.',
|
||||||
@@ -30,6 +31,7 @@ export default defineConfig({
|
|||||||
{
|
{
|
||||||
label: 'Guides',
|
label: 'Guides',
|
||||||
items: [
|
items: [
|
||||||
|
{ label: 'The matcha CLI', slug: 'guides/cli' },
|
||||||
{ label: 'Routing', slug: 'guides/routing' },
|
{ label: 'Routing', slug: 'guides/routing' },
|
||||||
{ label: 'Dependency injection', slug: 'guides/dependency-injection' },
|
{ label: 'Dependency injection', slug: 'guides/dependency-injection' },
|
||||||
{ label: 'Argument decorators', slug: 'guides/arguments' },
|
{ label: 'Argument decorators', slug: 'guides/arguments' },
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ title: The typed flow core
|
|||||||
description: "The functional flow API where the compile-time dependency guarantee lives."
|
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.
|
The [decorator layer](/docs/guides/dependency-injection/) validates the graph at **boot**. The functional core, `flow`, validates it in the **type checker** — before the program ever runs.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import { flow } from '@green-tea/core';
|
import { flow } from '@green-tea/core';
|
||||||
@@ -21,4 +21,4 @@ This is the strongest guarantee green-tea offers: the type *is* the dependency c
|
|||||||
`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.
|
`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.
|
See [The dependency graph](/docs/concepts/the-graph/) for how both layers describe the same model.
|
||||||
@@ -27,14 +27,14 @@ class Authenticate { /* ... */ }
|
|||||||
- **No ordering bugs.** There's no positional `app.use()` sequence to get wrong; the sort is the order.
|
- **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.
|
- **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`.
|
- **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/).
|
- **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](/docs/guides/introspection/).
|
||||||
|
|
||||||
## Two layers
|
## Two layers
|
||||||
|
|
||||||
green-tea exposes the graph two ways:
|
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`.
|
1. **The typed functional core, [`flow`](/docs/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.
|
2. **The declarative decorator layer** — `@Provider` / `@Step` / `@Module` / `@Route` / `@Get` plus [argument decorators](/docs/guides/arguments/). Emits runtime metadata, builds and sorts the graph, and validates at boot.
|
||||||
|
|
||||||
Both describe the same graph; pick the ergonomics you want.
|
Both describe the same graph; pick the ergonomics you want.
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,16 @@ title: Getting started
|
|||||||
description: Install green-tea, configure TypeScript decorators, and build your first graph-based route.
|
description: Install green-tea, configure TypeScript decorators, and build your first graph-based route.
|
||||||
---
|
---
|
||||||
|
|
||||||
## Install
|
## Scaffold it
|
||||||
|
|
||||||
|
The fastest path is [matcha](/docs/guides/cli/), green-tea's CLI. It writes a project that runs on the first command — no wiring, no config:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
matcha new my-api # --runtime node (default) | deno | bun
|
||||||
|
cd my-api && matcha run
|
||||||
|
```
|
||||||
|
|
||||||
|
## Or install by hand
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm install @green-tea/core reflect-metadata
|
npm install @green-tea/core reflect-metadata
|
||||||
@@ -12,7 +21,9 @@ npm install ws # WebSocket routes (@Ws) and mesh
|
|||||||
npm install busboy # multipart/form-data file uploads
|
npm install busboy # multipart/form-data file uploads
|
||||||
```
|
```
|
||||||
|
|
||||||
green-tea targets **Node ≥ 18** and uses **legacy** TypeScript decorators. Enable them in your `tsconfig.json`:
|
green-tea runs on **Node ≥ 18, Deno, Bun, and the edge** — the same app, you only swap the entry point. This guide uses Node; see [runtimes](/docs/guides/runtimes/) for the others and for what the edge can't offer.
|
||||||
|
|
||||||
|
green-tea uses **legacy** TypeScript decorators. Enable them in your `tsconfig.json`:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -24,7 +35,7 @@ green-tea targets **Node ≥ 18** and uses **legacy** TypeScript decorators. Ena
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
You do **not** need `emitDecoratorMetadata` — green-tea records argument positions explicitly. See [Why legacy decorators](/concepts/the-graph/#why-legacy-decorators) for the rationale.
|
You do **not** need `emitDecoratorMetadata` — green-tea records argument positions explicitly. See [Why legacy decorators](/docs/concepts/the-graph/#why-legacy-decorators) for the rationale.
|
||||||
|
|
||||||
## Your first app
|
## Your first app
|
||||||
|
|
||||||
@@ -78,7 +89,7 @@ The handler asked for `user` via `@needs('user')`. If nothing in the graph produ
|
|||||||
|
|
||||||
## Where to next
|
## Where to next
|
||||||
|
|
||||||
- [The dependency graph](/concepts/the-graph/) — the mental model behind everything.
|
- [The dependency graph](/docs/concepts/the-graph/) — the mental model behind everything.
|
||||||
- [Dependency injection](/guides/dependency-injection/) — providers, steps, and modules in depth.
|
- [Dependency injection](/docs/guides/dependency-injection/) — providers, steps, and modules in depth.
|
||||||
- [Argument decorators](/guides/arguments/) — everything a handler can inject.
|
- [Argument decorators](/docs/guides/arguments/) — everything a handler can inject.
|
||||||
- [Streaming & real-time](/guides/streaming/) — SSE, WebSocket, and ndjson from one primitive.
|
- [Streaming & real-time](/docs/guides/streaming/) — SSE, WebSocket, and ndjson from one primitive.
|
||||||
@@ -34,7 +34,7 @@ getUser(@needs('user') user: any, @param('id') id: string) {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
See [Dependency injection](/guides/dependency-injection/) for how `needs`/`provides` build the
|
See [Dependency injection](/docs/guides/dependency-injection/) for how `needs`/`provides` build the
|
||||||
graph.
|
graph.
|
||||||
|
|
||||||
## `@ctx` — the whole context
|
## `@ctx` — the whole context
|
||||||
@@ -94,7 +94,7 @@ needs a name to say which route param it binds. `@body(Schema)`, `@query(Schema)
|
|||||||
object.
|
object.
|
||||||
:::
|
:::
|
||||||
|
|
||||||
A failing schema short-circuits the request with **422**. See [Validation](/guides/validation/)
|
A failing schema short-circuits the request with **422**. See [Validation](/docs/guides/validation/)
|
||||||
for the full contract (fail-fast order, error shape, async schemas, and caveats).
|
for the full contract (fail-fast order, error shape, async schemas, and caveats).
|
||||||
|
|
||||||
## Multipart access asymmetry
|
## Multipart access asymmetry
|
||||||
@@ -138,11 +138,11 @@ echo(@inbound() incoming: AsyncIterable<string>) {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
See [Streaming](/guides/streaming/) for SSE, WebSocket duplex, and channels.
|
See [Streaming](/docs/guides/streaming/) for SSE, WebSocket duplex, and channels.
|
||||||
|
|
||||||
## Where to go next
|
## Where to go next
|
||||||
|
|
||||||
- How injected values are produced: [Dependency injection](/guides/dependency-injection/).
|
- How injected values are produced: [Dependency injection](/docs/guides/dependency-injection/).
|
||||||
- The mental model: [The graph](/concepts/the-graph/).
|
- The mental model: [The graph](/docs/concepts/the-graph/).
|
||||||
- Validating and coercing injected values: [Validation](/guides/validation/).
|
- Validating and coercing injected values: [Validation](/docs/guides/validation/).
|
||||||
- The full API surface: [Decorator reference](/reference/decorators/).
|
- The full API surface: [Decorator reference](/docs/reference/decorators/).
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
---
|
||||||
|
title: The matcha CLI
|
||||||
|
description: "Scaffold, run, and generate green-tea apps from a single native binary."
|
||||||
|
---
|
||||||
|
|
||||||
|
**matcha** scaffolds green-tea projects, runs them in watch mode, and generates pieces already wired into your graph. It is a native binary — installing the CLI needs no JS runtime, and it only reaches for yours when it runs or type-checks your project.
|
||||||
|
|
||||||
|
That is deliberate: green-tea runs on Node, Deno, Bun, and the edge, so its tool shouldn't be bound to one of them.
|
||||||
|
|
||||||
|
## Install
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -fsSL https://raw.githubusercontent.com/Expressive-Tea/matcha/main/install.sh | sh
|
||||||
|
```
|
||||||
|
|
||||||
|
Downloads a checksum-verified prebuilt binary into `~/.local/bin`. Environment variables go on the `sh` side of the pipe:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -fsSL …/install.sh | MATCHA_VERSION=v26.7.0 MATCHA_INSTALL_DIR=/usr/local/bin sh
|
||||||
|
```
|
||||||
|
|
||||||
|
From source, if you have Rust:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cargo install --git https://github.com/Expressive-Tea/matcha
|
||||||
|
```
|
||||||
|
|
||||||
|
## Scaffold — `matcha new`
|
||||||
|
|
||||||
|
```bash
|
||||||
|
matcha new my-api # Node (the default)
|
||||||
|
matcha new my-api --runtime deno # or deno | bun
|
||||||
|
matcha new my-api --template-url gh:owner/repo # any git template
|
||||||
|
```
|
||||||
|
|
||||||
|
The starter is alive on the first run: it serves an `index.html` and streams a rotating zen message over `@Sse('/zen')`. Open the browser and something is already moving — you are editing a working app, not assembling one.
|
||||||
|
|
||||||
|
Only the entry point and the config differ between runtimes. The `src/` tree is identical, which is the same portability the framework promises.
|
||||||
|
|
||||||
|
## Run — `matcha run`
|
||||||
|
|
||||||
|
```bash
|
||||||
|
matcha run
|
||||||
|
```
|
||||||
|
|
||||||
|
Detects the runtime and starts a watch loop. First match wins:
|
||||||
|
|
||||||
|
1. `matcha.toml` — an explicit `runtime = "node" | "deno" | "bun"`
|
||||||
|
2. `deno.json` / `deno.jsonc` → deno
|
||||||
|
3. `bun.lockb` / `bun.lock` → bun
|
||||||
|
4. `package.json` → node
|
||||||
|
|
||||||
|
Edge is a deploy target, not a `matcha run` target.
|
||||||
|
|
||||||
|
## Generate — `matcha create`
|
||||||
|
|
||||||
|
```bash
|
||||||
|
matcha create controller Users
|
||||||
|
matcha create step Authenticate
|
||||||
|
matcha create provider Database
|
||||||
|
matcha create module Billing
|
||||||
|
matcha create controller Users --check # type-check with your runtime afterward
|
||||||
|
```
|
||||||
|
|
||||||
|
Writes the file **and wires it in** — into the right `@Module` array, or into `createApp({ modules })` for a module.
|
||||||
|
|
||||||
|
## Extend — `matcha add`
|
||||||
|
|
||||||
|
```bash
|
||||||
|
matcha add sse # or: stream | buffer
|
||||||
|
```
|
||||||
|
|
||||||
|
Inserts a handler of that shape into your controller.
|
||||||
|
|
||||||
|
## How the edits stay safe
|
||||||
|
|
||||||
|
`create` and `add` edit your TypeScript with [tree-sitter](https://tree-sitter.github.io), not string splicing or regex. Edits are **idempotent** — running the same command twice doesn't duplicate anything — and they **revert themselves** if the result wouldn't parse. A generator that corrupts your source is worse than no generator.
|
||||||
|
|
||||||
|
One case it deliberately refuses: if `modules` is a variable (`modules: MODULES`) rather than an array literal, `create module` won't add a second `modules` key. Duplicate keys parse cleanly, so nothing would fail — it would just silently shadow your value. It tells you instead.
|
||||||
@@ -138,9 +138,9 @@ receive `undefined`. Boot fails loudly, so you never serve `undefined`.
|
|||||||
|
|
||||||
## Where to go next
|
## Where to go next
|
||||||
|
|
||||||
- New to green-tea? Start with [Getting started](/getting-started/).
|
- New to green-tea? Start with [Getting started](/docs/getting-started/).
|
||||||
- The mental model behind all of this: [The graph](/concepts/the-graph/).
|
- The mental model behind all of this: [The graph](/docs/concepts/the-graph/).
|
||||||
- Everything a handler can inject: [Argument decorators](/guides/arguments/) and the
|
- Everything a handler can inject: [Argument decorators](/docs/guides/arguments/) and the
|
||||||
[decorator reference](/reference/decorators/).
|
[decorator reference](/docs/reference/decorators/).
|
||||||
- Coerce and validate injected values with Standard Schema: [Validation](/guides/validation/).
|
- Coerce and validate injected values with Standard Schema: [Validation](/docs/guides/validation/).
|
||||||
- Declare `@Sse` and return an `AsyncIterable` to push data over time: [Streaming](/guides/streaming/).
|
- Declare `@Sse` and return an `AsyncIterable` to push data over time: [Streaming](/docs/guides/streaming/).
|
||||||
@@ -64,5 +64,5 @@ 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) — 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).
|
||||||
|
|
||||||
:::note
|
:::note
|
||||||
Errors are also observable without changing the response: subscribe to `request:step:error` (and `stream:error`) on [`app.bus`](/guides/plugins/) to log or trace them.
|
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.
|
||||||
:::
|
:::
|
||||||
@@ -37,7 +37,7 @@ class AboutController {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Reading a file needs a filesystem, so this mode is Node/Deno/Bun only — see [Runtimes](/guides/runtimes/) for the edge alternative.
|
Reading a file needs a filesystem, so this mode is Node/Deno/Bun only — see [Runtimes](/docs/guides/runtimes/) for the edge alternative.
|
||||||
|
|
||||||
### 3. Render a template — Node/Deno/Bun
|
### 3. Render a template — Node/Deno/Bun
|
||||||
|
|
||||||
@@ -134,7 +134,7 @@ const app3 = createApp({ modules: [ApiModule], static: '/srv/site' }); // absolu
|
|||||||
- **Declared routes always win.** Static is only consulted when nothing matched, so `@Get('/api/ping')` is never shadowed by a file at `public/api/ping`.
|
- **Declared routes always win.** Static is only consulted when nothing matched, so `@Get('/api/ping')` is never shadowed by a file at `public/api/ping`.
|
||||||
- Path traversal (`../`, encoded or not) is rejected — a request can't escape the static root.
|
- Path traversal (`../`, encoded or not) is rejected — a request can't escape the static root.
|
||||||
|
|
||||||
Like the file/template modes of `@Html`, `static` needs a filesystem: it's Node/Deno/Bun only. Configuring it on an edge runtime throws at `createApp()` time — see [Runtimes](/guides/runtimes/).
|
Like the file/template modes of `@Html`, `static` needs a filesystem: it's Node/Deno/Bun only. Configuring it on an edge runtime throws at `createApp()` time — see [Runtimes](/docs/guides/runtimes/).
|
||||||
|
|
||||||
## The boot rule
|
## The boot rule
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ title: Graph introspection
|
|||||||
description: "explain, graph, toMermaid, and the graph endpoint."
|
description: "explain, graph, toMermaid, and the graph endpoint."
|
||||||
---
|
---
|
||||||
|
|
||||||
Because the request/boot pipeline is an explicit [dependency graph](/concepts/the-graph/),
|
Because the request/boot pipeline is an explicit [dependency graph](/docs/concepts/the-graph/),
|
||||||
you can inspect it directly — visualize the whole thing, or explain exactly which nodes a
|
you can inspect it directly — visualize the whole thing, or explain exactly which nodes a
|
||||||
single route runs.
|
single route runs.
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ description: "Distributed dependency injection over a secret-gated WebSocket con
|
|||||||
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.**
|
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.
|
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](/docs/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.
|
Exports are opt-in (`export: true`) and the control channel is gated by a shared secret.
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ title: OpenAPI
|
|||||||
description: "Generate a structural OpenAPI 3.1 document from the route graph."
|
description: "Generate a structural OpenAPI 3.1 document from the route graph."
|
||||||
---
|
---
|
||||||
|
|
||||||
Because the request pipeline is [data you can read](/concepts/the-graph/), green-tea can project it — the same way it renders [Mermaid/DOT](/guides/introspection/), it emits **OpenAPI**.
|
Because the request pipeline is [data you can read](/docs/concepts/the-graph/), green-tea can project it — the same way it renders [Mermaid/DOT](/docs/guides/introspection/), it emits **OpenAPI**.
|
||||||
|
|
||||||
## `app.openapi()`
|
## `app.openapi()`
|
||||||
|
|
||||||
@@ -36,6 +36,6 @@ const app = createApp({ modules: [ApiModule], devOpenapi: true });
|
|||||||
|
|
||||||
This is a **structural** spec: paths, methods, parameters, which routes take a body, and the standard error responses. What it does **not** include yet:
|
This is a **structural** spec: paths, methods, parameters, which routes take a body, and the standard error responses. What it does **not** include yet:
|
||||||
|
|
||||||
- **Request/response body schemas.** [Standard Schema](/guides/validation/) (zod/valibot/arktype) validates input but does not expose a JSON Schema representation, so body shapes are documented generically. Parameter types default to `string`.
|
- **Request/response body schemas.** [Standard Schema](/docs/guides/validation/) (zod/valibot/arktype) validates input but does not expose a JSON Schema representation, so body shapes are documented generically. Parameter types default to `string`.
|
||||||
|
|
||||||
Full schemas — declared and enforced on the way out via a `@Produce(schema)` decorator that also validates responses — are on the roadmap for the stable release. For beta, the structural document already drives Swagger UI, client codegen, and API diffing.
|
Full schemas — declared and enforced on the way out via a `@Produce(schema)` decorator that also validates responses — are on the roadmap for the stable release. For beta, the structural document already drives Swagger UI, client codegen, and API diffing.
|
||||||
@@ -30,7 +30,7 @@ and the framework computes where that node lands.
|
|||||||
Because execution is per-route (a route runs only the transitive closure of its handler's
|
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
|
`@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
|
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
|
runs it unconditionally. See [The graph](/docs/concepts/the-graph/) for how the closure is
|
||||||
computed.
|
computed.
|
||||||
:::
|
:::
|
||||||
|
|
||||||
@@ -55,4 +55,4 @@ The full event vocabulary:
|
|||||||
|
|
||||||
Observation is read-only: handlers see the event payload but can't alter control flow. To
|
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
|
change behavior, contribute a node to your scope — see
|
||||||
[Dependency injection](/guides/dependency-injection/).
|
[Dependency injection](/docs/guides/dependency-injection/).
|
||||||
@@ -51,7 +51,7 @@ When more than one route matches the same path, the **most specific wins** — `
|
|||||||
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`.
|
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
|
:::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/).
|
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/).
|
||||||
:::
|
:::
|
||||||
|
|
||||||
## Not yet
|
## Not yet
|
||||||
@@ -61,4 +61,4 @@ The matcher is intentionally small for beta. **Not built** (on the roadmap):
|
|||||||
- Regex / typed param constraints such as `:id(\d+)`.
|
- 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 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.
|
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.
|
||||||
@@ -22,12 +22,15 @@ Bun.serve({ fetch: app.fetch });
|
|||||||
export default { fetch: app.fetch };
|
export default { fetch: app.fetch };
|
||||||
```
|
```
|
||||||
|
|
||||||
**Node is the reference implementation** — every runtime returns the same status, headers,
|
**Node is the reference implementation.** A parity suite pins `app.fetch` to Node's native
|
||||||
and body for the same request (enforced by a parity test suite).
|
listener — identical status, headers, and body for the same request. The other runtimes drive
|
||||||
|
that *same* `app.fetch` / `app.upgrade` core, so they inherit that behaviour rather than
|
||||||
|
re-implementing it, and each carries its own smoke tests: Deno and Bun cover WebSocket and mesh,
|
||||||
|
and edge runs against real workerd (Miniflare).
|
||||||
|
|
||||||
**All four runtimes now have full WebSocket support:** Node, Deno, and Bun via `serveDeno` /
|
**All four runtimes now have full WebSocket support:** Node via `app.listen()`, Deno and Bun via
|
||||||
`serveBun`, and Cloudflare Workers / edge via `edgeHandler` (see below) — same graph, same
|
`serveDeno` / `serveBun`, and Cloudflare Workers / edge via `edgeHandler` (see below) — same graph,
|
||||||
`@Ws` handlers, same rooms/channels everywhere. `app.listen()`, TLS and per-request timeouts
|
same `@Ws` handlers, same rooms/channels everywhere. `app.listen()`, TLS and per-request timeouts
|
||||||
remain Node-only; on Deno/Bun/edge you get `app.fetch` + the runtime's adapter. **Mesh (alpha)
|
remain Node-only; on Deno/Bun/edge you get `app.fetch` + the runtime's adapter. **Mesh (alpha)
|
||||||
runs on Node, Deno and Bun** — teapot and teacup, in any combination — but not on edge.
|
runs on Node, Deno and Bun** — teapot and teacup, in any combination — but not on edge.
|
||||||
|
|
||||||
@@ -60,7 +63,7 @@ Any runtime can build a `WsSocket` capability (`inbound`, `abort`, `isOpen`, `se
|
|||||||
same primitive (see below).
|
same primitive (see below).
|
||||||
|
|
||||||
**Still Node-only:** `app.listen()`, TLS and per-request timeouts. On Deno you get
|
**Still Node-only:** `app.listen()`, TLS and per-request timeouts. On Deno you get
|
||||||
`app.fetch` + `serveDeno`. [Mesh](/guides/mesh/) works here: the control channel is
|
`app.fetch` + `serveDeno`. [Mesh](/docs/guides/mesh/) works here: the control channel is
|
||||||
served through `app.upgrade` and the teacup connects with Deno's global `WebSocket`.
|
served through `app.upgrade` and the teacup connects with Deno's global `WebSocket`.
|
||||||
|
|
||||||
## WebSocket on Bun
|
## WebSocket on Bun
|
||||||
@@ -83,7 +86,7 @@ serveBun(app, { port: 8000 });
|
|||||||
run on Node and Deno. Behaviour matches the Node reference.
|
run on Node and Deno. Behaviour matches the Node reference.
|
||||||
|
|
||||||
**Still Node-only:** `app.listen()`, TLS and per-request timeouts. On Bun you get
|
**Still Node-only:** `app.listen()`, TLS and per-request timeouts. On Bun you get
|
||||||
`app.fetch` + `serveBun`. [Mesh](/guides/mesh/) works here too.
|
`app.fetch` + `serveBun`. [Mesh](/docs/guides/mesh/) works here too.
|
||||||
|
|
||||||
## Cloudflare Workers / edge
|
## Cloudflare Workers / edge
|
||||||
|
|
||||||
@@ -115,7 +118,7 @@ compatibility_date = "2024-09-23" # or later
|
|||||||
Green Tea's core statically imports Node built-ins that workerd only provides under
|
Green Tea's core statically imports Node built-ins that workerd only provides under
|
||||||
this flag; without it, the Worker fails to load.
|
this flag; without it, the Worker fails to load.
|
||||||
|
|
||||||
**Still Node-only:** `app.listen()`, TLS and per-request timeouts. [Mesh](/guides/mesh/)
|
**Still Node-only:** `app.listen()`, TLS and per-request timeouts. [Mesh](/docs/guides/mesh/)
|
||||||
is **not** supported on edge: the teapot's secret comparison needs `node:crypto`'s
|
is **not** supported on edge: the teapot's secret comparison needs `node:crypto`'s
|
||||||
`timingSafeEqual`, which `nodejs_compat` does not provide. Cloudflare's
|
`timingSafeEqual`, which `nodejs_compat` does not provide. Cloudflare's
|
||||||
Durable Objects and WebSocket Hibernation are **not** used — `edgeHandler` accepts
|
Durable Objects and WebSocket Hibernation are **not** used — `edgeHandler` accepts
|
||||||
@@ -124,7 +127,7 @@ open for its lifetime rather than hibernating between messages.
|
|||||||
|
|
||||||
## Filesystem features — Node/Deno/Bun only
|
## Filesystem features — Node/Deno/Bun only
|
||||||
|
|
||||||
A few [HTML & views](/guides/html/) features read from disk, so they need a runtime with
|
A few [HTML & views](/docs/guides/html/) features read from disk, so they need a runtime with
|
||||||
a filesystem:
|
a filesystem:
|
||||||
|
|
||||||
- `@Html('file.html')` — reads and caches the file at boot.
|
- `@Html('file.html')` — reads and caches the file at boot.
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ description: "TLS and wss, secure-by-default headers, CORS, and trustProxy."
|
|||||||
---
|
---
|
||||||
|
|
||||||
Four `createApp` options cover TLS, proxying, CORS, and response headers: `tls`,
|
Four `createApp` options cover TLS, proxying, CORS, and response headers: `tls`,
|
||||||
`trustProxy`, `cors`, and `security`. See the [`createApp` reference](/reference/createapp/)
|
`trustProxy`, `cors`, and `security`. See the [`createApp` reference](/docs/reference/createapp/)
|
||||||
for the full option list.
|
for the full option list.
|
||||||
|
|
||||||
## TLS (native https/wss)
|
## TLS (native https/wss)
|
||||||
@@ -97,5 +97,5 @@ strips and sets forwarded headers itself, and terminate TLS where you control th
|
|||||||
|
|
||||||
## Related
|
## Related
|
||||||
|
|
||||||
- [`createApp` reference](/reference/createapp/) — every construction option
|
- [`createApp` reference](/docs/reference/createapp/) — every construction option
|
||||||
- [File uploads / multipart](/guides/uploads/) — request-body handling
|
- [File uploads / multipart](/docs/guides/uploads/) — request-body handling
|
||||||
@@ -7,23 +7,22 @@ Most stacks treat "push data over time" as a bolt-on: Express reaches for a `ws`
|
|||||||
|
|
||||||
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.
|
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
|
## One primitive, three modes
|
||||||
|
|
||||||
| Declare | Direction | Transport | Reach for it when |
|
| Declare | Direction | Transport | Reach for it when |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| `@Sse` | server → client | `text/event-stream` | live updates to a browser (`EventSource`) |
|
| `@Sse` | server → client | `text/event-stream` | live updates to a browser (`EventSource`) |
|
||||||
| `@Ws` | duplex | WebSocket | chat, collaboration — anything two-way |
|
| `@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 |
|
| `@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:
|
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.
|
- **`@Sse`** — 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.
|
- **`@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.
|
- **`@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
|
:::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 bypasses the response transformer — the transport frames each value directly, handles backpressure, and cleans up on disconnect. See [arguments](/docs/guides/arguments/) for the full list of argument decorators, including the stream-only `@inbound()` and `@abort()`.
|
||||||
:::
|
:::
|
||||||
|
|
||||||
## Streaming — SSE
|
## Streaming — SSE
|
||||||
@@ -102,7 +101,7 @@ class Live {
|
|||||||
|
|
||||||
Same `@Route`, same handler shape, same `AsyncIterable` — real-time is not a separate framework you also have to learn.
|
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.
|
`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](/docs/guides/security/) for handshake authentication.
|
||||||
|
|
||||||
## Transport is declared, not inferred
|
## Transport is declared, not inferred
|
||||||
|
|
||||||
|
|||||||
@@ -29,5 +29,5 @@ An override for an unknown token throws. The set of tokens is validated against
|
|||||||
graph, so a typo'd or stale override is a construction-time error, not a silent no-op.
|
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
|
This pairs well with [`app.explain(route)`](/docs/guides/introspection/) — explain the chain to
|
||||||
see which tokens a route actually depends on, then override exactly those.
|
see which tokens a route actually depends on, then override exactly those.
|
||||||
@@ -27,7 +27,7 @@ class ProfileController {
|
|||||||
`UploadedFile` is `{ filename, contentType, data: Buffer, size }` — the whole file is buffered in memory, no temp files.
|
`UploadedFile` is `{ filename, contentType, data: Buffer, size }` — the whole file is buffered in memory, no temp files.
|
||||||
|
|
||||||
:::note[Access asymmetry]
|
:::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.
|
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](/docs/guides/arguments/) for how `@body()` behaves across content types.
|
||||||
:::
|
:::
|
||||||
|
|
||||||
## Repeated fields — `bodyDuplicates`
|
## Repeated fields — `bodyDuplicates`
|
||||||
@@ -67,5 +67,5 @@ uploadAvatar(@body() form: MultipartBody) { /* ... */ }
|
|||||||
A route's `maxBodyBytes` / `maxParts` fall back to the server-wide `limits` when unset. A malformed multipart body (bad boundary, missing headers, truncated part) → **400**.
|
A route's `maxBodyBytes` / `maxParts` fall back to the server-wide `limits` when unset. A malformed multipart body (bad boundary, missing headers, truncated part) → **400**.
|
||||||
|
|
||||||
:::note
|
:::note
|
||||||
To validate parsed fields against a schema, pass a Standard Schema to `@body()` — see [validation](/guides/validation/).
|
To validate parsed fields against a schema, pass a Standard Schema to `@body()` — see [validation](/docs/guides/validation/).
|
||||||
:::
|
:::
|
||||||
@@ -48,7 +48,7 @@ needs a name to say which route param it binds. `@body(Schema)`, `@query(Schema)
|
|||||||
object (all of `body`/`query`/`headers`).
|
object (all of `body`/`query`/`headers`).
|
||||||
:::
|
:::
|
||||||
|
|
||||||
See [Argument decorators](/guides/arguments/) for the full slot semantics of each decorator.
|
See [Argument decorators](/docs/guides/arguments/) for the full slot semantics of each decorator.
|
||||||
|
|
||||||
## Failure: 422 with per-field issues
|
## Failure: 422 with per-field issues
|
||||||
|
|
||||||
@@ -79,6 +79,6 @@ validation are all out of scope for this feature.
|
|||||||
|
|
||||||
## Related
|
## Related
|
||||||
|
|
||||||
- [Argument decorators](/guides/arguments/) — every slot decorator and its parsing rules
|
- [Argument decorators](/docs/guides/arguments/) — every slot decorator and its parsing rules
|
||||||
- [File uploads / multipart](/guides/uploads/) — how multipart bodies are parsed before validation
|
- [File uploads / multipart](/docs/guides/uploads/) — how multipart bodies are parsed before validation
|
||||||
- [`createApp` reference](/reference/createapp/) — app construction options
|
- [`createApp` reference](/docs/reference/createapp/) — app construction options
|
||||||
@@ -9,11 +9,11 @@ hero:
|
|||||||
tagline: A zen, opinionated, type-safe framework. Your API is a dependency graph you can see, slice, and trust — not a mutable bag threaded through positional middleware. That's the tea. 🍵
|
tagline: A zen, opinionated, type-safe framework. Your API is a dependency graph you can see, slice, and trust — not a mutable bag threaded through positional middleware. That's the tea. 🍵
|
||||||
actions:
|
actions:
|
||||||
- text: Get started
|
- text: Get started
|
||||||
link: /getting-started/
|
link: /docs/getting-started/
|
||||||
icon: right-arrow
|
icon: right-arrow
|
||||||
variant: primary
|
variant: primary
|
||||||
- text: The idea
|
- text: The idea
|
||||||
link: /concepts/the-graph/
|
link: /docs/concepts/the-graph/
|
||||||
icon: open-book
|
icon: open-book
|
||||||
variant: minimal
|
variant: minimal
|
||||||
---
|
---
|
||||||
@@ -37,8 +37,11 @@ Most frameworks make you keep the whole request in your head: which middleware r
|
|||||||
<Card title="One primitive for real-time" icon="rocket">
|
<Card title="One primitive for real-time" icon="rocket">
|
||||||
Declare `@Sse`, `@Stream`, or `@Ws` and return an `AsyncIterable` — the transport streams it (SSE, ndjson, or a WebSocket duplex) with backpressure and cleanup handled. No separate gateway.
|
Declare `@Sse`, `@Stream`, or `@Ws` and return an `AsyncIterable` — the transport streams it (SSE, ndjson, or a WebSocket duplex) with backpressure and cleanup handled. No separate gateway.
|
||||||
</Card>
|
</Card>
|
||||||
|
<Card title="Runs wherever JS runs" icon="laptop">
|
||||||
|
Node, Deno, Bun, and the edge — the same app, you only swap the entry point. HTTP, SSE, and WebSocket behave identically on all four.
|
||||||
|
</Card>
|
||||||
</CardGrid>
|
</CardGrid>
|
||||||
|
|
||||||
:::note[Beta]
|
:::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.
|
green-tea is **beta**, on the RC track. One runtime dependency (`reflect-metadata`); `ws` and `busboy` are optional peers. [mesh](/docs/guides/mesh/) is alpha and gated behind an explicit opt-in.
|
||||||
:::
|
:::
|
||||||
@@ -12,21 +12,21 @@ const app = createApp(options);
|
|||||||
| Option | Type | Default | Meaning |
|
| Option | Type | Default | Meaning |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| `modules` | `Ctor[]` | — | the `@Module` classes to wire (required) |
|
| `modules` | `Ctor[]` | — | the `@Module` classes to wire (required) |
|
||||||
| `plugins` | `Plugin[]` | `[]` | plugins, each limited to `bus.on` + `scope.add` ([plugins](/guides/plugins/)) |
|
| `plugins` | `Plugin[]` | `[]` | plugins, each limited to `bus.on` + `scope.add` ([plugins](/docs/guides/plugins/)) |
|
||||||
| `limits` | `RequestLimits` | see below | body-size and timeout ceilings |
|
| `limits` | `RequestLimits` | see below | body-size and timeout ceilings |
|
||||||
| `devGraph` | `boolean` | `false` | mount `GET /__graph__` ([introspection](/guides/introspection/)) |
|
| `devGraph` | `boolean` | `false` | mount `GET /__graph__` ([introspection](/docs/guides/introspection/)) |
|
||||||
| `devOpenapi` | `boolean` | `false` | mount `GET /__openapi__` serving the [OpenAPI](/guides/openapi/) document |
|
| `devOpenapi` | `boolean` | `false` | mount `GET /__openapi__` serving the [OpenAPI](/docs/guides/openapi/) document |
|
||||||
| `overrides` | `Record<string, unknown>` | — | swap any node by token ([testing](/guides/testing/)) |
|
| `overrides` | `Record<string, unknown>` | — | swap any node by token ([testing](/docs/guides/testing/)) |
|
||||||
| `tls` | `TlsOptions` | — | serve over https/wss |
|
| `tls` | `TlsOptions` | — | serve over https/wss |
|
||||||
| `trustProxy` | `boolean` | `false` | honor `X-Forwarded-*` for `ctx.protocol` / `ctx.ip` |
|
| `trustProxy` | `boolean` | `false` | honor `X-Forwarded-*` for `ctx.protocol` / `ctx.ip` |
|
||||||
| `security` | `boolean \| SecurityOptions` | `true` | secure-by-default headers ([security](/guides/security/)) |
|
| `security` | `boolean \| SecurityOptions` | `true` | secure-by-default headers ([security](/docs/guides/security/)) |
|
||||||
| `cors` | `CorsOptions` | — | CORS handling |
|
| `cors` | `CorsOptions` | — | CORS handling |
|
||||||
| `bodyDuplicates` | `'array' \| 'last'` | `'last'` | policy for repeated form fields |
|
| `bodyDuplicates` | `'array' \| 'last'` | `'last'` | policy for repeated form fields |
|
||||||
| `onError` | `ErrorRenderer` | — | render errors your way ([error handling](/guides/errors/)); returns a response or `undefined` to fall back to JSON |
|
| `onError` | `ErrorRenderer` | — | render errors your way ([error handling](/docs/guides/errors/)); returns a response or `undefined` to fall back to JSON |
|
||||||
| `views` | `string` | `process.cwd()` | base dir `@Html('file.html')` paths resolve against — relative paths join it, absolute paths are used as-is ([HTML & views](/guides/html/)) |
|
| `views` | `string` | `process.cwd()` | base dir `@Html('file.html')` paths resolve against — relative paths join it, absolute paths are used as-is ([HTML & views](/docs/guides/html/)) |
|
||||||
| `viewEngine` | `(source: string, data: unknown) => string` | built-in `render` | swap in your own template engine for `@Html(..., { template: true })`; template mode only ([HTML & views](/guides/html/)) |
|
| `viewEngine` | `(source: string, data: unknown) => string` | built-in `render` | swap in your own template engine for `@Html(..., { template: true })`; template mode only ([HTML & views](/docs/guides/html/)) |
|
||||||
| `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](/guides/html/)) |
|
| `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](/guides/mesh/)) |
|
| `mesh` | `MeshConfig` | — | distributed DI — **requires `experimental: true`** ([mesh](/docs/guides/mesh/)) |
|
||||||
| `experimental` | `boolean` | `false` | opt in to alpha features (currently gates `mesh`) |
|
| `experimental` | `boolean` | `false` | opt in to alpha features (currently gates `mesh`) |
|
||||||
|
|
||||||
### `RequestLimits`
|
### `RequestLimits`
|
||||||
@@ -53,7 +53,7 @@ const app = createApp(options);
|
|||||||
|
|
||||||
### `MeshConfig`
|
### `MeshConfig`
|
||||||
|
|
||||||
`{ secret?, teapots?, timeoutMs? }` — `teapots` is `{ url, secret }[]`. See [Mesh](/guides/mesh/).
|
`{ secret?, teapots?, timeoutMs?, heartbeatMs? }` — `teapots` is `{ url, secret }[]`; `timeoutMs` bounds an RPC (default 30s, → 504), `heartbeatMs` is the ping gap that detects a half-open link (default 15s, → 503). See [Mesh](/docs/guides/mesh/).
|
||||||
|
|
||||||
## The `App`
|
## The `App`
|
||||||
|
|
||||||
@@ -67,7 +67,7 @@ const app = createApp(options);
|
|||||||
| `explain(route)` | `Explain` | the chain annotated with each node's needs/provides |
|
| `explain(route)` | `Explain` | the chain annotated with each node's needs/provides |
|
||||||
| `graph()` | `GraphView` | the full node + route graph |
|
| `graph()` | `GraphView` | the full node + route graph |
|
||||||
| `toMermaid()` / `toDOT()` | `string` | render the graph |
|
| `toMermaid()` / `toDOT()` | `string` | render the graph |
|
||||||
| `openapi(info?)` | `OpenApiDoc` | structural OpenAPI 3.1 document ([details](/guides/openapi/)) |
|
| `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 `listen()`) |
|
||||||
| `bus` | `Bus` | lifecycle + request event bus |
|
| `bus` | `Bus` | lifecycle + request event bus |
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ title: Decorators
|
|||||||
description: "Full reference for every class, method, and argument decorator."
|
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).
|
Every decorator green-tea exports, grouped by where it applies. All require `experimentalDecorators: true` in your `tsconfig` — see [Why legacy decorators](/docs/concepts/the-graph/#why-legacy-decorators).
|
||||||
|
|
||||||
## Structure
|
## Structure
|
||||||
|
|
||||||
@@ -35,8 +35,8 @@ An app-scope value, built once at boot and cached, addressable by `provides`.
|
|||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| `provides` | `string` | — | the token this provider produces (required) |
|
| `provides` | `string` | — | the token this provider produces (required) |
|
||||||
| `needs` | `string[]` | `[]` | tokens it depends on |
|
| `needs` | `string[]` | `[]` | tokens it depends on |
|
||||||
| `optional` | `boolean` | `false` | if it throws on boot, degrade instead of aborting ([details](/guides/dependency-injection/)) |
|
| `optional` | `boolean` | `false` | if it throws on boot, degrade instead of aborting ([details](/docs/guides/dependency-injection/)) |
|
||||||
| `export` | `boolean` | `false` | expose over the mesh control channel ([mesh](/guides/mesh/)) |
|
| `export` | `boolean` | `false` | expose over the mesh control channel ([mesh](/docs/guides/mesh/)) |
|
||||||
|
|
||||||
### `@Step(options)`
|
### `@Step(options)`
|
||||||
|
|
||||||
@@ -48,19 +48,19 @@ Method decorator. Turns a handler's return value into `{ status?, headers?, body
|
|||||||
|
|
||||||
### `@Html` / `@Html(path, opts?)`
|
### `@Html` / `@Html(path, opts?)`
|
||||||
|
|
||||||
Method decorator. Marks a buffered `GET`/`POST` handler as serving HTML instead of going through the JSON transformer. Three modes ([details](/guides/html/)):
|
Method decorator. Marks a buffered `GET`/`POST` handler as serving HTML instead of going through the JSON transformer. Three modes ([details](/docs/guides/html/)):
|
||||||
|
|
||||||
| Form | Behavior |
|
| Form | Behavior |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `@Html` (bare) | sends the handler's returned string as `text/html` |
|
| `@Html` (bare) | sends the handler's returned string as `text/html` |
|
||||||
| `@Html('file.html')` | serves that file verbatim; the handler's return value is ignored |
|
| `@Html('file.html')` | serves that file verbatim; the handler's return value is ignored |
|
||||||
| `@Html('file.html', { template: true })` | renders the file with the handler's returned data, via the built-in `render` engine or `viewEngine` ([createApp](/reference/createapp/)) |
|
| `@Html('file.html', { template: true })` | renders the file with the handler's returned data, via the built-in `render` engine or `viewEngine` ([createApp](/docs/reference/createapp/)) |
|
||||||
|
|
||||||
Only buffered `GET`/`POST` routes are supported, and `@Html` can't be combined with `@Transformer` on the same handler — both are validated at boot, not per-request.
|
Only buffered `GET`/`POST` routes are supported, and `@Html` can't be combined with `@Transformer` on the same handler — both are validated at boot, not per-request.
|
||||||
|
|
||||||
## Routes
|
## Routes
|
||||||
|
|
||||||
Method decorators on a controller. All accept `(path, opts?)` where `opts = { export?: boolean, duplicates?: 'array' | 'last', maxBodyBytes?: number, maxParts?: number }`. `maxBodyBytes` / `maxParts` override the server-wide [`limits`](/reference/createapp/) for this route only.
|
Method decorators on a controller. All accept `(path, opts?)` where `opts = { export?: boolean, duplicates?: 'array' | 'last', maxBodyBytes?: number, maxParts?: number }`. `maxBodyBytes` / `maxParts` override the server-wide [`limits`](/docs/reference/createapp/) for this route only.
|
||||||
|
|
||||||
| Decorator | Method | Transport |
|
| Decorator | Method | Transport |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
@@ -75,7 +75,7 @@ Method decorators on a controller. All accept `(path, opts?)` where `opts = { ex
|
|||||||
@Post('/avatar', { maxBodyBytes: 5_000_000, maxParts: 20 }) // per-route upload limits
|
@Post('/avatar', { maxBodyBytes: 5_000_000, maxParts: 20 }) // per-route upload limits
|
||||||
```
|
```
|
||||||
|
|
||||||
See [Routing](/guides/routing/) for pattern matching and [Streaming](/guides/streaming/) for the transports.
|
See [Routing](/docs/guides/routing/) for pattern matching and [Streaming](/docs/guides/streaming/) for the transports.
|
||||||
|
|
||||||
## Arguments
|
## Arguments
|
||||||
|
|
||||||
@@ -93,4 +93,4 @@ A handler's signature declares exactly what it wants, in any order.
|
|||||||
| `@inbound()` | the incoming message stream (WebSocket) | `()` |
|
| `@inbound()` | the incoming message stream (WebSocket) | `()` |
|
||||||
| `@abort()` | the request's `AbortSignal` | `()` |
|
| `@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/).
|
Passing a [Standard Schema](/docs/guides/validation/) validates and coerces the value before the handler sees it. Full details in [Argument decorators](/docs/guides/arguments/).
|
||||||
Reference in new issue
Block a user