Compare commits
33
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
180de79462 | ||
|
|
4f504eda11 | ||
|
|
94ab334d85 | ||
|
|
3a8d93320d | ||
|
|
270480b2d6 | ||
|
|
27f1d103ea | ||
|
|
0ad53fa284 | ||
|
|
5fccd3cc8c | ||
|
|
9398a5a2df | ||
|
|
29aafde84c | ||
|
|
dbb996dd4c | ||
|
|
f45ee7d309 | ||
|
|
00aef4541b | ||
|
|
bd3b2556bc | ||
|
|
87c1226e97 | ||
|
|
1db4e01e40 | ||
|
|
74f09d2e0b | ||
|
|
fcd3df7022 | ||
|
|
934fbd4c19 | ||
|
|
d9276a4769 | ||
|
|
3a56e656bd | ||
|
|
a2acec69bf | ||
|
|
9a61ba8646 | ||
|
|
63be0ef8f7 | ||
|
|
8e38fffd77 | ||
|
|
790db661e5 | ||
|
|
63a61aeb0b | ||
|
|
e343ae501f | ||
|
|
e0212d14e5 | ||
|
|
b72883c2ed | ||
|
|
489aa685bb | ||
|
|
c12be9a2f5 | ||
|
|
0541464093 |
No files matched your search
@@ -13,9 +13,16 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
node-version: '18'
|
node-version: '18'
|
||||||
- run: npm ci
|
- run: npm ci
|
||||||
|
- run: npm audit
|
||||||
- run: npm run lint
|
- run: npm run lint
|
||||||
- run: npm run format:check
|
- run: npm run format:check
|
||||||
- run: npm run complexity:check
|
- run: npm run complexity:check
|
||||||
- run: npm run typecheck
|
- run: npm run typecheck
|
||||||
- run: npm test
|
- run: npm test
|
||||||
- run: npm run build
|
- run: npm run build
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: '22.12'
|
||||||
|
- run: npm ci --prefix website
|
||||||
|
- run: npm audit --prefix website
|
||||||
|
- run: npm run docs:build
|
||||||
@@ -23,6 +23,7 @@ jobs:
|
|||||||
registry-url: 'https://registry.npmjs.org'
|
registry-url: 'https://registry.npmjs.org'
|
||||||
- run: npm install -g npm@latest # npm >= 11.5.1 is required for OIDC trusted publishing
|
- run: npm install -g npm@latest # npm >= 11.5.1 is required for OIDC trusted publishing
|
||||||
- run: npm ci
|
- run: npm ci
|
||||||
|
- run: npm audit
|
||||||
# `npm publish` runs prepublishOnly (lint + complexity + typecheck + test + build) first.
|
# `npm publish` runs prepublishOnly (lint + complexity + typecheck + test + build) first.
|
||||||
# No NODE_AUTH_TOKEN — npm exchanges the OIDC id-token for a short-lived publish token.
|
# No NODE_AUTH_TOKEN — npm exchanges the OIDC id-token for a short-lived publish token.
|
||||||
# A prerelease (26.7.0-beta.N) publishes under its channel tag (beta/alpha/rc) so `latest`
|
# A prerelease (26.7.0-beta.N) publishes under its channel tag (beta/alpha/rc) so `latest`
|
||||||
|
|||||||
+14
-10
@@ -1,13 +1,12 @@
|
|||||||
name: Stage → Verdaccio
|
name: Stage → Verdaccio
|
||||||
|
|
||||||
# Staging publish. Runs on GITEA ONLY (the `if` guards against GitHub), on every merge
|
# Staging publish. Runs on GITEA ONLY (the `if` guards against GitHub) for release
|
||||||
# to main. Publishes the package as-is — version comes from package.json (a prerelease
|
# branches. Publishes prereleases to the internal Verdaccio under the `stg` dist-tag.
|
||||||
# like 26.7.1-beta.N) — to the internal Verdaccio under the `stg` dist-tag. This registry
|
# Staging versions are intentionally mutable: an existing prerelease is removed before
|
||||||
# rejects overwriting an existing version, so the step unpublishes it first (a no-op on the
|
# publishing the updated release candidate under the same version.
|
||||||
# first publish) then publishes fresh.
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [main]
|
branches: ['release/**']
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
publish-stg:
|
publish-stg:
|
||||||
@@ -19,13 +18,18 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
node-version: '22'
|
node-version: '22'
|
||||||
- run: npm ci
|
- run: npm ci
|
||||||
# `npm publish` runs prepublishOnly (lint + complexity + typecheck + test + build)
|
- run: npm audit
|
||||||
# as its own gate before anything leaves the machine.
|
- name: Validate release candidate
|
||||||
- name: Publish to Verdaccio (unpublish + publish)
|
run: npm run prepublishOnly
|
||||||
|
- name: Publish prerelease to Verdaccio
|
||||||
env:
|
env:
|
||||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_AUTH }}
|
NODE_AUTH_TOKEN: ${{ secrets.NPM_AUTH }}
|
||||||
run: |
|
run: |
|
||||||
npm config set //npm.svc.zoit.services/:_authToken "$NODE_AUTH_TOKEN"
|
npm config set //npm.svc.zoit.services/:_authToken "$NODE_AUTH_TOKEN"
|
||||||
VER=$(node -p "require('./package.json').version")
|
VER=$(node -p "require('./package.json').version")
|
||||||
|
case "$VER" in
|
||||||
|
*-*) ;;
|
||||||
|
*) echo "Refusing to stage non-prerelease version: $VER" >&2; exit 1 ;;
|
||||||
|
esac
|
||||||
npm unpublish "@green-tea/core@$VER" --registry https://npm.svc.zoit.services --force 2>/dev/null || true
|
npm unpublish "@green-tea/core@$VER" --registry https://npm.svc.zoit.services --force 2>/dev/null || true
|
||||||
npm publish --registry https://npm.svc.zoit.services --tag stg
|
npm publish --ignore-scripts --registry https://npm.svc.zoit.services --tag stg
|
||||||
+35
-10
@@ -3,11 +3,23 @@
|
|||||||
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]
|
||||||
|
|
||||||
|
## [26.8.0-beta.0] - 2026-08-02
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
- **Safe constrained route parameters:** patterns such as `:id(\d+)` match a complete decoded
|
||||||
|
segment. The parser accepts a deliberately small, bounded regex subset and rejects unsafe or
|
||||||
|
malformed expressions at boot. Specificity is now static ▸ constrained param ▸ plain param ▸
|
||||||
|
catch-all; matching remains a linear scan.
|
||||||
|
- **`@Head` and `@Options` route decorators**, explicit-handler priority, buffered-GET HEAD fallback,
|
||||||
|
and automatic `204` OPTIONS responses with deterministic `Allow` ordering. GET implies HEAD and
|
||||||
|
every existing path implies OPTIONS; streaming GET routes do not become implicit HEAD routes.
|
||||||
|
- **OpenAPI route constraints and methods:** constrained path params emit `schema.pattern`, and
|
||||||
|
explicitly declared HEAD/OPTIONS handlers appear as operations without inventing automatic ones.
|
||||||
- **HTML / views:** `@Html` decorator (string, file, and template modes), a zero-dep built-in
|
- **HTML / views:** `@Html` decorator (string, file, and template modes), a zero-dep built-in
|
||||||
template engine (`{{ }}` escaped / `{{{ }}}` raw, exported as `render`) with a `viewEngine`
|
template engine (`{{ }}` escaped / `{{{ }}}` raw, exported as `render`) with a `viewEngine`
|
||||||
bring-your-own hook, and zero-config `static` directory serving (`createApp({ static: true })`).
|
bring-your-own hook, and zero-config `static` directory serving (`createApp({ static: true })`).
|
||||||
@@ -41,6 +53,14 @@ green-tea uses calendar versioning: `YY.MM.PATCH`.
|
|||||||
pings — the platform `WebSocket` on Deno/Bun does not expose `ws.ping()`.
|
pings — the platform `WebSocket` on Deno/Bun does not expose `ws.ping()`.
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
- The Deno WebSocket adapter snapshots request and connection metadata before accepting an upgrade;
|
||||||
|
Deno 2.9 invalidates that metadata once upgraded, which previously broke WebSocket and mesh boots.
|
||||||
|
- Repeated slashes and malformed path encoding now return `400` consistently across Node and Fetch
|
||||||
|
adapters, retaining configured security/CORS headers. `/path` and `/path/` remain equivalent.
|
||||||
|
- Ambiguous same-method route shapes now fail at boot with both declarations named. Effective-shape
|
||||||
|
checks also cover remote mesh conflicts and local routes that shadow a remote export.
|
||||||
|
- HEAD responses always suppress the body while preserving handler status and headers; Fetch
|
||||||
|
responses also avoid constructing forbidden bodies for `204`, `205`, and `304` statuses.
|
||||||
- The opt-in dev routes `/__graph__` (graph viewer) and `/__openapi__` are now
|
- The opt-in dev routes `/__graph__` (graph viewer) and `/__openapi__` are now
|
||||||
served over `app.fetch` too, so they work on every runtime (Deno/Bun/edge),
|
served over `app.fetch` too, so they work on every runtime (Deno/Bun/edge),
|
||||||
not only the Node `app.listen()` path.
|
not only the Node `app.listen()` path.
|
||||||
@@ -54,9 +74,9 @@ green-tea uses calendar versioning: `YY.MM.PATCH`.
|
|||||||
- **`request:step:enter`/`leave` are now emitted for `@Ws` and mesh routes.** Only HTTP routes
|
- **`request:step:enter`/`leave` are now emitted for `@Ws` and mesh routes.** Only HTTP routes
|
||||||
emitted them, so a logging plugin silently observed nothing on a WebSocket route — a gap in a
|
emitted them, so a logging plugin silently observed nothing on a WebSocket route — a gap in a
|
||||||
documented plugin API. All transports now run their steps through one path.
|
documented plugin API. All transports now run their steps through one path.
|
||||||
- **A mesh route exported by two teapots now fails the boot**, naming the route and both teapots,
|
- **A mesh route exported by two teapots now fails the boot**, naming both effective patterns and
|
||||||
instead of silently serving whichever connected first and leaving the other dead. There is no
|
both teapots, instead of silently serving whichever connected first and leaving the other dead.
|
||||||
load balancing to fall back on, so green-tea will not pick for you.
|
There is no load balancing to fall back on, so green-tea will not pick for you.
|
||||||
- **A local route shadowing a remote one now warns.** Local still takes precedence — that is how you
|
- **A local route shadowing a remote one now warns.** Local still takes precedence — that is how you
|
||||||
override a teapot — but a silently shadowed export used to look like a broken teapot.
|
override a teapot — but a silently shadowed export used to look like a broken teapot.
|
||||||
- **`app.close()` closes mesh links even with no server**, so a mesh app booted through `app.fetch`
|
- **`app.close()` closes mesh links even with no server**, so a mesh app booted through `app.fetch`
|
||||||
@@ -68,6 +88,9 @@ green-tea uses calendar versioning: `YY.MM.PATCH`.
|
|||||||
`request:step:leave`.
|
`request:step:leave`.
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
- Root, runtime-only, and website dependency audits are clean after supported package updates and
|
||||||
|
narrow pins for vulnerable transitives. CI audits root + website trees and builds the docs; the
|
||||||
|
GitHub OIDC release workflow audits immediately before its publish gate.
|
||||||
- App-scope providers now boot exactly once (memoized): a second `app.listen()`
|
- App-scope providers now boot exactly once (memoized): a second `app.listen()`
|
||||||
call no longer re-runs provider factories or their side effects.
|
call no longer re-runs provider factories or their side effects.
|
||||||
- **`WsOpenCtx.req`** (available in `@Ws`/`@Sse` handlers) is now a neutral
|
- **`WsOpenCtx.req`** (available in `@Ws`/`@Sse` handlers) is now a neutral
|
||||||
@@ -77,10 +100,11 @@ green-tea uses calendar versioning: `YY.MM.PATCH`.
|
|||||||
`ctx.req`; use `ctx.protocol` / `ctx.ip` / `ctx.query` / `ctx.headers`
|
`ctx.req`; use `ctx.protocol` / `ctx.ip` / `ctx.query` / `ctx.headers`
|
||||||
instead — all still provided.
|
instead — all still provided.
|
||||||
- **Breaking (pre-1.0): transport is now enforced by declaration.** A buffered route
|
- **Breaking (pre-1.0): transport is now enforced by declaration.** A buffered route
|
||||||
(`@Get`/`@Post`/`@Put`/`@Patch`/`@Delete`) whose handler returns an `AsyncIterable`, or a streaming
|
(`@Get`/`@Head`/`@Post`/`@Put`/`@Patch`/`@Delete`/`@Options`) whose handler returns an
|
||||||
route (`@Sse`/`@Ws`) whose handler returns a plain value, now fails with a 500 `TransportMismatchError`
|
`AsyncIterable`, or a streaming route (`@Sse`/`@Ws`) whose handler returns a plain value, now
|
||||||
instead of silently switching behavior. `@Stream` still negotiates both. Declare `@Sse`/`@Stream`/`@Ws`
|
fails with a 500 `TransportMismatchError` instead of silently switching behavior. `@Stream`
|
||||||
to stream — a return value no longer changes a route's wire contract.
|
still negotiates both. Declare `@Sse`/`@Stream`/`@Ws` to stream — a return value no longer
|
||||||
|
changes a route's wire contract.
|
||||||
|
|
||||||
## [26.7.0-beta.0] - 2026-07-07
|
## [26.7.0-beta.0] - 2026-07-07
|
||||||
|
|
||||||
@@ -129,5 +153,6 @@ change before the stable release.
|
|||||||
- **Benchmarks** — reproducible `npm run bench` harness vs Express 5, Fastify 5,
|
- **Benchmarks** — reproducible `npm run bench` harness vs Express 5, Fastify 5,
|
||||||
NestJS, and raw `http`; results in [BENCHMARKS.md](./BENCHMARKS.md).
|
NestJS, and raw `http`; results in [BENCHMARKS.md](./BENCHMARKS.md).
|
||||||
|
|
||||||
[Unreleased]: https://git.svc.zoit.services/Green-Tea/core/compare/26.7.0-beta.0...develop
|
[Unreleased]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.0...main
|
||||||
[26.7.0-beta.0]: https://git.svc.zoit.services/Green-Tea/core/releases/tag/26.7.0-beta.0
|
[26.8.0-beta.0]: https://github.com/Expressive-Tea/green-tea/compare/v26.7.0-beta.0...v26.8.0-beta.0
|
||||||
|
[26.7.0-beta.0]: https://github.com/Expressive-Tea/green-tea/releases/tag/v26.7.0-beta.0
|
||||||
@@ -11,31 +11,47 @@
|
|||||||
not a mutable bag threaded through positional middleware. <i>That's the tea.</i> 🍵
|
not a mutable bag threaded through positional middleware. <i>That's the tea.</i> 🍵
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
`@green-tea/core` — **beta**, RC-track. One runtime dependency: `reflect-metadata`. Two optional peers you install only if you use them: `ws` (WebSocket / mesh) and `busboy` (multipart uploads).
|
---
|
||||||
|
|
||||||
```bash
|
## The problem
|
||||||
npm install @green-tea/core reflect-metadata
|
|
||||||
# optional, only if you use them:
|
```js
|
||||||
npm install ws # WebSocket routes (@Ws) and mesh
|
const user = req.user;
|
||||||
npm install busboy # multipart/form-data file uploads
|
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
It compiles. TypeScript is happy. And it's a prayer — `req.user` exists only if some middleware ran before this handler, which depends on where the router got mounted, which line `app.use()` sits on, and whether a package you installed last sprint quietly inserted itself into the middle of your chain.
|
||||||
|
|
||||||
|
So you keep the whole request in your head: what ran, what's on `req` by now, what order things fire in, which plugin deleted your body parser. That bookkeeping is where the bugs live, and no test or type catches them, because nothing is *wrong* — the code is correct and the app is still broken.
|
||||||
|
|
||||||
## The idea
|
## The idea
|
||||||
|
|
||||||
Most frameworks make you keep the whole request in your head: which middleware ran, whether `req.user` exists by now, what order things fire in, which plugin quietly deleted your body parser. That mental bookkeeping is where bugs live.
|
green-tea puts the request on the page instead. You declare what each step **needs** and **produces**; the framework computes the order, type-checks the wiring, and can print the whole thing.
|
||||||
|
|
||||||
green-tea puts the request on the page instead. You declare what each step **needs** and **produces**; the framework computes the order, type-checks the wiring, and can print the whole thing. A route runs only the steps its handler actually depends on. Boot fails loudly when a dependency is missing, so you never serve `undefined`.
|
- Order is **derived** from your dependencies, never maintained by hand.
|
||||||
|
- Boot **fails loudly** when nothing provides a key, so you never serve `undefined`.
|
||||||
|
- A route runs **only** the steps its handler actually depends on.
|
||||||
|
- `app.explain('/users/:id')` prints the whole chain. Onboarding is reading, not archaeology.
|
||||||
|
|
||||||
Less to hold in your head. That's the tea.
|
Less to hold in your head. That's the tea.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install @green-tea/core@beta reflect-metadata
|
||||||
|
```
|
||||||
|
|
||||||
|
`@green-tea/core` — **beta**, RC-track. One runtime dependency: `reflect-metadata`. Two optional peers you install only if you use them:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install ws # WebSocket routes (@Ws) and mesh
|
||||||
|
npm install busboy # multipart/form-data file uploads
|
||||||
|
```
|
||||||
|
|
||||||
## What's different — and why it matters
|
## What's different — and why it matters
|
||||||
|
|
||||||
- **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 +66,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 +108,8 @@ 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.
|
||||||
|
- **Ceilings that are already on.** `limits` caps body size (`413`), multipart parts, and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. Configurable, and safe before you configure anything.
|
||||||
- **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 +136,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
|
||||||
@@ -189,17 +209,20 @@ The handler signature declares exactly what it wants — in any order, nothing m
|
|||||||
|
|
||||||
`@needs` keys are validated at boot: nothing provides the key → `createApp` throws with a clear error instead of serving `undefined`. Pass a Standard Schema (`@body(User)`) and the value is validated, coerced, and typed before your handler sees it.
|
`@needs` keys are validated at boot: nothing provides the key → `createApp` throws with a clear error instead of serving `undefined`. Pass a Standard Schema (`@body(User)`) and the value is validated, coerced, and typed before your handler sees it.
|
||||||
|
|
||||||
> **Optional providers degrade, they don't crash.** A provider marked `optional: true` that throws on boot does **not** abort startup — it is left unregistered and logged. On `listen()` the app prints a one-line summary of what's running degraded, and the list is queryable via `app.degraded()`. Routes that actually need a degraded provider fail at request time, not at boot. This is deliberate (graceful degradation); wire an alert off `app.degraded()` or the `boot:provider:fail` bus event in production so a degraded start is never silent.
|
> **Optional providers degrade, they don't crash.** A provider marked `optional: true` that throws on boot does **not** abort startup — it is left unregistered and logged. The first serving call (`fetch`, `upgrade`, or `listen`) prints a one-line summary of what's running degraded, and the list is queryable via `app.degraded()`. Routes that actually need a degraded provider fail at request time, not at boot. This is deliberate (graceful degradation); wire an alert off `app.degraded()` or the `boot:provider:fail` bus event in production so a degraded start is never silent.
|
||||||
|
|
||||||
## Routing
|
## Routing
|
||||||
|
|
||||||
Patterns match by segment: static, `:param` (one segment), and a trailing `:name*` **catch-all** that captures the rest of the path — slashes included — into `params.name`. When more than one route matches, the **most specific wins** (static ▸ `:param` ▸ catch-all), independent of registration order. A path that exists under a *different* method returns **`405` with an `Allow` header**, not `404`.
|
Patterns match by segment: static, constrained params such as `:id(\d+)`, plain `:param`, and a trailing `:name*` **catch-all**. The most specific wins (static ▸ constrained ▸ plain param ▸ catch-all), and ambiguous same-method shapes fail at boot instead of depending on registration order.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
|
@Get('/users/:id(\\d+)') // /users/42
|
||||||
@Get('/files/:path*') // /files/img/2026/logo.png → params.path = "img/2026/logo.png"
|
@Get('/files/:path*') // /files/img/2026/logo.png → params.path = "img/2026/logo.png"
|
||||||
```
|
```
|
||||||
|
|
||||||
**Not yet** (post-beta, on the roadmap): regex / typed param constraints like `:id(\d+)`, and route matching is a linear scan — fine for typical route tables, but a radix-tree matcher for very large ones isn't built.
|
`@Head` and `@Options` provide explicit handlers. Otherwise a buffered GET can serve HEAD without a body, and OPTIONS on an existing path returns `204` with canonical `Allow`; other method mismatches return `405`. `/path` and `/path/` are equivalent, while repeated slashes and malformed encoding return `400` rather than being normalized ambiguously. Constraints use a deliberately safe regex subset. See the full [routing guide](https://green-tea.expressive-tea.io/docs/guides/routing/).
|
||||||
|
|
||||||
|
Matching is still a linear scan — fine for typical route tables. A radix tree for very large tables remains post-beta work.
|
||||||
|
|
||||||
## Two layers
|
## Two layers
|
||||||
|
|
||||||
@@ -220,21 +243,24 @@ 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.
|
**No observability layer, either.** There is no built-in logger, no metrics export, and no tracing hooks; core does not depend on a logging library and does not intend to. Today you compose those as steps and providers like anything else. A first-class contract — an injectable logger, structured output, and hooks an OpenTelemetry exporter can attach to — is [tracked as one design](https://github.com/Expressive-Tea/green-tea/issues/10), because doing it piecemeal produces three mechanisms that don't fit together. If your team's definition of production-ready includes shipping traces on day one, this is the gap to know about.
|
||||||
|
|
||||||
|
**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,13 +270,16 @@ 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.
|
||||||
|
- ✅ **router completeness for beta** — safe constrained params, deterministic precedence, explicit/automatic HEAD and OPTIONS, strict path validation, and ambiguity checks across local and mesh routes.
|
||||||
|
- **next** — API freeze + first published release, mesh sub-specs (discovery, load-balancing, failover), official plugins, and a radix-tree matcher for very large route tables.
|
||||||
|
|
||||||
## Versioning
|
## Versioning
|
||||||
|
|
||||||
green-tea uses **calendar versioning**: `YY.M.PATCH` (e.g. `26.7.0` = the first release cut in July 2026, patch 0). The month is **not** zero-padded — npm treats versions as semver, which forbids leading zeros. A version tells you *when* it shipped, not how many breaking changes preceded it — those are always called out in the [CHANGELOG](./CHANGELOG.md).
|
green-tea uses **calendar versioning**: `YY.M.PATCH` (e.g. `26.8.0` = the first release cut in August 2026, patch 0). The month is **not** zero-padded — npm treats versions as semver, which forbids leading zeros. A version tells you *when* it shipped, not how many breaking changes preceded it — those are always called out in the [CHANGELOG](./CHANGELOG.md).
|
||||||
|
|
||||||
**While in beta**, releases carry a `-beta.N` pre-release suffix on the calendar version (e.g. `26.7.0-beta.0`) and publish under the npm `beta` dist-tag — so a plain `npm install @green-tea/core` won't pick one up until the first stable calendar release. The API can still change between betas.
|
**While in beta**, releases carry a `-beta.N` pre-release suffix on the calendar version (e.g. `26.8.0-beta.0`) and publish under the npm `beta` dist-tag. Until the first stable release there is nothing else to install, so `latest` tracks the newest beta too — `npm install @green-tea/core` and `@green-tea/core@beta` resolve to the same version. Install with the explicit `@beta` tag anyway: the day a stable ships, `latest` moves to it and your installs stay on the channel you meant. The API can still change between betas.
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
|||||||
@@ -18,11 +18,11 @@
|
|||||||
"workspace": {
|
"workspace": {
|
||||||
"packageJson": {
|
"packageJson": {
|
||||||
"dependencies": [
|
"dependencies": [
|
||||||
"npm:@eslint/js@^9.39.4",
|
"npm:@eslint/js@^9.39.5",
|
||||||
"npm:@nestjs/common@^11.1.27",
|
"npm:@nestjs/common@^11.1.28",
|
||||||
"npm:@nestjs/core@^11.1.27",
|
"npm:@nestjs/core@^11.1.28",
|
||||||
"npm:@nestjs/platform-express@^11.1.27",
|
"npm:@nestjs/platform-express@^11.1.28",
|
||||||
"npm:@nestjs/platform-fastify@^11.1.27",
|
"npm:@nestjs/platform-fastify@^11.1.28",
|
||||||
"npm:@stylistic/eslint-plugin@^5.10.0",
|
"npm:@stylistic/eslint-plugin@^5.10.0",
|
||||||
"npm:@types/autocannon@^7.12.7",
|
"npm:@types/autocannon@^7.12.7",
|
||||||
"npm:@types/busboy@^1.5.4",
|
"npm:@types/busboy@^1.5.4",
|
||||||
@@ -32,20 +32,31 @@
|
|||||||
"npm:autocannon@8",
|
"npm:autocannon@8",
|
||||||
"npm:busboy@^1.6.0",
|
"npm:busboy@^1.6.0",
|
||||||
"npm:cognitive-complexity-ts@~0.8.2",
|
"npm:cognitive-complexity-ts@~0.8.2",
|
||||||
"npm:eslint@^9.39.4",
|
"npm:esbuild@0.27.2",
|
||||||
|
"npm:eslint@^9.39.5",
|
||||||
"npm:express@^5.2.1",
|
"npm:express@^5.2.1",
|
||||||
"npm:fastify@^5.10.0",
|
"npm:fastify@^5.11.0",
|
||||||
"npm:graphql@^16.9.0",
|
"npm:graphql@^16.9.0",
|
||||||
"npm:prettier@^3.9.4",
|
"npm:miniflare@^4.20260730.0",
|
||||||
|
"npm:prettier@^3.9.6",
|
||||||
"npm:reflect-metadata@0.2.2",
|
"npm:reflect-metadata@0.2.2",
|
||||||
"npm:rxjs@^7.8.2",
|
"npm:rxjs@^7.8.2",
|
||||||
"npm:tsup@^8.5.1",
|
"npm:tsup@^8.5.1",
|
||||||
"npm:tsx@^4.23.0",
|
"npm:tsx@^4.23.5",
|
||||||
"npm:typescript-eslint@^8.63.0",
|
"npm:typescript-eslint@^8.65.0",
|
||||||
"npm:typescript@^5.5.0",
|
"npm:typescript@^5.5.0",
|
||||||
"npm:vitest@2",
|
"npm:vite@^6.4.3",
|
||||||
"npm:ws@^8.21.0"
|
"npm:vitest@^3.2.7",
|
||||||
]
|
"npm:ws@^8.21.1"
|
||||||
|
],
|
||||||
|
"overrides": {
|
||||||
|
"find-my-way": "9.7.0",
|
||||||
|
"autocannon": {
|
||||||
|
"hyperid": {
|
||||||
|
"uuid": "11.1.1"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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.
|
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
# Router correctness and security beta design
|
||||||
|
|
||||||
|
**Date:** 2026-08-02
|
||||||
|
**Target:** `26.8.0-beta.0`
|
||||||
|
**Status:** Approved
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Prepare the August beta by completing the router's missing HTTP behavior, adding safe segment constraints, aligning the public documentation with the code, and removing known dependency vulnerabilities from the core repository and documentation site.
|
||||||
|
|
||||||
|
The release keeps the current linear matcher. A radix tree remains a separate performance project that must earn its complexity through benchmarks.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
This change includes:
|
||||||
|
|
||||||
|
- first-class `HEAD` and `OPTIONS` routes;
|
||||||
|
- automatic `HEAD` fallback to `GET`;
|
||||||
|
- automatic bare `OPTIONS` responses;
|
||||||
|
- correct and deterministic `Allow` headers;
|
||||||
|
- a tolerant trailing-slash policy with rejection of repeated internal slashes;
|
||||||
|
- route-pattern validation at boot;
|
||||||
|
- safe parameter constraints such as `:id(\d+)`;
|
||||||
|
- malformed URI handling as a client error;
|
||||||
|
- duplicate and ambiguous route detection;
|
||||||
|
- OpenAPI projection of constrained parameters;
|
||||||
|
- dependency remediation for the root package and `website/`;
|
||||||
|
- public documentation and changelog updates;
|
||||||
|
- the `26.8.0-beta.0` package-version bump.
|
||||||
|
|
||||||
|
This change excludes:
|
||||||
|
|
||||||
|
- a radix-tree matcher;
|
||||||
|
- arbitrary, unrestricted regular expressions;
|
||||||
|
- manual publication, npm tags, or registry mutations;
|
||||||
|
- mesh discovery, load balancing, and failover.
|
||||||
|
|
||||||
|
## Route semantics
|
||||||
|
|
||||||
|
### Path normalization
|
||||||
|
|
||||||
|
`/users` and `/users/` identify the same route. The matcher removes one trailing slash except for `/`.
|
||||||
|
|
||||||
|
The ingress rejects repeated slashes, including `/users//42`, with `400 Bad Request`. It applies this rule before declared-route matching and static-file fallback, so Node and Fetch adapters behave alike.
|
||||||
|
|
||||||
|
Malformed percent encoding also returns `400 Bad Request`. A malformed path never escapes the matcher as `URIError` and never becomes `500`.
|
||||||
|
|
||||||
|
### Methods
|
||||||
|
|
||||||
|
The public `HttpMethod` type and decorator surface gain `HEAD` and `OPTIONS`. `@Head` and `@Options` accept the same route options as the existing buffered method decorators.
|
||||||
|
|
||||||
|
For `HEAD`, an explicit `HEAD` route wins. Without one, the router matches the corresponding `GET` route and executes its pipeline, but every adapter suppresses the response body. The response retains the status and headers that `GET` would produce. Streaming routes do not serve as implicit `HEAD` handlers.
|
||||||
|
|
||||||
|
For a bare `OPTIONS` request, an explicit `OPTIONS` route wins. Without one, any matching path receives `204 No Content` and an `Allow` header. CORS preflight remains the earlier specialized branch and keeps its configured CORS response.
|
||||||
|
|
||||||
|
`Allow` uses a stable method order. It adds `HEAD` when a buffered `GET` route exists and adds `OPTIONS` whenever the path exists. A request with another unsupported method receives `405` plus the same value.
|
||||||
|
|
||||||
|
### Pattern validation
|
||||||
|
|
||||||
|
The application compiles and validates route patterns during graph construction. Invalid declarations fail before the app serves traffic. Validation rejects:
|
||||||
|
|
||||||
|
- a catch-all outside the final segment;
|
||||||
|
- empty parameter or catch-all names;
|
||||||
|
- repeated parameter names in one pattern;
|
||||||
|
- repeated internal slashes in declarations;
|
||||||
|
- malformed constraints;
|
||||||
|
- duplicate routes with the same method and effective pattern;
|
||||||
|
- patterns that differ only by parameter names and therefore match the same requests with equal precedence.
|
||||||
|
|
||||||
|
Errors name the method, pattern, controller origin, and conflict when applicable.
|
||||||
|
|
||||||
|
### Segment constraints
|
||||||
|
|
||||||
|
The matcher accepts a constrained parameter such as `:id(\d+)`. A constraint matches the whole decoded segment. `/users/12` matches `:id(\d+)`; `/users/12x` does not. A failed constraint remains a normal non-match, so another route may win before the router returns `404`.
|
||||||
|
|
||||||
|
The implementation compiles constraints once and caches the compiled pattern. It accepts a deliberately small regular-expression subset for common numeric, UUID, slug, and enumerated segments. It rejects lookarounds, backreferences, nested groups, nested quantifiers, and other constructs that create a practical ReDoS risk. This keeps the advertised syntax without executing unrestricted attacker-facing regular expressions.
|
||||||
|
|
||||||
|
Specificity remains deterministic:
|
||||||
|
|
||||||
|
1. static segment;
|
||||||
|
2. constrained parameter;
|
||||||
|
3. unconstrained parameter;
|
||||||
|
4. catch-all.
|
||||||
|
|
||||||
|
Registration order resolves only genuine, non-ambiguous ties that survive boot validation.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
`src/http/router.ts` owns pattern parsing, validation, compilation, matching, method fallback, and `Allow` calculation. A compiled representation records normalized segments, parameter names, optional constraints, catch-all state, and specificity.
|
||||||
|
|
||||||
|
`src/metadata.ts` exposes the new method type and decorators. Application graph construction compiles route definitions and reports declaration errors with controller context. The runtime-neutral HTTP core decides `HEAD`, `OPTIONS`, `400`, `404`, and `405`; Node and Fetch adapters only serialize its outcome.
|
||||||
|
|
||||||
|
`src/openapi.ts` converts constrained paths to OpenAPI templates and places the accepted expression in the path parameter's `schema.pattern`. It lists explicit `HEAD` and `OPTIONS` operations but does not invent operations for automatic fallbacks.
|
||||||
|
|
||||||
|
Mesh route manifests carry the expanded method union. Existing wire behavior stays compatible because method values are strings and the change adds values without changing the envelope shape.
|
||||||
|
|
||||||
|
## Error behavior
|
||||||
|
|
||||||
|
Declaration errors fail at boot. Request syntax errors return the standard error envelope with status `400` and pass through the configured `onError` renderer. Pattern non-matches return `404`; method mismatches return `405`; automatic `OPTIONS` returns `204`.
|
||||||
|
|
||||||
|
Error responses keep the existing security and CORS header injection. They do not include decoded attacker input, stack traces, or internal regular-expression details.
|
||||||
|
|
||||||
|
## Dependency remediation
|
||||||
|
|
||||||
|
The published runtime dependency set is already clean: `npm audit --omit=dev` reports zero vulnerabilities. The full development tree and documentation site require remediation.
|
||||||
|
|
||||||
|
The root update will prefer the smallest supported versions that close each advisory:
|
||||||
|
|
||||||
|
- Vitest moves to `3.2.6`, which fixes the critical advisory while preserving Node 18 support;
|
||||||
|
- the Nest benchmark packages move to `11.1.28`, including Multer `2.2.0`;
|
||||||
|
- Miniflare moves to its current compatible patch with fixed Sharp;
|
||||||
|
- Fastify and compatible toolchain packages receive current patch/minor updates;
|
||||||
|
- `find-my-way` receives a narrow `9.7.0` override while Nest pins the vulnerable `9.6.0`, with Nest/Fastify benchmarks as a compatibility gate;
|
||||||
|
- Autocannon's `hyperid`/`uuid` chain receives an isolated remediation only if the benchmark suite proves it compatible; otherwise the benchmark dependency will be replaced or isolated rather than suppressing the advisory.
|
||||||
|
|
||||||
|
The documentation site moves Astro to `7.1.6`, Starlight to `0.41.6`, and resolves the patched PostCSS and SVGO versions. Both lockfiles will be regenerated from their manifests.
|
||||||
|
|
||||||
|
The work will not use `npm audit fix --force`, security-audit suppression, or an incompatible downgrade merely to produce a green report.
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
The change updates:
|
||||||
|
|
||||||
|
- the README routing section and roadmap;
|
||||||
|
- the Routing guide;
|
||||||
|
- the Decorators reference;
|
||||||
|
- the OpenAPI guide where constrained parameters affect output;
|
||||||
|
- the CHANGELOG and package version;
|
||||||
|
- the Starlight 404 configuration that currently emits a build warning.
|
||||||
|
|
||||||
|
Examples will state the trailing-slash policy, double-slash rejection, automatic method behavior, constraint limits, and the deferred radix-tree work.
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
The implementation adds unit and integration coverage for:
|
||||||
|
|
||||||
|
- explicit and implicit `HEAD`;
|
||||||
|
- body suppression and header preservation;
|
||||||
|
- explicit and automatic `OPTIONS`;
|
||||||
|
- CORS-preflight precedence;
|
||||||
|
- deterministic `Allow` values;
|
||||||
|
- trailing slash equivalence and double-slash rejection;
|
||||||
|
- invalid percent encoding;
|
||||||
|
- route-declaration failures;
|
||||||
|
- constrained matches, non-matches, precedence, and unsafe-expression rejection;
|
||||||
|
- OpenAPI path and `schema.pattern` output;
|
||||||
|
- Node and Fetch parity;
|
||||||
|
- mesh method serialization where relevant.
|
||||||
|
|
||||||
|
The release gate runs:
|
||||||
|
|
||||||
|
- root and website audits with zero known vulnerabilities;
|
||||||
|
- the runtime-only root audit separately;
|
||||||
|
- Node tests, typecheck, lint, format, complexity, and build;
|
||||||
|
- Deno, Bun, and Edge suites when their runtimes are available;
|
||||||
|
- documentation build without the current 404 warning;
|
||||||
|
- framework benchmarks, including the Nest/Fastify paths affected by overrides;
|
||||||
|
- `npm pack --dry-run` to inspect the published artifact.
|
||||||
|
|
||||||
|
## CI and publication flow
|
||||||
|
|
||||||
|
Gitea remains the source of the release flow:
|
||||||
|
|
||||||
|
1. CI runs on `develop` and `main`.
|
||||||
|
2. A merge to Gitea `main` publishes the package to internal Verdaccio under `stg`.
|
||||||
|
3. Gitea's promotion workflow pushes only `main` and version tags to GitHub.
|
||||||
|
4. A promoted `v*` tag triggers GitHub's `release.yml`.
|
||||||
|
5. GitHub publishes to npm through Trusted Publishing/OIDC and derives `beta` from `26.8.0-beta.0`.
|
||||||
|
|
||||||
|
This implementation prepares the version and validates the workflows. It does not merge to `main`, create a release tag, publish to Verdaccio, or invoke `npm publish` locally.
|
||||||
@@ -0,0 +1,679 @@
|
|||||||
|
# Router Security Beta Implementation Plan
|
||||||
|
|
||||||
|
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
|
||||||
|
|
||||||
|
**Goal:** Ship `26.8.0-beta.0` with complete HEAD/OPTIONS behavior, safe constrained route parameters, strict path handling, accurate documentation, and clean dependency audits.
|
||||||
|
|
||||||
|
**Architecture:** Keep the linear route table, but compile and validate each pattern once. Centralize path syntax, matching, method fallback, and `Allow` calculation in the runtime-neutral HTTP layer so Node and Fetch adapters stay behaviorally identical. Remediate tooling dependencies without changing the package's Node 18 runtime contract or its one required runtime dependency.
|
||||||
|
|
||||||
|
**Tech Stack:** TypeScript, legacy decorators, Node HTTP, Fetch API, Vitest, OpenAPI 3.1, Astro/Starlight, npm lockfiles, GitHub/Gitea Actions.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 1: Compile and validate route patterns
|
||||||
|
|
||||||
|
**Skills:** `@superpowers:test-driven-development`, `@security-review`
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `src/http/router.ts`
|
||||||
|
- Modify: `src/http/types.ts`
|
||||||
|
- Test: `test/router.test.ts`
|
||||||
|
|
||||||
|
**Step 1: Write failing compiler tests**
|
||||||
|
|
||||||
|
Add tests that establish the supported grammar and precedence:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
describe('compilePattern', () => {
|
||||||
|
it('compiles constrained params and gives them precedence over plain params', () => {
|
||||||
|
const routes = [route('GET', '/users/:value'), route('GET', '/users/:id(\\d+)')];
|
||||||
|
expect(matchRoute(routes, 'GET', '/users/42')?.def.pattern).toBe('/users/:id(\\d+)');
|
||||||
|
expect(matchRoute(routes, 'GET', '/users/diego')?.def.pattern).toBe('/users/:value');
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
'/files/:rest*/tail',
|
||||||
|
'/users/:',
|
||||||
|
'/users/:id/:id',
|
||||||
|
'/users//:id',
|
||||||
|
'/users/:id((a+)+)',
|
||||||
|
'/users/:id((?=a)a)',
|
||||||
|
'/users/:id(\\1)',
|
||||||
|
])('rejects invalid or unsafe pattern %s', (pattern) => {
|
||||||
|
expect(() => compilePattern(pattern)).toThrow(/invalid route pattern|unsafe route constraint/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
Also cover numeric, UUID-like, slug, and bounded-quantifier examples; a constraint must match the complete decoded segment.
|
||||||
|
|
||||||
|
**Step 2: Run the focused test and confirm RED**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx vitest run test/router.test.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: FAIL because `compilePattern` and constrained matching do not exist.
|
||||||
|
|
||||||
|
**Step 3: Implement the compiled representation**
|
||||||
|
|
||||||
|
In `src/http/router.ts`, add:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
type CompiledSegment =
|
||||||
|
| { kind: 'static'; value: string }
|
||||||
|
| { kind: 'param'; name: string; constraint?: RegExp }
|
||||||
|
| { kind: 'catchAll'; name: string };
|
||||||
|
|
||||||
|
export interface CompiledPattern {
|
||||||
|
source: string;
|
||||||
|
normalized: string;
|
||||||
|
shape: string;
|
||||||
|
segments: CompiledSegment[];
|
||||||
|
kinds: number[]; // static=3, constrained=2, param=1; catch-all stored separately
|
||||||
|
catchAll: boolean;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Implement `compilePattern(pattern)`, `matchCompiled(compiled, pathSegments)`, and a string-keyed cache used by `matchPattern`. Parse `:name(expr)` only when the closing `)` ends the segment. Anchor accepted constraints as `^(?:${expr})$`.
|
||||||
|
|
||||||
|
Implement `assertSafeConstraint` as a small whitelist parser. Permit literals, character classes, `\\d`/`\\w`/`\\s` classes, escaped literals, and simple quantifiers. Reject expression length above 128, groups, alternation, anchors, lookarounds, backreferences, nested quantifiers, and adjacent unbounded quantified atoms without a separating literal. Do not add a runtime dependency.
|
||||||
|
|
||||||
|
Build `shape` from segment kinds and constraint source so `:id` and `:name` have the same effective shape.
|
||||||
|
|
||||||
|
**Step 4: Run tests and confirm GREEN**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx vitest run test/router.test.ts
|
||||||
|
npm run typecheck
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: all router tests pass and TypeScript reports no errors.
|
||||||
|
|
||||||
|
**Step 5: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add src/http/router.ts src/http/types.ts test/router.test.ts
|
||||||
|
git commit -s -m "feat(router): compile safe constrained patterns"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Task 2: Validate request paths and route-table ambiguity
|
||||||
|
|
||||||
|
**Skills:** `@superpowers:test-driven-development`, `@security-review`
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `src/http/router.ts`
|
||||||
|
- Modify: `src/app/index.ts`
|
||||||
|
- Modify: `src/app/types.ts`
|
||||||
|
- Test: `test/router.test.ts`
|
||||||
|
- Test: `test/app.test.ts`
|
||||||
|
|
||||||
|
**Step 1: Write failing path-policy tests**
|
||||||
|
|
||||||
|
Add router tests for the approved normalization:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
expect(normalizeRequestPath('/users')).toBe('/users');
|
||||||
|
expect(normalizeRequestPath('/users/')).toBe('/users');
|
||||||
|
expect(normalizeRequestPath('/')).toBe('/');
|
||||||
|
expect(() => normalizeRequestPath('/users//42')).toThrow(/repeated slash/);
|
||||||
|
expect(() => normalizeRequestPath('/users/%E0%A4%A')).toThrow(/malformed path encoding/);
|
||||||
|
```
|
||||||
|
|
||||||
|
Add app-construction tests proving that identical routes and routes that differ only by parameter names fail before serving:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
expect(() => createApp({ modules: [DuplicateRouteModule] })).toThrow(/ambiguous route.*GET/);
|
||||||
|
```
|
||||||
|
|
||||||
|
Cover the same path under different methods as valid.
|
||||||
|
|
||||||
|
**Step 2: Run focused tests and confirm RED**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx vitest run test/router.test.ts test/app.test.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: FAIL because normalization and ambiguity checks are absent.
|
||||||
|
|
||||||
|
**Step 3: Implement request normalization**
|
||||||
|
|
||||||
|
Add `InvalidRequestPathError` and `normalizeRequestPath(path)` to `src/http/router.ts`. Strip exactly one trailing slash except at root, reject `//`, and call `decodeURIComponent` on every raw segment only to validate encoding. Matching still compares static segments according to the existing encoded-path contract and decodes captured values once.
|
||||||
|
|
||||||
|
**Step 4: Implement route-table validation**
|
||||||
|
|
||||||
|
Store a `compiled` pattern on each internal `RoutePlan`/`RouteDef`, or expose a shared cache accessor if that avoids duplicating state. During `collectControllers`, compile each joined pattern and compare the candidate's method plus `shape` with existing route plans. Throw an error that includes method, pattern, controller/handler, and conflicting declaration.
|
||||||
|
|
||||||
|
Apply the same validation after remote mesh routes join. A remote conflict must name both mesh owner URLs rather than silently selecting registration order.
|
||||||
|
|
||||||
|
**Step 5: Run focused and mesh tests**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx vitest run test/router.test.ts test/app.test.ts test/mesh/fetch-boot.test.ts test/mesh/integration.test.ts
|
||||||
|
npm run typecheck
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: all selected tests pass.
|
||||||
|
|
||||||
|
**Step 6: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add src/http/router.ts src/app/index.ts src/app/types.ts test/router.test.ts test/app.test.ts
|
||||||
|
git commit -s -m "fix(router): reject invalid and ambiguous paths"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Task 3: Add HEAD and OPTIONS to the public decorator API
|
||||||
|
|
||||||
|
**Skills:** `@superpowers:test-driven-development`
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `src/metadata.ts`
|
||||||
|
- Modify: `src/index.ts`
|
||||||
|
- Modify: `src/signals.ts`
|
||||||
|
- Test: `test/metadata.test.ts`
|
||||||
|
- Test: `test/smoke.test.ts`
|
||||||
|
|
||||||
|
**Step 1: Write failing decorator tests**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
class Methods {
|
||||||
|
@Head('/resource') head() {}
|
||||||
|
@Options('/resource') options() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(getRoutes(Methods).map(({ method }) => method)).toEqual(['HEAD', 'OPTIONS']);
|
||||||
|
```
|
||||||
|
|
||||||
|
Add a public-barrel smoke test that imports `Head`, `Options`, and `HttpMethod` from `src/index.ts`.
|
||||||
|
|
||||||
|
**Step 2: Run tests and confirm RED**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx vitest run test/metadata.test.ts test/smoke.test.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: FAIL because the exports do not exist.
|
||||||
|
|
||||||
|
**Step 3: Implement decorators and messages**
|
||||||
|
|
||||||
|
Extend `HttpMethod`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS';
|
||||||
|
```
|
||||||
|
|
||||||
|
Create buffered `Head` and `Options` decorators through `routeDecorator`, export them from `src/index.ts`, and update `TransportMismatchError`'s buffered-method message. Keep `@Html` restricted to GET/POST and update its rejection text to include HEAD/OPTIONS.
|
||||||
|
|
||||||
|
**Step 4: Run tests and typecheck**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx vitest run test/metadata.test.ts test/smoke.test.ts test/transport-enforcement.test.ts test/views-html.test.ts
|
||||||
|
npm run typecheck
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: all pass.
|
||||||
|
|
||||||
|
**Step 5: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add src/metadata.ts src/index.ts src/signals.ts test/metadata.test.ts test/smoke.test.ts
|
||||||
|
git commit -s -m "feat(router): expose HEAD and OPTIONS decorators"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Task 4: Implement runtime-neutral HEAD, OPTIONS, and path errors
|
||||||
|
|
||||||
|
**Skills:** `@superpowers:test-driven-development`, `@security-review`
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `src/http/router.ts`
|
||||||
|
- Modify: `src/http/core.ts`
|
||||||
|
- Modify: `src/http/web.ts`
|
||||||
|
- Modify: `src/http/server.ts`
|
||||||
|
- Test: `test/router.test.ts`
|
||||||
|
- Test: `test/http.test.ts`
|
||||||
|
- Test: `test/fetch.test.ts`
|
||||||
|
- Test: `test/parity.test.ts`
|
||||||
|
- Test: `test/transport-security.test.ts`
|
||||||
|
|
||||||
|
**Step 1: Write failing method-semantics tests**
|
||||||
|
|
||||||
|
Cover these cases in both Node and `app.fetch`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Explicit HEAD wins.
|
||||||
|
// Otherwise buffered GET runs once, retains status/headers, and emits an empty body.
|
||||||
|
// Streaming GET does not become implicit HEAD.
|
||||||
|
// Explicit OPTIONS wins.
|
||||||
|
// Automatic OPTIONS returns 204 and deterministic Allow.
|
||||||
|
// GET implies HEAD; every existing path implies OPTIONS.
|
||||||
|
// CORS preflight still runs before explicit/automatic OPTIONS.
|
||||||
|
// Double slash and malformed encoding return 400 with security headers.
|
||||||
|
```
|
||||||
|
|
||||||
|
Use a canonical expected header such as `GET, HEAD, POST, OPTIONS`.
|
||||||
|
|
||||||
|
**Step 2: Run focused tests and confirm RED**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx vitest run test/router.test.ts test/http.test.ts test/fetch.test.ts test/parity.test.ts test/transport-security.test.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: new assertions fail under the current 405 behavior.
|
||||||
|
|
||||||
|
**Step 3: Implement method resolution**
|
||||||
|
|
||||||
|
In `src/http/router.ts`, add a stable method order and helpers:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export interface ResolvedRoute extends MatchedRoute {
|
||||||
|
implicitHead: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveRoute(routes: RouteDef[], method: string, path: string): ResolvedRoute | undefined;
|
||||||
|
export function allowedMethods(routes: RouteDef[], path: string): HttpMethod[];
|
||||||
|
```
|
||||||
|
|
||||||
|
`resolveRoute` tries explicit method first. For HEAD only, it falls back to a matching buffered GET. `allowedMethods` deduplicates explicit methods, adds HEAD for buffered GET, adds OPTIONS for every existing path, and sorts canonically.
|
||||||
|
|
||||||
|
**Step 4: Implement core outcomes**
|
||||||
|
|
||||||
|
At the start of `handle`, normalize the path and render `InvalidRequestPathError` as `400`. Preserve the existing CORS-preflight branch. Resolve explicit OPTIONS normally; otherwise return buffered `204` with `allow` and empty body. For an implicit or explicit HEAD route, run the normal pipeline but replace a buffered result body with `''`. Reject a stream outcome for HEAD as a transport mismatch rather than opening a stream.
|
||||||
|
|
||||||
|
**Step 5: Align body acquisition in both adapters**
|
||||||
|
|
||||||
|
Replace early `matchRoute` calls in `src/http/web.ts` and `src/http/server.ts` with the same normalization and resolution helper used by `handle`. If path validation fails before body acquisition, render `400` through `onError` with injected security/CORS headers. Never read a request body for automatic OPTIONS or an invalid path.
|
||||||
|
|
||||||
|
**Step 6: Run focused tests and confirm GREEN**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx vitest run test/router.test.ts test/http.test.ts test/fetch.test.ts test/parity.test.ts test/transport-security.test.ts
|
||||||
|
npm run typecheck
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: all selected tests pass with Node/Fetch parity.
|
||||||
|
|
||||||
|
**Step 7: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add src/http/router.ts src/http/core.ts src/http/web.ts src/http/server.ts test/router.test.ts test/http.test.ts test/fetch.test.ts test/parity.test.ts test/transport-security.test.ts
|
||||||
|
git commit -s -m "feat(http): complete HEAD and OPTIONS semantics"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Task 5: Project constraints into OpenAPI and introspection
|
||||||
|
|
||||||
|
**Skills:** `@superpowers:test-driven-development`
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `src/openapi.ts`
|
||||||
|
- Modify: `src/app/introspect.ts`
|
||||||
|
- Test: `test/openapi.test.ts`
|
||||||
|
- Test: `test/graph-viz.test.ts`
|
||||||
|
|
||||||
|
**Step 1: Write failing OpenAPI tests**
|
||||||
|
|
||||||
|
Add `@Get('/:id(\\d+)')`, explicit `@Head`, and explicit `@Options` routes to the fixture. Assert:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
expect(doc.paths['/api/users/{id}']).toBeDefined();
|
||||||
|
expect((doc.paths['/api/users/{id}'].get as any).parameters).toContainEqual(
|
||||||
|
expect.objectContaining({ name: 'id', schema: { type: 'string', pattern: '\\d+' } }),
|
||||||
|
);
|
||||||
|
expect(doc.paths['/api/users/{id}'].head).toBeDefined();
|
||||||
|
expect(doc.paths['/api/users/{id}'].options).toBeDefined();
|
||||||
|
```
|
||||||
|
|
||||||
|
Assert that automatic HEAD/OPTIONS operations are not invented.
|
||||||
|
|
||||||
|
**Step 2: Run tests and confirm RED**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx vitest run test/openapi.test.ts test/graph-viz.test.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: constrained template parsing or schema assertions fail.
|
||||||
|
|
||||||
|
**Step 3: Implement projection**
|
||||||
|
|
||||||
|
Reuse the route compiler's parsed segment data instead of parsing the syntax a second way. Convert params and catch-alls to `{name}`. Add `schema.pattern` only for constrained params. Ensure `inspect`, `explain`, Mermaid, and DOT retain the human-readable original pattern.
|
||||||
|
|
||||||
|
**Step 4: Run tests and typecheck**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx vitest run test/openapi.test.ts test/graph-viz.test.ts test/app.test.ts
|
||||||
|
npm run typecheck
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: all pass.
|
||||||
|
|
||||||
|
**Step 5: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add src/openapi.ts src/app/introspect.ts test/openapi.test.ts test/graph-viz.test.ts
|
||||||
|
git commit -s -m "feat(openapi): document constrained route params"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Task 6: Remove root and website dependency advisories
|
||||||
|
|
||||||
|
**Skills:** `@security-review`
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `package.json`
|
||||||
|
- Modify: `package-lock.json`
|
||||||
|
- Modify: `website/package.json`
|
||||||
|
- Modify: `website/package-lock.json`
|
||||||
|
- Test: `bench/servers/nestjs-express.ts`
|
||||||
|
- Test: `bench/servers/nestjs-fastify.ts`
|
||||||
|
|
||||||
|
**Step 1: Record the failing audit baseline**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm audit
|
||||||
|
npm --prefix website audit
|
||||||
|
npm audit --omit=dev
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: root full audit reports 17 advisories, website reports 3, runtime-only root reports 0.
|
||||||
|
|
||||||
|
**Step 2: Apply supported direct updates**
|
||||||
|
|
||||||
|
Update root dependencies with explicit commands so the manifests and lockfile agree:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install --save-dev vitest@^3.2.6 \
|
||||||
|
@nestjs/common@^11.1.28 @nestjs/core@^11.1.28 \
|
||||||
|
@nestjs/platform-express@^11.1.28 @nestjs/platform-fastify@^11.1.28 \
|
||||||
|
fastify@^5.11.0 miniflare@^4.20260730.0 \
|
||||||
|
@eslint/js@^9.39.5 eslint@^9.39.5 prettier@^3.9.6 \
|
||||||
|
tsx@^4.23.5 typescript-eslint@^8.65.0 ws@^8.21.1
|
||||||
|
npm --prefix website install astro@^7.1.6 @astrojs/starlight@^0.41.6
|
||||||
|
```
|
||||||
|
|
||||||
|
Do not bump TypeScript, ESLint, or GraphQL across their next major versions.
|
||||||
|
|
||||||
|
**Step 3: Add narrow overrides only for unresolved vulnerable transitives**
|
||||||
|
|
||||||
|
Run `npm audit --json` and inspect the exact remaining paths. Add the smallest overrides justified by that output, initially:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"overrides": {
|
||||||
|
"@nestjs/platform-fastify": {
|
||||||
|
"find-my-way": "9.7.0"
|
||||||
|
},
|
||||||
|
"autocannon": {
|
||||||
|
"hyperid": {
|
||||||
|
"uuid": "11.1.1"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
If npm rejects nested override syntax, express the same ownership with `$` references or the supported nested-object form for the installed npm version. Never add a global override when a package-scoped one works.
|
||||||
|
|
||||||
|
**Step 4: Prove compatibility before accepting overrides**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run typecheck
|
||||||
|
npm test
|
||||||
|
npm run bench
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: tests pass; Express, Fastify, Nest Express, and Nest Fastify scenarios start and complete; Autocannon produces all scenario rows. If the UUID override breaks Autocannon, revert only that override and replace/isolate Autocannon in a follow-up commit within this task until the full audit is clean.
|
||||||
|
|
||||||
|
**Step 5: Verify clean audits**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm audit
|
||||||
|
npm audit --omit=dev
|
||||||
|
npm --prefix website audit
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: all three commands exit 0 with zero vulnerabilities.
|
||||||
|
|
||||||
|
**Step 6: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add package.json package-lock.json website/package.json website/package-lock.json
|
||||||
|
git commit -s -m "chore(deps): remediate security advisories"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Task 7: Add security and documentation gates to CI
|
||||||
|
|
||||||
|
**Skills:** `@security-review`
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `.github/workflows/ci.yml`
|
||||||
|
- Modify: `.github/workflows/release.yml`
|
||||||
|
|
||||||
|
**Step 1: Define the expected gates**
|
||||||
|
|
||||||
|
The CI job must install root and website lockfiles, audit both, build docs, and preserve the existing Node 18 package gate. The GitHub-only release job must audit the root tree immediately after `npm ci` and before `npm publish`.
|
||||||
|
|
||||||
|
**Step 2: Update CI**
|
||||||
|
|
||||||
|
Add these steps after the root `npm ci`:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
- run: npm audit
|
||||||
|
- run: npm ci --prefix website
|
||||||
|
- run: npm audit --prefix website
|
||||||
|
- run: npm run docs:build
|
||||||
|
```
|
||||||
|
|
||||||
|
Keep lint, format, complexity, typecheck, test, and build unchanged.
|
||||||
|
|
||||||
|
**Step 3: Update the GitHub release gate**
|
||||||
|
|
||||||
|
Add `npm audit` after `npm ci` in `.github/workflows/release.yml`. Do not change the tag trigger, Gitea server guard, Node 22 OIDC setup, dist-tag derivation, or `npm publish` command.
|
||||||
|
|
||||||
|
Do not modify `stage.yml` or `promote.yml`; their verified GitFlow responsibilities remain:
|
||||||
|
|
||||||
|
- Gitea `main` → Verdaccio `stg`;
|
||||||
|
- Gitea `main` and `v*` tags → GitHub;
|
||||||
|
- GitHub `v*` → npm OIDC release.
|
||||||
|
|
||||||
|
**Step 4: Validate workflow syntax and diff**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx prettier --check .github/workflows/ci.yml .github/workflows/release.yml
|
||||||
|
git diff --check
|
||||||
|
```
|
||||||
|
|
||||||
|
If Prettier does not parse the workflow format in this repo, inspect with `ruby -e "require 'yaml'; YAML.load_file(ARGV[0])" <file>` and record that command instead.
|
||||||
|
|
||||||
|
**Step 5: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add .github/workflows/ci.yml .github/workflows/release.yml
|
||||||
|
git commit -s -m "ci: gate releases on clean dependency audits"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Task 8: Audit and align the complete website documentation
|
||||||
|
|
||||||
|
**Skills:** `@writing-clearly-and-concisely`
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Review: every page under `website/src/content/docs/`
|
||||||
|
- Modify: `website/src/content/docs/guides/routing.md`
|
||||||
|
- Modify: `website/src/content/docs/reference/decorators.md`
|
||||||
|
- Modify: `website/src/content/docs/guides/openapi.md`
|
||||||
|
- Modify: any other website page whose API, behavior, example, or cross-link has drifted from the code
|
||||||
|
- Create: `website/src/content/docs/404.md`
|
||||||
|
|
||||||
|
**Step 1: Build a code-backed website documentation inventory**
|
||||||
|
|
||||||
|
Compare every website page with the current public exports in `src/index.ts`, app options and methods in `src/app/types.ts`, decorator metadata in `src/metadata.ts`, routing behavior in `src/http/router.ts`, and the executable tests. Search the whole documentation tree for stale method lists, obsolete limitations, old error semantics, old beta/version examples, broken internal links, and examples that no longer typecheck conceptually.
|
||||||
|
|
||||||
|
Do not change a claim from memory. Each correction must be supported by code or a passing test.
|
||||||
|
|
||||||
|
**Step 2: Update routing documentation from the verified behavior**
|
||||||
|
|
||||||
|
Document:
|
||||||
|
|
||||||
|
- `@Head` and `@Options`;
|
||||||
|
- explicit-route priority and automatic fallbacks;
|
||||||
|
- canonical `Allow` behavior;
|
||||||
|
- `/path` equals `/path/`;
|
||||||
|
- `//` and malformed encoding return `400`;
|
||||||
|
- catch-all must be final;
|
||||||
|
- `:id(\\d+)`, whole-segment matching, precedence, and the safe-subset restriction;
|
||||||
|
- the matcher remains linear and a radix tree remains deferred.
|
||||||
|
|
||||||
|
Remove the current statement that bare OPTIONS returns 405.
|
||||||
|
|
||||||
|
**Step 3: Align cross-cutting website references**
|
||||||
|
|
||||||
|
At minimum, verify and correct:
|
||||||
|
|
||||||
|
- every buffered-method list to include or intentionally exclude `HEAD`/`OPTIONS` according to the actual API;
|
||||||
|
- `405`, automatic `OPTIONS`, implicit `HEAD`, CORS-preflight, malformed-path, and security-header descriptions;
|
||||||
|
- OpenAPI behavior: explicit HEAD/OPTIONS appear as operations, constrained params produce `schema.pattern`, and automatic fallbacks remain absent;
|
||||||
|
- mesh route-conflict wording after effective-pattern normalization;
|
||||||
|
- examples and links between routing, decorators, errors, HTML, streaming, security, OpenAPI, and `createApp` reference pages;
|
||||||
|
- navigation/frontmatter descriptions that still advertise the old router surface.
|
||||||
|
|
||||||
|
Keep intentional historical or roadmap statements only when they remain true.
|
||||||
|
|
||||||
|
**Step 4: Fix the Starlight 404 warning**
|
||||||
|
|
||||||
|
Create the missing `404.md` entry with valid Starlight frontmatter and concise navigation back to the docs index. Run `npm run docs:build` and confirm the line `Entry docs → 404 was not found` disappears.
|
||||||
|
|
||||||
|
**Step 5: Validate the whole website documentation tree**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run docs:build
|
||||||
|
npm --prefix website audit
|
||||||
|
rg -n 'Not built|bare `OPTIONS`|returns `405`|@Get.*@Post.*@Put.*@Patch.*@Delete' website/src/content/docs
|
||||||
|
rg -n '\]\(/docs/' website/src/content/docs
|
||||||
|
git diff --check
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: all 23+ pages build without the missing-404 warning, the website audit remains clean, obsolete router claims are gone, and every changed claim has a code/test source.
|
||||||
|
|
||||||
|
**Step 6: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add website/src/content/docs
|
||||||
|
git commit -s -m "docs(website): align guides with router behavior"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Task 9: Align package documentation and prepare the August beta
|
||||||
|
|
||||||
|
**Skills:** `@writing-clearly-and-concisely`
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `README.md`
|
||||||
|
- Modify: `CHANGELOG.md`
|
||||||
|
- Modify: `src/index.ts`
|
||||||
|
- Modify: `package.json`
|
||||||
|
- Modify: `package-lock.json`
|
||||||
|
|
||||||
|
**Step 1: Align the package-facing documentation**
|
||||||
|
|
||||||
|
Update README routing, roadmap, method, security, and beta-status claims from the same verified behavior documented in the website. Keep README concise and link to the complete website guides rather than duplicating their full reference material.
|
||||||
|
|
||||||
|
**Step 2: Bump the beta version consistently**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm version 26.8.0-beta.0 --no-git-tag-version
|
||||||
|
```
|
||||||
|
|
||||||
|
Update `src/index.ts`'s `VERSION` constant and add a `26.8.0-beta.0` CHANGELOG entry covering routes, security remediation, docs, and compatibility. Confirm README's CalVer examples remain accurate.
|
||||||
|
|
||||||
|
**Step 3: Verify docs and version consistency**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run docs:build
|
||||||
|
node -e "const p=require('./package.json'); const l=require('./package-lock.json'); if (p.version !== l.version || p.version !== l.packages[''].version) process.exit(1)"
|
||||||
|
rg -n '26\.7\.0-beta\.0|Not built|bare `OPTIONS`' README.md CHANGELOG.md src website/src/content/docs
|
||||||
|
git diff --check
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: package versions agree, website docs still build, and any old beta string is retained only in historical release examples.
|
||||||
|
|
||||||
|
**Step 4: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add README.md CHANGELOG.md src/index.ts package.json package-lock.json
|
||||||
|
git commit -s -m "docs: document router completeness for beta"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Task 10: Run the complete release-candidate verification
|
||||||
|
|
||||||
|
**Skills:** `@superpowers:verification-before-completion`, `@security-review`
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify only if a verification failure reveals an in-scope defect.
|
||||||
|
|
||||||
|
**Step 1: Run static and Node gates**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run lint
|
||||||
|
npm run format:check
|
||||||
|
npm run complexity:check
|
||||||
|
npm run typecheck
|
||||||
|
npm run typecheck:bench
|
||||||
|
npm test
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: every command exits 0. Record the existing lint-warning count separately; introduce no new warnings.
|
||||||
|
|
||||||
|
**Step 2: Run multi-runtime gates**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run test:deno
|
||||||
|
npm run test:bun
|
||||||
|
npm run test:edge
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: every installed runtime suite exits 0. If a runtime is unavailable, report the exact missing command; do not claim that suite passed.
|
||||||
|
|
||||||
|
**Step 3: Run security, docs, and benchmark gates**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm audit
|
||||||
|
npm audit --omit=dev
|
||||||
|
npm --prefix website audit
|
||||||
|
npm run docs:build
|
||||||
|
npm run bench
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: zero advisories; docs build without warning; all benchmark scenarios complete.
|
||||||
|
|
||||||
|
**Step 4: Inspect the publish artifact without publishing**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm pack --dry-run
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: package contains `dist`, assets, README, CHANGELOG, and LICENSE; version is `26.8.0-beta.0`; no docs worktree, tests, secrets, or local environment files appear.
|
||||||
|
|
||||||
|
**Step 5: Review branch and workflow boundaries**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git status --short --branch
|
||||||
|
git log --oneline --decorate develop..HEAD
|
||||||
|
git diff --check develop...HEAD
|
||||||
|
git diff --stat develop...HEAD
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: clean `feat/router-security-beta`; all commits carry `Signed-off-by`; no tag, registry publication, `main` merge, or workflow secret change occurred.
|
||||||
|
|
||||||
|
**Step 6: Commit any verification-only repair**
|
||||||
|
|
||||||
|
Only if Step 1–5 exposed an in-scope defect:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add <exact repaired files>
|
||||||
|
git commit -s -m "fix: address beta verification findings"
|
||||||
|
```
|
||||||
|
|
||||||
|
Re-run the failed gate and the complete related suite after any repair.
|
||||||
@@ -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)
|
|
||||||
```
|
|
||||||
Generated
+1240
-1095
File diff suppressed because it is too large.
Load diff
+34
-15
@@ -1,9 +1,17 @@
|
|||||||
{
|
{
|
||||||
"name": "@green-tea/core",
|
"name": "@green-tea/core",
|
||||||
"version": "26.7.0-beta.0",
|
"version": "26.8.0-beta.0",
|
||||||
"description": "A zen, opinionated, type-safe framework — your API is a graph, not a middleware chain.",
|
"description": "You declare what each step needs and provides; green-tea computes the execution order, fails at boot if something is missing, and prints the whole pipeline. HTTP, SSE and WebSocket on Node, Deno, Bun and the edge.",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"author": "green-tea contributors",
|
"author": "green-tea contributors",
|
||||||
|
"repository": {
|
||||||
|
"type": "git",
|
||||||
|
"url": "git+https://github.com/Expressive-Tea/green-tea.git"
|
||||||
|
},
|
||||||
|
"bugs": {
|
||||||
|
"url": "https://github.com/Expressive-Tea/green-tea/issues"
|
||||||
|
},
|
||||||
|
"homepage": "https://green-tea.expressive-tea.io/docs/",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"http",
|
"http",
|
||||||
"framework",
|
"framework",
|
||||||
@@ -112,12 +120,21 @@
|
|||||||
"optional": true
|
"optional": true
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"overrides": {
|
||||||
|
"find-my-way": "9.7.0",
|
||||||
|
"autocannon": {
|
||||||
|
"hyperid": {
|
||||||
|
"uuid": "11.1.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"undici": "7.29.0"
|
||||||
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.39.4",
|
"@eslint/js": "^9.39.5",
|
||||||
"@nestjs/common": "^11.1.27",
|
"@nestjs/common": "^11.1.28",
|
||||||
"@nestjs/core": "^11.1.27",
|
"@nestjs/core": "^11.1.28",
|
||||||
"@nestjs/platform-express": "^11.1.27",
|
"@nestjs/platform-express": "^11.1.28",
|
||||||
"@nestjs/platform-fastify": "^11.1.27",
|
"@nestjs/platform-fastify": "^11.1.28",
|
||||||
"@stylistic/eslint-plugin": "^5.10.0",
|
"@stylistic/eslint-plugin": "^5.10.0",
|
||||||
"@types/autocannon": "^7.12.7",
|
"@types/autocannon": "^7.12.7",
|
||||||
"@types/busboy": "^1.5.4",
|
"@types/busboy": "^1.5.4",
|
||||||
@@ -127,18 +144,20 @@
|
|||||||
"autocannon": "^8.0.0",
|
"autocannon": "^8.0.0",
|
||||||
"busboy": "^1.6.0",
|
"busboy": "^1.6.0",
|
||||||
"cognitive-complexity-ts": "^0.8.2",
|
"cognitive-complexity-ts": "^0.8.2",
|
||||||
"eslint": "^9.39.4",
|
"eslint": "^9.39.5",
|
||||||
|
"esbuild": "0.27.2",
|
||||||
"express": "^5.2.1",
|
"express": "^5.2.1",
|
||||||
"fastify": "^5.10.0",
|
"fastify": "^5.11.0",
|
||||||
"graphql": "^16.9.0",
|
"graphql": "^16.9.0",
|
||||||
"miniflare": "^4.20260708.1",
|
"miniflare": "^4.20260730.0",
|
||||||
"prettier": "^3.9.4",
|
"prettier": "^3.9.6",
|
||||||
"rxjs": "^7.8.2",
|
"rxjs": "^7.8.2",
|
||||||
"tsup": "^8.5.1",
|
"tsup": "^8.5.1",
|
||||||
"tsx": "^4.23.0",
|
"tsx": "^4.23.5",
|
||||||
"typescript": "^5.5.0",
|
"typescript": "^5.5.0",
|
||||||
"typescript-eslint": "^8.63.0",
|
"typescript-eslint": "^8.65.0",
|
||||||
"vitest": "^2.0.0",
|
"vite": "^6.4.3",
|
||||||
"ws": "^8.21.0"
|
"vitest": "^3.2.7",
|
||||||
|
"ws": "^8.21.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+36
-9
@@ -35,6 +35,7 @@ import type { MeshControl } from '../http';
|
|||||||
import type { RequestEnvelope, RouteEntry } from '../mesh/protocol';
|
import type { RequestEnvelope, RouteEntry } from '../mesh/protocol';
|
||||||
import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types';
|
import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types';
|
||||||
import { inspectRoute, buildGraphView, explainRoute } from './introspect';
|
import { inspectRoute, buildGraphView, explainRoute } from './introspect';
|
||||||
|
import { compilePattern } from '../http/router';
|
||||||
|
|
||||||
export type { App, InspectLine, ExplainNode, Explain, MeshConfig } from './types';
|
export type { App, InspectLine, ExplainNode, Explain, MeshConfig } from './types';
|
||||||
|
|
||||||
@@ -349,6 +350,7 @@ function collectControllers(
|
|||||||
const instance: any = new ControllerClass();
|
const instance: any = new ControllerClass();
|
||||||
const argSpecs = getArgs(ControllerClass, route.handlerName);
|
const argSpecs = getArgs(ControllerClass, route.handlerName);
|
||||||
const pattern = joinPath(mountpoint, route.path);
|
const pattern = joinPath(mountpoint, route.path);
|
||||||
|
const declaration = `${ControllerClass.name}.${route.handlerName}`;
|
||||||
|
|
||||||
if (route.export) {
|
if (route.export) {
|
||||||
if (route.transport !== 'buffer') throw new Error(`cannot export streaming route ${pattern}`);
|
if (route.transport !== 'buffer') throw new Error(`cannot export streaming route ${pattern}`);
|
||||||
@@ -357,11 +359,12 @@ function collectControllers(
|
|||||||
|
|
||||||
const transformer = resolveTransformer(ControllerClass, route, pattern, viewsCtx);
|
const transformer = resolveTransformer(ControllerClass, route, pattern, viewsCtx);
|
||||||
|
|
||||||
registry.routePlans.push({
|
const plan: RoutePlan = {
|
||||||
pattern,
|
pattern,
|
||||||
method: route.method,
|
method: route.method,
|
||||||
transport: route.transport,
|
transport: route.transport,
|
||||||
origin,
|
origin,
|
||||||
|
declaration,
|
||||||
providers: [],
|
providers: [],
|
||||||
steps: [],
|
steps: [],
|
||||||
handlerName: route.handlerName,
|
handlerName: route.handlerName,
|
||||||
@@ -372,11 +375,27 @@ function collectControllers(
|
|||||||
maxBodyBytes: route.maxBodyBytes,
|
maxBodyBytes: route.maxBodyBytes,
|
||||||
maxParts: route.maxParts,
|
maxParts: route.maxParts,
|
||||||
args: argSpecs,
|
args: argSpecs,
|
||||||
});
|
};
|
||||||
|
assertRouteAvailable(registry.routePlans, plan);
|
||||||
|
registry.routePlans.push(plan);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Rejects local routes that have the same method and effective match shape. */
|
||||||
|
function assertRouteAvailable(existing: RoutePlan[], candidate: RoutePlan): void {
|
||||||
|
const compiled = compilePattern(candidate.pattern);
|
||||||
|
const conflict = existing.find(
|
||||||
|
(plan) => plan.method === candidate.method && compilePattern(plan.pattern).shape === compiled.shape,
|
||||||
|
);
|
||||||
|
if (!conflict) return;
|
||||||
|
|
||||||
|
throw new Error(
|
||||||
|
`ambiguous route ${candidate.method} ${candidate.pattern} at ${candidate.declaration} conflicts with ` +
|
||||||
|
`${conflict.method} ${conflict.pattern} at ${conflict.declaration}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resolves the response transformer for a route: `@Html` metadata builds an HTML transformer (after
|
* Resolves the response transformer for a route: `@Html` metadata builds an HTML transformer (after
|
||||||
* validating placement — buffered GET/POST only, and not combined with `@Transformer`); otherwise the
|
* validating placement — buffered GET/POST only, and not combined with `@Transformer`); otherwise the
|
||||||
@@ -394,7 +413,7 @@ function resolveTransformer(
|
|||||||
|
|
||||||
if (route.transport !== 'buffer' || (route.method !== 'GET' && route.method !== 'POST')) {
|
if (route.transport !== 'buffer' || (route.method !== 'GET' && route.method !== 'POST')) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`@Html on ${route.method} ${pattern} is not allowed — @Html only supports buffered GET/POST routes (not SSE/WS/PUT/PATCH/DELETE)`,
|
`@Html on ${route.method} ${pattern} is not allowed — @Html only supports buffered GET/POST routes (not SSE/WS/HEAD/PUT/PATCH/DELETE/OPTIONS)`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -512,7 +531,7 @@ async function spliceRemoteScopes(
|
|||||||
): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[] }> {
|
): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[] }> {
|
||||||
const remoteRoutes: RouteDef[] = [];
|
const remoteRoutes: RouteDef[] = [];
|
||||||
const meshLinks: Link[] = [];
|
const meshLinks: Link[] = [];
|
||||||
const routeOwners = new Map<string, string>(); // "METHOD /pattern" -> the teapot that exported it
|
const routeOwners = new Map<string, { url: string; pattern: string }>(); // "METHOD effective-shape" -> owner
|
||||||
|
|
||||||
try {
|
try {
|
||||||
for (const teapot of mesh.teapots ?? []) {
|
for (const teapot of mesh.teapots ?? []) {
|
||||||
@@ -539,7 +558,8 @@ async function spliceRemoteScopes(
|
|||||||
}
|
}
|
||||||
|
|
||||||
for (const route of routes) {
|
for (const route of routes) {
|
||||||
const key = `${route.method} ${route.pattern}`;
|
const display = `${route.method} ${route.pattern}`;
|
||||||
|
const key = `${route.method} ${compilePattern(route.pattern).shape}`;
|
||||||
const owner = routeOwners.get(key);
|
const owner = routeOwners.get(key);
|
||||||
|
|
||||||
// Fail the boot rather than pick one. Route matching keeps the first of two identical
|
// Fail the boot rather than pick one. Route matching keeps the first of two identical
|
||||||
@@ -548,21 +568,28 @@ async function spliceRemoteScopes(
|
|||||||
// Scope tokens already fail this way in setRunner; routes now match.
|
// Scope tokens already fail this way in setRunner; routes now match.
|
||||||
if (owner) {
|
if (owner) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`mesh: route '${key}' is exported by more than one teapot (${owner} and ${teapot.url}) — ` +
|
`mesh: ambiguous remote route '${display}' from ${teapot.url} conflicts with ` +
|
||||||
|
`'${route.method} ${owner.pattern}' from ${owner.url} — ` +
|
||||||
'load balancing across teapots is not implemented yet, so green-tea will not choose one for you. ' +
|
'load balancing across teapots is not implemented yet, so green-tea will not choose one for you. ' +
|
||||||
'Export it from a single teapot.',
|
'Export it from a single teapot.',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
routeOwners.set(key, teapot.url);
|
routeOwners.set(key, { url: teapot.url, pattern: route.pattern });
|
||||||
|
|
||||||
// Local routes are merged ahead of remote ones (see buildHttpRoutes), so a local twin
|
// Local routes are merged ahead of remote ones (see buildHttpRoutes), so a local twin
|
||||||
// wins. That precedence is deliberate — your own code beats an imported one, and it is
|
// wins. That precedence is deliberate — your own code beats an imported one, and it is
|
||||||
// how you override a teapot — but silently shadowing an export looks exactly like a
|
// how you override a teapot — but silently shadowing an export looks exactly like a
|
||||||
// broken teapot from the outside. Warn and let the developer decide.
|
// broken teapot from the outside. Warn and let the developer decide.
|
||||||
if (registry.routePlans.some((plan) => plan.method === route.method && plan.pattern === route.pattern)) {
|
if (
|
||||||
|
registry.routePlans.some(
|
||||||
|
(plan) =>
|
||||||
|
plan.method === route.method &&
|
||||||
|
compilePattern(plan.pattern).shape === compilePattern(route.pattern).shape,
|
||||||
|
)
|
||||||
|
) {
|
||||||
console.warn(
|
console.warn(
|
||||||
`[green-tea] mesh: route '${key}' is exported by teapot ${teapot.url} but also declared locally — ` +
|
`[green-tea] mesh: route '${display}' is exported by teapot ${teapot.url} but also declared locally — ` +
|
||||||
'the local route takes precedence and the remote one will not be reached. ' +
|
'the local route takes precedence and the remote one will not be reached. ' +
|
||||||
'Remove one if that is not what you meant.',
|
'Remove one if that is not what you meant.',
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -70,6 +70,7 @@ export interface RoutePlan {
|
|||||||
method: HttpMethod;
|
method: HttpMethod;
|
||||||
transport: Transport;
|
transport: Transport;
|
||||||
origin: string;
|
origin: string;
|
||||||
|
declaration: string;
|
||||||
providers: GraphNode[];
|
providers: GraphNode[];
|
||||||
steps: GraphNode[];
|
steps: GraphNode[];
|
||||||
handlerName: string;
|
handlerName: string;
|
||||||
|
|||||||
+3
-1
@@ -35,10 +35,12 @@ declare const Deno: {
|
|||||||
export function serveDeno(app: App, options?: DenoServeOptions): DenoHttpServer {
|
export function serveDeno(app: App, options?: DenoServeOptions): DenoHttpServer {
|
||||||
return Deno.serve(options ?? {}, (request, info) => {
|
return Deno.serve(options ?? {}, (request, info) => {
|
||||||
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
||||||
|
// Deno invalidates request connection metadata as soon as the upgrade is accepted.
|
||||||
|
const wsRequest = toWsRequest(request, info.remoteAddr.hostname);
|
||||||
const { socket, response } = Deno.upgradeWebSocket(request);
|
const { socket, response } = Deno.upgradeWebSocket(request);
|
||||||
socket.binaryType = 'arraybuffer'; // deliver binary frames as ArrayBuffer, which decodeMessage expects
|
socket.binaryType = 'arraybuffer'; // deliver binary frames as ArrayBuffer, which decodeMessage expects
|
||||||
// fire-and-forget: the 101 response must be returned synchronously while the graph runs
|
// fire-and-forget: the 101 response must be returned synchronously while the graph runs
|
||||||
void upgradeSafely(app, toWsRequest(request, info.remoteAddr.hostname), eventSocket(socket));
|
void upgradeSafely(app, wsRequest, eventSocket(socket));
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+74
-24
@@ -3,7 +3,7 @@ import { HttpError, NotFound } from '../signals';
|
|||||||
import { renderError } from '../transformers';
|
import { renderError } from '../transformers';
|
||||||
import { isStreamResult, type PipelineResult } from '../pipeline';
|
import { isStreamResult, type PipelineResult } from '../pipeline';
|
||||||
import { buildSecurityHeaders, resolveCors, corsPreflightHeaders } from '../security';
|
import { buildSecurityHeaders, resolveCors, corsPreflightHeaders } from '../security';
|
||||||
import { matchRoute, allowedMethods, parseQuery } from './router';
|
import { resolveRoute, allowedMethods, normalizeRequestPath, parseQuery } from './router';
|
||||||
import { pickEncoder } from './stream';
|
import { pickEncoder } from './stream';
|
||||||
import type { RouteDef, HttpOptions } from './types';
|
import type { RouteDef, HttpOptions } from './types';
|
||||||
import type { StreamEncoder } from '../encoders';
|
import type { StreamEncoder } from '../encoders';
|
||||||
@@ -49,6 +49,61 @@ export function computeInjected(
|
|||||||
return injected;
|
return injected;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function errorOutcome(
|
||||||
|
error: unknown,
|
||||||
|
req: NeutralRequest,
|
||||||
|
injected: Record<string, string>,
|
||||||
|
opts: HttpOptions | undefined,
|
||||||
|
headers: Record<string, string> = {},
|
||||||
|
): HandleResult {
|
||||||
|
const rendered = renderError(error, { method: req.method, url: req.url, headers: req.headers }, opts?.onError);
|
||||||
|
return {
|
||||||
|
injected,
|
||||||
|
outcome: {
|
||||||
|
kind: 'buffered',
|
||||||
|
status: rendered.status,
|
||||||
|
headers: { ...rendered.headers, ...headers },
|
||||||
|
body: req.method === 'HEAD' ? '' : rendered.body,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function unmatchedOutcome(
|
||||||
|
routes: RouteDef[],
|
||||||
|
opts: HttpOptions | undefined,
|
||||||
|
req: NeutralRequest,
|
||||||
|
path: string,
|
||||||
|
injected: Record<string, string>,
|
||||||
|
): Promise<HandleResult> {
|
||||||
|
if ((req.method === 'GET' || req.method === 'HEAD') && opts?.static) {
|
||||||
|
const hit = await opts.static(path);
|
||||||
|
|
||||||
|
if (hit) {
|
||||||
|
return {
|
||||||
|
injected,
|
||||||
|
outcome: {
|
||||||
|
kind: 'buffered',
|
||||||
|
status: 200,
|
||||||
|
headers: { 'content-type': hit.contentType },
|
||||||
|
body: req.method === 'HEAD' ? '' : hit.body,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const allow = allowedMethods(routes, path);
|
||||||
|
|
||||||
|
if (req.method === 'OPTIONS' && allow.length) {
|
||||||
|
return {
|
||||||
|
injected,
|
||||||
|
outcome: { kind: 'buffered', status: 204, headers: { allow: allow.join(', ') }, body: '' },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const error = allow.length ? new HttpError(405, 'Method Not Allowed') : new NotFound('Not Found');
|
||||||
|
return errorOutcome(error, req, injected, opts, allow.length ? { allow: allow.join(', ') } : {});
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Runtime-neutral request handler: security/CORS headers, preflight short-circuit, route match / 404 / 405,
|
* Runtime-neutral request handler: security/CORS headers, preflight short-circuit, route match / 404 / 405,
|
||||||
* route-handler invocation with error rendering, and the buffered-vs-stream decision. Does no I/O — the
|
* route-handler invocation with error rendering, and the buffered-vs-stream decision. Does no I/O — the
|
||||||
@@ -59,35 +114,22 @@ export async function handle(
|
|||||||
opts: HttpOptions | undefined,
|
opts: HttpOptions | undefined,
|
||||||
req: NeutralRequest,
|
req: NeutralRequest,
|
||||||
): Promise<HandleResult | Preflight> {
|
): Promise<HandleResult | Preflight> {
|
||||||
const path = req.url.split('?')[0];
|
|
||||||
const injected = computeInjected(opts, req);
|
const injected = computeInjected(opts, req);
|
||||||
|
let path: string;
|
||||||
|
|
||||||
|
try {
|
||||||
|
path = normalizeRequestPath(req.url.split('?')[0]);
|
||||||
|
} catch {
|
||||||
|
return errorOutcome(new HttpError(400, 'Bad Request'), req, injected, opts);
|
||||||
|
}
|
||||||
|
|
||||||
if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) {
|
if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) {
|
||||||
return { preflight: corsPreflightHeaders(opts.cors, req) };
|
return { preflight: corsPreflightHeaders(opts.cors, req) };
|
||||||
}
|
}
|
||||||
|
|
||||||
const matched = matchRoute(routes, req.method, path);
|
const matched = resolveRoute(routes, req.method, path);
|
||||||
|
|
||||||
if (!matched) {
|
if (!matched) return unmatchedOutcome(routes, opts, req, path, injected);
|
||||||
if ((req.method === 'GET' || req.method === 'HEAD') && opts?.static) {
|
|
||||||
const hit = await opts.static(path);
|
|
||||||
|
|
||||||
if (hit) {
|
|
||||||
const body = req.method === 'HEAD' ? '' : hit.body;
|
|
||||||
return {
|
|
||||||
injected,
|
|
||||||
outcome: { kind: 'buffered', status: 200, headers: { 'content-type': hit.contentType }, body },
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Path matches a route under a different method → 405 with Allow; otherwise 404.
|
|
||||||
const allow = allowedMethods(routes, path);
|
|
||||||
const err = allow.length ? new HttpError(405, 'Method Not Allowed') : new NotFound('Not Found');
|
|
||||||
const rendered = renderError(err, { method: req.method, url: req.url, headers: req.headers }, opts?.onError);
|
|
||||||
const headers = allow.length ? { ...rendered.headers, allow: allow.join(', ') } : rendered.headers;
|
|
||||||
return { injected, outcome: { kind: 'buffered', status: rendered.status, headers, body: rendered.body } };
|
|
||||||
}
|
|
||||||
|
|
||||||
let result: PipelineResult;
|
let result: PipelineResult;
|
||||||
|
|
||||||
@@ -111,5 +153,13 @@ export async function handle(
|
|||||||
return { injected, outcome: { kind: 'stream', headers: encoder.headers, stream: result.stream, encoder } };
|
return { injected, outcome: { kind: 'stream', headers: encoder.headers, stream: result.stream, encoder } };
|
||||||
}
|
}
|
||||||
|
|
||||||
return { injected, outcome: { kind: 'buffered', status: result.status, headers: result.headers, body: result.body } };
|
return {
|
||||||
|
injected,
|
||||||
|
outcome: {
|
||||||
|
kind: 'buffered',
|
||||||
|
status: result.status,
|
||||||
|
headers: result.headers,
|
||||||
|
body: req.method === 'HEAD' ? '' : result.body,
|
||||||
|
},
|
||||||
|
};
|
||||||
}
|
}
|
||||||
+240
-34
@@ -1,63 +1,236 @@
|
|||||||
import type { RouteDef, MatchedRoute } from './types';
|
import type { RouteDef, MatchedRoute } from './types';
|
||||||
|
|
||||||
/**
|
export type CompiledSegment =
|
||||||
* Matches a route pattern against a request path. Supports static segments, `:param` (one segment),
|
| { kind: 'static'; value: string }
|
||||||
* and a trailing `:name*` catch-all that captures the rest of the path (slashes included) into `params.name`.
|
| { kind: 'param'; name: string; constraint?: RegExp; constraintSource?: string }
|
||||||
* @returns Extracted params (decoded) when the path matches, otherwise undefined.
|
| { kind: 'catchAll'; name: string };
|
||||||
*/
|
|
||||||
export function matchPattern(pattern: string, path: string): Record<string, string> | undefined {
|
/** Parsed route pattern reused by matching, specificity, ambiguity checks, and OpenAPI projection. */
|
||||||
|
export interface CompiledPattern {
|
||||||
|
source: string;
|
||||||
|
normalized: string;
|
||||||
|
shape: string;
|
||||||
|
segments: CompiledSegment[];
|
||||||
|
kinds: number[];
|
||||||
|
catchAll: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const compiledCache = new Map<string, CompiledPattern>();
|
||||||
|
const PARAM_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
||||||
|
const MAX_CONSTRAINT_LENGTH = 128;
|
||||||
|
|
||||||
|
/** Request-path syntax error. Adapters translate this to the standard 400 response envelope. */
|
||||||
|
export class InvalidRequestPathError extends Error {
|
||||||
|
constructor(message: string) {
|
||||||
|
super(message);
|
||||||
|
this.name = 'InvalidRequestPathError';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ConstraintToken {
|
||||||
|
length: number;
|
||||||
|
unbounded: boolean;
|
||||||
|
separator: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reads one atom plus its optional quantifier from the deliberately small safe-regex subset. */
|
||||||
|
function readConstraintToken(source: string): ConstraintToken | undefined {
|
||||||
|
const atom = /^(?:\\[dDsSwW]|\\[.\-_/]|[A-Za-z0-9_.-]|\[(?:\\.|[^\]\\])+\])/u.exec(source)?.[0];
|
||||||
|
if (!atom) return undefined;
|
||||||
|
|
||||||
|
const rest = source.slice(atom.length);
|
||||||
|
const quantifier = /^(?:[+*?]|\{\d+(?:,\d*)?\})/u.exec(rest)?.[0] ?? '';
|
||||||
|
if (quantifier.startsWith('{')) assertBoundedQuantifier(quantifier);
|
||||||
|
|
||||||
|
return {
|
||||||
|
length: atom.length + quantifier.length,
|
||||||
|
unbounded: quantifier === '+' || quantifier === '*' || quantifier.endsWith(',}'),
|
||||||
|
separator: quantifier === '' && /^(?:\\[.\-_/]|[._-])$/u.test(atom),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rejects nonsensical or excessively large counted quantifiers before RegExp compilation. */
|
||||||
|
function assertBoundedQuantifier(quantifier: string): void {
|
||||||
|
const [minText, maxText] = quantifier.slice(1, -1).split(',');
|
||||||
|
const min = Number(minText);
|
||||||
|
const max = maxText === undefined || maxText === '' ? min : Number(maxText);
|
||||||
|
if (min > max || max > 2048) throw new Error(`unsafe route constraint: invalid quantifier '${quantifier}'`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Accepts only a linear, group-free regex subset to keep attacker-controlled segments ReDoS-safe. */
|
||||||
|
function assertSafeConstraint(source: string): void {
|
||||||
|
if (!source || source.length > MAX_CONSTRAINT_LENGTH)
|
||||||
|
throw new Error('unsafe route constraint: expression must contain 1-128 characters');
|
||||||
|
|
||||||
|
let offset = 0;
|
||||||
|
let previousUnbounded = false;
|
||||||
|
|
||||||
|
while (offset < source.length) {
|
||||||
|
const token = readConstraintToken(source.slice(offset));
|
||||||
|
if (!token) throw new Error(`unsafe route constraint: unsupported expression '${source}'`);
|
||||||
|
if (previousUnbounded && token.unbounded)
|
||||||
|
throw new Error(`unsafe route constraint: adjacent unbounded quantifiers in '${source}'`);
|
||||||
|
previousUnbounded = token.separator ? false : token.unbounded;
|
||||||
|
offset += token.length;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertParamName(name: string, pattern: string): void {
|
||||||
|
if (!PARAM_NAME.test(name)) throw new Error(`invalid route pattern '${pattern}': invalid parameter name '${name}'`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function compileParam(segment: string, pattern: string): Extract<CompiledSegment, { kind: 'param' }> {
|
||||||
|
const constraintStart = segment.indexOf('(');
|
||||||
|
|
||||||
|
if (constraintStart < 0) {
|
||||||
|
const name = segment.slice(1);
|
||||||
|
assertParamName(name, pattern);
|
||||||
|
return { kind: 'param', name };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!segment.endsWith(')')) throw new Error(`invalid route pattern '${pattern}': malformed constraint`);
|
||||||
|
const name = segment.slice(1, constraintStart);
|
||||||
|
const constraintSource = segment.slice(constraintStart + 1, -1);
|
||||||
|
assertParamName(name, pattern);
|
||||||
|
assertSafeConstraint(constraintSource);
|
||||||
|
return {
|
||||||
|
kind: 'param',
|
||||||
|
name,
|
||||||
|
constraintSource,
|
||||||
|
constraint: new RegExp(`^(?:${constraintSource})$`, 'u'),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function compileSegments(pattern: string, rawSegments: string[]): CompiledSegment[] {
|
||||||
|
const names = new Set<string>();
|
||||||
|
const compiled: CompiledSegment[] = [];
|
||||||
|
|
||||||
|
for (let index = 0; index < rawSegments.length; index++) {
|
||||||
|
const raw = rawSegments[index];
|
||||||
|
let segment: CompiledSegment;
|
||||||
|
|
||||||
|
if (raw.startsWith(':') && raw.endsWith('*')) {
|
||||||
|
const name = raw.slice(1, -1);
|
||||||
|
assertParamName(name, pattern);
|
||||||
|
if (index !== rawSegments.length - 1)
|
||||||
|
throw new Error(`invalid route pattern '${pattern}': catch-all must be the final segment`);
|
||||||
|
segment = { kind: 'catchAll', name };
|
||||||
|
} else if (raw.startsWith(':')) {
|
||||||
|
segment = compileParam(raw, pattern);
|
||||||
|
} else {
|
||||||
|
segment = { kind: 'static', value: raw };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (segment.kind !== 'static') {
|
||||||
|
if (names.has(segment.name))
|
||||||
|
throw new Error(`invalid route pattern '${pattern}': duplicate parameter '${segment.name}'`);
|
||||||
|
names.add(segment.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
compiled.push(segment);
|
||||||
|
}
|
||||||
|
|
||||||
|
return compiled;
|
||||||
|
}
|
||||||
|
|
||||||
|
function segmentShape(segment: CompiledSegment): string {
|
||||||
|
if (segment.kind === 'static') return `s:${segment.value}`;
|
||||||
|
if (segment.kind === 'catchAll') return 'c';
|
||||||
|
return segment.constraintSource ? `r:${segment.constraintSource}` : 'p';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Compiles and validates one route pattern. Results are cached by source string. */
|
||||||
|
export function compilePattern(pattern: string): CompiledPattern {
|
||||||
|
const cached = compiledCache.get(pattern);
|
||||||
|
if (cached) return cached;
|
||||||
|
if (!pattern.startsWith('/')) throw new Error(`invalid route pattern '${pattern}': pattern must start with '/'`);
|
||||||
|
if (pattern.includes('//')) throw new Error(`invalid route pattern '${pattern}': repeated slash`);
|
||||||
|
|
||||||
|
const normalized = pattern.length > 1 && pattern.endsWith('/') ? pattern.slice(0, -1) : pattern;
|
||||||
|
const rawSegments = normalized === '/' ? [] : normalized.split('/').slice(1);
|
||||||
|
const segments = compileSegments(pattern, rawSegments);
|
||||||
|
const compiled: CompiledPattern = {
|
||||||
|
source: pattern,
|
||||||
|
normalized,
|
||||||
|
shape: segments.map(segmentShape).join('/'),
|
||||||
|
segments,
|
||||||
|
kinds: segments
|
||||||
|
.filter((segment) => segment.kind !== 'catchAll')
|
||||||
|
.map((segment) => (segment.kind === 'static' ? 3 : segment.constraint ? 2 : 1)),
|
||||||
|
catchAll: segments.at(-1)?.kind === 'catchAll',
|
||||||
|
};
|
||||||
|
compiledCache.set(pattern, compiled);
|
||||||
|
return compiled;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Applies the public trailing-slash policy and validates every segment's percent encoding. */
|
||||||
|
export function normalizeRequestPath(path: string): string {
|
||||||
|
if (!path.startsWith('/')) throw new InvalidRequestPathError('invalid request path: path must start with slash');
|
||||||
|
if (path.includes('//')) throw new InvalidRequestPathError('invalid request path: repeated slash');
|
||||||
|
const normalized = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;
|
||||||
|
|
||||||
|
try {
|
||||||
|
for (const segment of normalized.split('/').slice(1)) decodeURIComponent(segment);
|
||||||
|
} catch {
|
||||||
|
throw new InvalidRequestPathError('invalid request path: malformed path encoding');
|
||||||
|
}
|
||||||
|
|
||||||
|
return normalized;
|
||||||
|
}
|
||||||
|
|
||||||
|
function decodeSegment(value: string): string {
|
||||||
|
return decodeURIComponent(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function matchCompiled(compiled: CompiledPattern, path: string): Record<string, string> | undefined {
|
||||||
const pathSegs = path.split('/').filter(Boolean);
|
const pathSegs = path.split('/').filter(Boolean);
|
||||||
const patternSegs = pattern.split('/').filter(Boolean);
|
|
||||||
const params: Record<string, string> = {};
|
const params: Record<string, string> = {};
|
||||||
|
|
||||||
for (let i = 0; i < patternSegs.length; i++) {
|
for (let index = 0; index < compiled.segments.length; index++) {
|
||||||
const seg = patternSegs[i];
|
const segment = compiled.segments[index];
|
||||||
|
|
||||||
// Trailing catch-all: capture every remaining segment (possibly none) as one decoded value.
|
if (segment.kind === 'catchAll') {
|
||||||
if (seg.startsWith(':') && seg.endsWith('*')) {
|
params[segment.name] = pathSegs.slice(index).map(decodeSegment).join('/');
|
||||||
params[seg.slice(1, -1)] = pathSegs.slice(i).map(decodeURIComponent).join('/');
|
|
||||||
return params;
|
return params;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (i >= pathSegs.length) return undefined; // pattern longer than path
|
if (index >= pathSegs.length) return undefined;
|
||||||
|
|
||||||
if (seg.startsWith(':')) params[seg.slice(1)] = decodeURIComponent(pathSegs[i]);
|
if (segment.kind === 'static') {
|
||||||
else if (seg !== pathSegs[i]) return undefined;
|
if (segment.value !== pathSegs[index]) return undefined;
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// No catch-all consumed the tail, so the lengths must match exactly.
|
const value = decodeSegment(pathSegs[index]);
|
||||||
return patternSegs.length === pathSegs.length ? params : undefined;
|
if (segment.constraint && !segment.constraint.test(value)) return undefined;
|
||||||
|
params[segment.name] = value;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Splits a pattern into its fixed-prefix segment kinds (2 = static, 1 = param) and whether it ends in a catch-all. */
|
return compiled.segments.length === pathSegs.length ? params : undefined;
|
||||||
function segScores(pattern: string): { catchAll: boolean; kinds: number[] } {
|
|
||||||
const kinds: number[] = [];
|
|
||||||
|
|
||||||
for (const seg of pattern.split('/').filter(Boolean)) {
|
|
||||||
if (seg.startsWith(':') && seg.endsWith('*')) return { catchAll: true, kinds };
|
|
||||||
kinds.push(seg.startsWith(':') ? 1 : 2);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return { catchAll: false, kinds };
|
/** Matches a compiled segment pattern and returns its decoded parameters. */
|
||||||
|
export function matchPattern(pattern: string, path: string): Record<string, string> | undefined {
|
||||||
|
return matchCompiled(compilePattern(pattern), path);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Orders two matching patterns by specificity: exact beats catch-all, then static beats param, then longer wins. */
|
/** Orders matching patterns by exactness, then static/constrained/plain segment specificity. */
|
||||||
function moreSpecific(a: string, b: string): number {
|
function moreSpecific(a: string, b: string): number {
|
||||||
const scoreA = segScores(a);
|
const scoreA = compilePattern(a);
|
||||||
const scoreB = segScores(b);
|
const scoreB = compilePattern(b);
|
||||||
if (scoreA.catchAll !== scoreB.catchAll) return scoreA.catchAll ? -1 : 1;
|
if (scoreA.catchAll !== scoreB.catchAll) return scoreA.catchAll ? -1 : 1;
|
||||||
const length = Math.max(scoreA.kinds.length, scoreB.kinds.length);
|
const length = Math.max(scoreA.kinds.length, scoreB.kinds.length);
|
||||||
|
|
||||||
for (let i = 0; i < length; i++) {
|
for (let index = 0; index < length; index++) {
|
||||||
const kindA = scoreA.kinds[i] ?? -1;
|
const kindA = scoreA.kinds[index] ?? -1;
|
||||||
const kindB = scoreB.kinds[i] ?? -1;
|
const kindB = scoreB.kinds[index] ?? -1;
|
||||||
if (kindA !== kindB) return kindA - kindB;
|
if (kindA !== kindB) return kindA - kindB;
|
||||||
}
|
}
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Finds the most specific route matching both method and path (static > param > catch-all; ties keep registration order). */
|
/** Finds the most specific route matching both method and path; ties keep registration order. */
|
||||||
export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined {
|
export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined {
|
||||||
let best: MatchedRoute | undefined;
|
let best: MatchedRoute | undefined;
|
||||||
let bestPattern = '';
|
let bestPattern = '';
|
||||||
@@ -76,11 +249,44 @@ export function matchRoute(routes: RouteDef[], method: string, path: string): Ma
|
|||||||
return best;
|
return best;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Route resolution adds the one HTTP fallback the matcher supports: buffered GET serves HEAD. */
|
||||||
|
export interface ResolvedRoute extends MatchedRoute {
|
||||||
|
implicitHead: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveRoute(routes: RouteDef[], method: string, path: string): ResolvedRoute | undefined {
|
||||||
|
const explicit = matchRoute(routes, method, path);
|
||||||
|
if (explicit) return { ...explicit, implicitHead: false };
|
||||||
|
if (method !== 'HEAD') return undefined;
|
||||||
|
|
||||||
|
const fallback = matchRoute(
|
||||||
|
routes.filter((route) => route.transport === 'buffer'),
|
||||||
|
'GET',
|
||||||
|
path,
|
||||||
|
);
|
||||||
|
return fallback ? { ...fallback, implicitHead: true } : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const METHOD_ORDER = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
|
||||||
|
|
||||||
/** Lists the distinct HTTP methods whose pattern matches the path — used to build a 405 `Allow` header. */
|
/** Lists the distinct HTTP methods whose pattern matches the path — used to build a 405 `Allow` header. */
|
||||||
export function allowedMethods(routes: RouteDef[], path: string): string[] {
|
export function allowedMethods(routes: RouteDef[], path: string): string[] {
|
||||||
const methods = new Set<string>();
|
const methods = new Set<string>();
|
||||||
for (const route of routes) if (matchPattern(route.pattern, path)) methods.add(route.method);
|
|
||||||
return [...methods];
|
for (const route of routes) {
|
||||||
|
if (!matchPattern(route.pattern, path)) continue;
|
||||||
|
methods.add(route.method);
|
||||||
|
if (route.method === 'GET' && route.transport === 'buffer') methods.add('HEAD');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (methods.size) methods.add('OPTIONS');
|
||||||
|
return [...methods].sort((a, b) => {
|
||||||
|
const indexA = METHOD_ORDER.indexOf(a);
|
||||||
|
const indexB = METHOD_ORDER.indexOf(b);
|
||||||
|
return (
|
||||||
|
(indexA < 0 ? METHOD_ORDER.length : indexA) - (indexB < 0 ? METHOD_ORDER.length : indexB) || a.localeCompare(b)
|
||||||
|
);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Parses a URL's query string into a flat string map (last value wins for repeated keys). */
|
/** Parses a URL's query string into a flat string map (last value wins for repeated keys). */
|
||||||
|
|||||||
+8
-2
@@ -5,7 +5,7 @@ import { isHttpError, HttpError } from '../signals';
|
|||||||
import type { Bus } from '../bus';
|
import type { Bus } from '../bus';
|
||||||
import { buildSecurityHeaders, resolveCors } from '../security';
|
import { buildSecurityHeaders, resolveCors } from '../security';
|
||||||
import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart';
|
import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart';
|
||||||
import { matchRoute } from './router';
|
import { normalizeRequestPath, resolveRoute } from './router';
|
||||||
import { readBody, deriveSecure, deriveIp } from './request';
|
import { readBody, deriveSecure, deriveIp } from './request';
|
||||||
import { pipeStream } from './stream';
|
import { pipeStream } from './stream';
|
||||||
import { attachWs } from './ws';
|
import { attachWs } from './ws';
|
||||||
@@ -93,7 +93,13 @@ function createRequestHandler(cfg: HandlerConfig) {
|
|||||||
// Mirror handle()'s own preflight/route-match decision here, so we only read the body
|
// Mirror handle()'s own preflight/route-match decision here, so we only read the body
|
||||||
// (below) for a request that actually reaches a route handler — matching prior behaviour.
|
// (below) for a request that actually reaches a route handler — matching prior behaviour.
|
||||||
const isPreflight = Boolean(opts?.cors && method === 'OPTIONS' && req.headers['access-control-request-method']);
|
const isPreflight = Boolean(opts?.cors && method === 'OPTIONS' && req.headers['access-control-request-method']);
|
||||||
const matched = isPreflight ? undefined : matchRoute(routes, method, path);
|
let matched: ReturnType<typeof resolveRoute>;
|
||||||
|
|
||||||
|
try {
|
||||||
|
matched = isPreflight ? undefined : resolveRoute(routes, method, normalizeRequestPath(path));
|
||||||
|
} catch {
|
||||||
|
matched = undefined; // handle() owns the standard 400 envelope and injected headers
|
||||||
|
}
|
||||||
|
|
||||||
let body: unknown;
|
let body: unknown;
|
||||||
|
|
||||||
|
|||||||
+11
-3
@@ -2,7 +2,7 @@ import type { StreamEncoder } from '../encoders';
|
|||||||
import { handle, computeInjected, type HandleResult } from './core';
|
import { handle, computeInjected, type HandleResult } from './core';
|
||||||
import { mergeInjectedHeaders } from './headers';
|
import { mergeInjectedHeaders } from './headers';
|
||||||
import { parseRequestBody } from './server';
|
import { parseRequestBody } from './server';
|
||||||
import { matchRoute } from './router';
|
import { normalizeRequestPath, resolveRoute } from './router';
|
||||||
import { HttpError } from '../signals';
|
import { HttpError } from '../signals';
|
||||||
import { renderError, type ErrorRequest, type ErrorResponse } from '../transformers';
|
import { renderError, type ErrorRequest, type ErrorResponse } from '../transformers';
|
||||||
import type { RouteDef, HttpOptions, MatchedRoute } from './types';
|
import type { RouteDef, HttpOptions, MatchedRoute } from './types';
|
||||||
@@ -108,7 +108,8 @@ function outcomeToResponse(result: HandleResult): Response {
|
|||||||
return new Response(asReadableStream(result.outcome.stream, result.outcome.encoder), { headers });
|
return new Response(asReadableStream(result.outcome.stream, result.outcome.encoder), { headers });
|
||||||
}
|
}
|
||||||
|
|
||||||
return new Response(result.outcome.body, { status: result.outcome.status, headers });
|
const body = [204, 205, 304].includes(result.outcome.status) ? null : result.outcome.body;
|
||||||
|
return new Response(body, { status: result.outcome.status, headers });
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -123,7 +124,14 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
|
|||||||
const url = new URL(request.url);
|
const url = new URL(request.url);
|
||||||
const path = url.pathname + url.search;
|
const path = url.pathname + url.search;
|
||||||
const headers = headersToRecord(request.headers);
|
const headers = headersToRecord(request.headers);
|
||||||
const matched = matchRoute(routes, request.method, url.pathname);
|
let matched: ReturnType<typeof resolveRoute>;
|
||||||
|
|
||||||
|
try {
|
||||||
|
matched = resolveRoute(routes, request.method, normalizeRequestPath(url.pathname));
|
||||||
|
} catch {
|
||||||
|
matched = undefined; // handle() renders the shared 400 response without reading a body
|
||||||
|
}
|
||||||
|
|
||||||
const secure = url.protocol === 'https:';
|
const secure = url.protocol === 'https:';
|
||||||
// Computed up-front from the same inputs `handle()` uses, so early-failure responses (413/400/501,
|
// Computed up-front from the same inputs `handle()` uses, so early-failure responses (413/400/501,
|
||||||
// before a route handler even runs) carry the same security/CORS headers Node's writeHead patch
|
// before a route handler even runs) carry the same security/CORS headers Node's writeHead patch
|
||||||
|
|||||||
+3
-1
@@ -6,7 +6,7 @@
|
|||||||
import 'reflect-metadata';
|
import 'reflect-metadata';
|
||||||
|
|
||||||
/** Package version, replaced at publish time. */
|
/** Package version, replaced at publish time. */
|
||||||
export const VERSION = '26.7.0-beta.0';
|
export const VERSION = '26.8.0-beta.0';
|
||||||
|
|
||||||
// Application
|
// Application
|
||||||
export { createApp } from './app';
|
export { createApp } from './app';
|
||||||
@@ -27,6 +27,7 @@ export {
|
|||||||
Step,
|
Step,
|
||||||
Route,
|
Route,
|
||||||
Get,
|
Get,
|
||||||
|
Head,
|
||||||
Module,
|
Module,
|
||||||
Transformer,
|
Transformer,
|
||||||
Sse,
|
Sse,
|
||||||
@@ -36,6 +37,7 @@ export {
|
|||||||
Put,
|
Put,
|
||||||
Patch,
|
Patch,
|
||||||
Delete,
|
Delete,
|
||||||
|
Options,
|
||||||
Html,
|
Html,
|
||||||
} from './metadata';
|
} from './metadata';
|
||||||
export type { Transport, HttpMethod } from './metadata';
|
export type { Transport, HttpMethod } from './metadata';
|
||||||
|
|||||||
+5
-1
@@ -25,7 +25,7 @@ export interface StepMeta {
|
|||||||
export: boolean;
|
export: boolean;
|
||||||
}
|
}
|
||||||
/** HTTP verbs supported by the route decorators. */
|
/** HTTP verbs supported by the route decorators. */
|
||||||
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
export type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS';
|
||||||
/** Wire transport a route responds with. */
|
/** Wire transport a route responds with. */
|
||||||
export type Transport = 'buffer' | 'sse' | 'ndjson' | 'negotiate' | 'ws';
|
export type Transport = 'buffer' | 'sse' | 'ndjson' | 'negotiate' | 'ws';
|
||||||
/** Metadata attached by a route decorator to a single handler method. */
|
/** Metadata attached by a route decorator to a single handler method. */
|
||||||
@@ -124,6 +124,8 @@ function routeDecorator(method: HttpMethod, transport: Transport) {
|
|||||||
|
|
||||||
/** Declares a buffered `GET` route. */
|
/** Declares a buffered `GET` route. */
|
||||||
export const Get = routeDecorator('GET', 'buffer');
|
export const Get = routeDecorator('GET', 'buffer');
|
||||||
|
/** Declares a buffered `HEAD` route. */
|
||||||
|
export const Head = routeDecorator('HEAD', 'buffer');
|
||||||
/** Declares a buffered `POST` route. */
|
/** Declares a buffered `POST` route. */
|
||||||
export const Post = routeDecorator('POST', 'buffer');
|
export const Post = routeDecorator('POST', 'buffer');
|
||||||
/** Declares a buffered `PUT` route. */
|
/** Declares a buffered `PUT` route. */
|
||||||
@@ -132,6 +134,8 @@ export const Put = routeDecorator('PUT', 'buffer');
|
|||||||
export const Patch = routeDecorator('PATCH', 'buffer');
|
export const Patch = routeDecorator('PATCH', 'buffer');
|
||||||
/** Declares a buffered `DELETE` route. */
|
/** Declares a buffered `DELETE` route. */
|
||||||
export const Delete = routeDecorator('DELETE', 'buffer');
|
export const Delete = routeDecorator('DELETE', 'buffer');
|
||||||
|
/** Declares a buffered `OPTIONS` route. */
|
||||||
|
export const Options = routeDecorator('OPTIONS', 'buffer');
|
||||||
/** Declares a `GET` route streamed as Server-Sent Events. */
|
/** Declares a `GET` route streamed as Server-Sent Events. */
|
||||||
export const Sse = routeDecorator('GET', 'sse');
|
export const Sse = routeDecorator('GET', 'sse');
|
||||||
/** Declares a `GET` route whose transport is content-negotiated at request time. */
|
/** Declares a `GET` route whose transport is content-negotiated at request time. */
|
||||||
|
|||||||
+24
-9
@@ -1,5 +1,6 @@
|
|||||||
import type { ArgSpec } from './params';
|
import type { ArgSpec } from './params';
|
||||||
import type { Transport } from './metadata';
|
import type { Transport } from './metadata';
|
||||||
|
import { compilePattern } from './http/router';
|
||||||
|
|
||||||
/** Minimal per-route input the OpenAPI projection needs, derived from a route plan. */
|
/** Minimal per-route input the OpenAPI projection needs, derived from a route plan. */
|
||||||
export interface OpenApiRoute {
|
export interface OpenApiRoute {
|
||||||
@@ -23,23 +24,37 @@ export interface OpenApiDoc {
|
|||||||
paths: Record<string, Record<string, unknown>>;
|
paths: Record<string, Record<string, unknown>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
type Parameter = { name: string; in: 'path' | 'query' | 'header'; required: boolean; schema: { type: 'string' } };
|
type Parameter = {
|
||||||
|
name: string;
|
||||||
|
in: 'path' | 'query' | 'header';
|
||||||
|
required: boolean;
|
||||||
|
schema: { type: 'string'; pattern?: string };
|
||||||
|
};
|
||||||
|
|
||||||
/** Converts a route pattern to an OpenAPI path template: `/users/:id` → `/users/{id}`, `:rest*` → `{rest}`. */
|
/** Converts a route pattern to an OpenAPI path template: `/users/:id` → `/users/{id}`, `:rest*` → `{rest}`. */
|
||||||
function templatePath(pattern: string): string {
|
function templatePath(pattern: string): string {
|
||||||
const segments = pattern
|
const segments = compilePattern(pattern).segments.map((segment) =>
|
||||||
.split('/')
|
segment.kind === 'static' ? segment.value : `{${segment.name}}`,
|
||||||
.filter(Boolean)
|
);
|
||||||
.map((seg) => (seg.startsWith(':') ? `{${seg.slice(1).replace(/\*$/, '')}}` : seg));
|
|
||||||
return `/${segments.join('/')}`;
|
return `/${segments.join('/')}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Every `:name` (and `:name*`) segment of a pattern becomes a required path parameter. */
|
/** Every `:name` (and `:name*`) segment of a pattern becomes a required path parameter. */
|
||||||
function pathParams(pattern: string): Parameter[] {
|
function pathParams(pattern: string): Parameter[] {
|
||||||
return pattern
|
return compilePattern(pattern).segments.flatMap((segment): Parameter[] => {
|
||||||
.split('/')
|
if (segment.kind === 'static') return [];
|
||||||
.filter((seg) => seg.startsWith(':'))
|
return [
|
||||||
.map((seg) => ({ name: seg.slice(1).replace(/\*$/, ''), in: 'path', required: true, schema: { type: 'string' } }));
|
{
|
||||||
|
name: segment.name,
|
||||||
|
in: 'path',
|
||||||
|
required: true,
|
||||||
|
schema: {
|
||||||
|
type: 'string',
|
||||||
|
...(segment.kind === 'param' && segment.constraintSource ? { pattern: segment.constraintSource } : {}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Query and header parameters declared by the handler's `@query` / `@headers` / `@header` argument decorators. */
|
/** Query and header parameters declared by the handler's `@query` / `@headers` / `@header` argument decorators. */
|
||||||
|
|||||||
+1
-1
@@ -62,7 +62,7 @@ export class TransportMismatchError extends HttpError {
|
|||||||
const expected = got === 'stream' ? 'return a value' : 'return an AsyncIterable';
|
const expected = got === 'stream' ? 'return a value' : 'return an AsyncIterable';
|
||||||
const fix =
|
const fix =
|
||||||
got === 'stream'
|
got === 'stream'
|
||||||
? 'buffered routes (@Get/@Post/@Put/@Patch/@Delete) must return a value — to stream, declare @Sse, @Stream, or @Ws'
|
? 'buffered routes (@Get/@Head/@Post/@Put/@Patch/@Delete/@Options) must return a value — to stream, declare @Sse, @Stream, or @Ws'
|
||||||
: 'streaming routes (@Sse/@Ws) must return an AsyncIterable (e.g. an async generator or channel())';
|
: 'streaming routes (@Sse/@Ws) must return an AsyncIterable (e.g. an async generator or channel())';
|
||||||
super(500, `Transport '${transport}'${where} must ${expected}, but the handler returned a ${got}. ${fix}.`);
|
super(500, `Transport '${transport}'${where} must ${expected}, but the handler returned a ${got}. ${fix}.`);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -583,3 +583,39 @@ test('per-route maxBodyBytes overrides the server default', async () => {
|
|||||||
|
|
||||||
server.close();
|
server.close();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('route table validation', () => {
|
||||||
|
it('rejects routes with the same method and effective pattern', () => {
|
||||||
|
@Route('/users')
|
||||||
|
class DuplicateCtl {
|
||||||
|
@Get('/:id') byId() {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
@Get('/:name') byName() {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/api', controllers: [DuplicateCtl] })
|
||||||
|
class DuplicateModule {}
|
||||||
|
|
||||||
|
expect(() => createApp({ modules: [DuplicateModule] })).toThrow(
|
||||||
|
/ambiguous route GET.*\/api\/users\/:name.*DuplicateCtl\.byName.*DuplicateCtl\.byId/,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('allows the same effective pattern under different methods', () => {
|
||||||
|
@Route('/users')
|
||||||
|
class MethodsCtl {
|
||||||
|
@Get('/:id') get() {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
@Post('/:name') post() {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/api', controllers: [MethodsCtl] })
|
||||||
|
class MethodsModule {}
|
||||||
|
|
||||||
|
expect(() => createApp({ modules: [MethodsModule] })).not.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { afterEach, expect, it, vi } from 'vitest';
|
||||||
|
import type { App } from '../src/app/types';
|
||||||
|
import { serveDeno } from '../src/deno';
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.unstubAllGlobals();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('snapshots connection metadata before Deno invalidates the upgraded request', async () => {
|
||||||
|
let upgraded = false;
|
||||||
|
let handler: ((request: Request, info: unknown) => Response | Promise<Response>) | undefined;
|
||||||
|
const socket = {
|
||||||
|
readyState: 1,
|
||||||
|
binaryType: '',
|
||||||
|
send: vi.fn(),
|
||||||
|
close: vi.fn(),
|
||||||
|
addEventListener: vi.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
vi.stubGlobal('Deno', {
|
||||||
|
serve: (_options: unknown, next: typeof handler) => {
|
||||||
|
handler = next;
|
||||||
|
return { finished: Promise.resolve(), shutdown: vi.fn() };
|
||||||
|
},
|
||||||
|
upgradeWebSocket: () => {
|
||||||
|
upgraded = true;
|
||||||
|
return { socket, response: new Response() };
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const upgrade = vi.fn().mockResolvedValue(undefined);
|
||||||
|
serveDeno({ upgrade } as unknown as App);
|
||||||
|
const info = {
|
||||||
|
get remoteAddr() {
|
||||||
|
if (upgraded) throw new TypeError('Request closed');
|
||||||
|
return { hostname: '127.0.0.1', port: 1234, transport: 'tcp' };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const request = new Request('http://localhost/socket?token=x', {
|
||||||
|
headers: { upgrade: 'websocket', 'x-test': 'yes' },
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(() => handler!(request, info)).not.toThrow();
|
||||||
|
await vi.waitFor(() =>
|
||||||
|
expect(upgrade).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ url: '/socket?token=x', ip: '127.0.0.1' }),
|
||||||
|
expect.any(Object),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -35,6 +35,26 @@ class DupCtl {
|
|||||||
@Module({ mountpoint: '/api', controllers: [DupCtl] })
|
@Module({ mountpoint: '/api', controllers: [DupCtl] })
|
||||||
class DupTeapotModule {}
|
class DupTeapotModule {}
|
||||||
|
|
||||||
|
@Route('/shape')
|
||||||
|
class ParamIdCtl {
|
||||||
|
@Get('/:id', { export: true })
|
||||||
|
get() {
|
||||||
|
return { from: 'id' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/api', controllers: [ParamIdCtl] })
|
||||||
|
class ParamIdTeapotModule {}
|
||||||
|
|
||||||
|
@Route('/shape')
|
||||||
|
class ParamNameCtl {
|
||||||
|
@Get('/:name', { export: true })
|
||||||
|
get() {
|
||||||
|
return { from: 'name' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/api', controllers: [ParamNameCtl] })
|
||||||
|
class ParamNameTeapotModule {}
|
||||||
|
|
||||||
@Route('/c')
|
@Route('/c')
|
||||||
class PlainCtl {
|
class PlainCtl {
|
||||||
@Get('/ok')
|
@Get('/ok')
|
||||||
@@ -112,6 +132,27 @@ describe('mesh skeleton integration', () => {
|
|||||||
bServer.close();
|
bServer.close();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('refuses ambiguous remote routes that differ only by parameter name', async () => {
|
||||||
|
const a = createApp({ modules: [ParamIdTeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||||
|
const b = createApp({ modules: [ParamNameTeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||||
|
const aServer = await a.listen(0);
|
||||||
|
const bServer = await b.listen(0);
|
||||||
|
const url = (s: any) => `ws://127.0.0.1:${(s.address() as any).port}/__mesh__/control`;
|
||||||
|
const teacup = createApp({
|
||||||
|
modules: [PlainTeacupModule],
|
||||||
|
experimental: true,
|
||||||
|
mesh: { teapots: [{ url: url(aServer), secret: SECRET }, { url: url(bServer), secret: SECRET }] },
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await expect(teacup.ready()).rejects.toThrow(/ambiguous remote route.*GET \/api\/shape\/:name/i);
|
||||||
|
} finally {
|
||||||
|
await teacup.close();
|
||||||
|
aServer.close();
|
||||||
|
bServer.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
it('accepts the same route from a single teapot (regression: no false positive)', async () => {
|
it('accepts the same route from a single teapot (regression: no false positive)', async () => {
|
||||||
const a = createApp({ modules: [DupTeapotModule], experimental: true, mesh: { secret: SECRET } });
|
const a = createApp({ modules: [DupTeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||||
const aServer = await a.listen(0);
|
const aServer = await a.listen(0);
|
||||||
|
|||||||
+13
-1
@@ -3,7 +3,7 @@ import { expect, test, describe, it } from 'vitest';
|
|||||||
import {
|
import {
|
||||||
Provider, Step, Route, Get, Module,
|
Provider, Step, Route, Get, Module,
|
||||||
getProviderMeta, getStepMeta, getRoutes, getModuleMeta,
|
getProviderMeta, getStepMeta, getRoutes, getModuleMeta,
|
||||||
Sse, Ws, Stream, Post,
|
Sse, Ws, Stream, Post, Head, Options,
|
||||||
} from '../src/metadata';
|
} from '../src/metadata';
|
||||||
|
|
||||||
@Provider({ provides: 'db', needs: ['config'] })
|
@Provider({ provides: 'db', needs: ['config'] })
|
||||||
@@ -54,6 +54,18 @@ describe('stream route decorators', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('HEAD and OPTIONS decorators', () => {
|
||||||
|
it('records both as buffered methods', () => {
|
||||||
|
class Methods {
|
||||||
|
@Head('/resource') head() {}
|
||||||
|
@Options('/resource') options() {}
|
||||||
|
}
|
||||||
|
const byName = Object.fromEntries(getRoutes(Methods).map((route) => [route.handlerName, route]));
|
||||||
|
expect(byName.head).toMatchObject({ method: 'HEAD', transport: 'buffer', path: '/resource' });
|
||||||
|
expect(byName.options).toMatchObject({ method: 'OPTIONS', transport: 'buffer', path: '/resource' });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('mesh export flags', () => {
|
describe('mesh export flags', () => {
|
||||||
it('providers/steps carry export (default false)', () => {
|
it('providers/steps carry export (default false)', () => {
|
||||||
@Provider({ provides: 'config', export: true }) class C { provide() { return {}; } }
|
@Provider({ provides: 'config', export: true }) class C { provide() { return {}; } }
|
||||||
|
|||||||
+25
-2
@@ -1,7 +1,7 @@
|
|||||||
import 'reflect-metadata';
|
import 'reflect-metadata';
|
||||||
import { describe, it, expect } from 'vitest';
|
import { describe, it, expect } from 'vitest';
|
||||||
import { createApp } from '../src/app';
|
import { createApp } from '../src/app';
|
||||||
import { Route, Get, Post, Ws, Module } from '../src/metadata';
|
import { Route, Get, Head, Options, Post, Ws, Module } from '../src/metadata';
|
||||||
import { param, query, headers, body } from '../src/params';
|
import { param, query, headers, body } from '../src/params';
|
||||||
|
|
||||||
const numSchema = {
|
const numSchema = {
|
||||||
@@ -14,7 +14,13 @@ const numSchema = {
|
|||||||
|
|
||||||
@Route('/users')
|
@Route('/users')
|
||||||
class Users {
|
class Users {
|
||||||
@Get('/:id') get(@param('id') _id: string, @query('expand') _e: string, @headers('x-trace') _t: string) {
|
@Get('/:id(\\d+)') get(@param('id') _id: string, @query('expand') _e: string, @headers('x-trace') _t: string) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
@Head('/:id(\\d+)') head() {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
@Options('/:id(\\d+)') options() {
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
@Post('/') create(@body() _b: unknown) {
|
@Post('/') create(@body() _b: unknown) {
|
||||||
@@ -52,6 +58,23 @@ describe('app.openapi()', () => {
|
|||||||
expect(byName).toEqual({ id: 'path', expand: 'query', 'x-trace': 'header' });
|
expect(byName).toEqual({ id: 'path', expand: 'query', 'x-trace': 'header' });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('projects a constrained param into schema.pattern', () => {
|
||||||
|
const op = doc.paths['/api/users/{id}'].get as any;
|
||||||
|
expect(op.parameters).toContainEqual({
|
||||||
|
name: 'id',
|
||||||
|
in: 'path',
|
||||||
|
required: true,
|
||||||
|
schema: { type: 'string', pattern: '\\d+' },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('includes explicit HEAD and OPTIONS without inventing automatic operations', () => {
|
||||||
|
expect(doc.paths['/api/users/{id}'].head).toBeDefined();
|
||||||
|
expect(doc.paths['/api/users/{id}'].options).toBeDefined();
|
||||||
|
expect(doc.paths['/api/users/search'].head).toBeUndefined();
|
||||||
|
expect(doc.paths['/api/users/search'].options).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
it('marks routes that take a body with requestBody', () => {
|
it('marks routes that take a body with requestBody', () => {
|
||||||
const op = doc.paths['/api/users'].post as any;
|
const op = doc.paths['/api/users'].post as any;
|
||||||
expect(op.requestBody.content['application/json']).toBeDefined();
|
expect(op.requestBody.content['application/json']).toBeDefined();
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { readFileSync } from 'node:fs';
|
||||||
|
import { resolve } from 'node:path';
|
||||||
|
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
|
interface PackageMetadata {
|
||||||
|
readonly repository?: {
|
||||||
|
readonly type?: string;
|
||||||
|
readonly url?: string;
|
||||||
|
};
|
||||||
|
readonly bugs?: {
|
||||||
|
readonly url?: string;
|
||||||
|
};
|
||||||
|
readonly homepage?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const packageJson = JSON.parse(readFileSync(resolve(process.cwd(), 'package.json'), 'utf8')) as PackageMetadata;
|
||||||
|
|
||||||
|
describe('package publication metadata', () => {
|
||||||
|
it('links npm provenance to the public GitHub repository', () => {
|
||||||
|
expect(packageJson.repository).toEqual({
|
||||||
|
type: 'git',
|
||||||
|
url: 'git+https://github.com/Expressive-Tea/green-tea.git',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('links npm consumers to support and documentation', () => {
|
||||||
|
expect(packageJson.bugs).toEqual({
|
||||||
|
url: 'https://github.com/Expressive-Tea/green-tea/issues',
|
||||||
|
});
|
||||||
|
expect(packageJson.homepage).toBe('https://green-tea.expressive-tea.io/docs/');
|
||||||
|
});
|
||||||
|
});
|
||||||
+48
-1
@@ -1,6 +1,6 @@
|
|||||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||||
import type { Server } from 'http';
|
import type { Server } from 'http';
|
||||||
import { createApp, Provider, Route, Get, Post, Module, needs, body, Sse } from '../src/index';
|
import { createApp, Provider, Route, Get, Head, Options, Post, Module, needs, body, Sse } from '../src/index';
|
||||||
|
|
||||||
@Provider({ provides: 'db' })
|
@Provider({ provides: 'db' })
|
||||||
class Db {
|
class Db {
|
||||||
@@ -22,6 +22,21 @@ class Ctl {
|
|||||||
yield { n: 2 };
|
yield { n: 2 };
|
||||||
})();
|
})();
|
||||||
}
|
}
|
||||||
|
@Get('/implicit-head') implicitHead() {
|
||||||
|
return { from: 'get' };
|
||||||
|
}
|
||||||
|
@Get('/explicit-head') explicitHeadGet() {
|
||||||
|
return { from: 'get' };
|
||||||
|
}
|
||||||
|
@Head('/explicit-head') explicitHead() {
|
||||||
|
return { from: 'head' };
|
||||||
|
}
|
||||||
|
@Get('/explicit-options') explicitOptionsGet() {
|
||||||
|
return { from: 'get' };
|
||||||
|
}
|
||||||
|
@Options('/explicit-options') explicitOptions() {
|
||||||
|
return { from: 'options' };
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@Module({ mountpoint: '/', providers: [Db], controllers: [Ctl] })
|
@Module({ mountpoint: '/', providers: [Db], controllers: [Ctl] })
|
||||||
class M {}
|
class M {}
|
||||||
@@ -78,6 +93,38 @@ describe('Node vs app.fetch parity (Node is truth)', () => {
|
|||||||
expect(web.status).toBe(node.status);
|
expect(web.status).toBe(node.status);
|
||||||
expect(norm(web.headers)).toEqual(norm(node.headers));
|
expect(norm(web.headers)).toEqual(norm(node.headers));
|
||||||
});
|
});
|
||||||
|
it('implicit and explicit HEAD return no body in both adapters', async () => {
|
||||||
|
for (const path of ['/api/implicit-head', '/api/explicit-head']) {
|
||||||
|
const { node, web } = await both(path, { method: 'HEAD' });
|
||||||
|
expect(node.status).toBe(200);
|
||||||
|
expect(web.status).toBe(node.status);
|
||||||
|
expect(await node.text()).toBe('');
|
||||||
|
expect(await web.text()).toBe('');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
it('automatic OPTIONS is 204 with the same canonical Allow header', async () => {
|
||||||
|
const { node, web } = await both('/api/x', { method: 'OPTIONS' });
|
||||||
|
expect(node.status).toBe(204);
|
||||||
|
expect(web.status).toBe(204);
|
||||||
|
expect(node.headers.get('allow')).toBe('GET, HEAD, OPTIONS');
|
||||||
|
expect(web.headers.get('allow')).toBe(node.headers.get('allow'));
|
||||||
|
});
|
||||||
|
it('explicit OPTIONS route runs normally', async () => {
|
||||||
|
const { node, web } = await both('/api/explicit-options', { method: 'OPTIONS' });
|
||||||
|
expect(node.status).toBe(200);
|
||||||
|
expect(web.status).toBe(200);
|
||||||
|
expect(await node.json()).toEqual({ from: 'options' });
|
||||||
|
expect(await web.json()).toEqual({ from: 'options' });
|
||||||
|
});
|
||||||
|
it('rejects repeated slashes and malformed encoding with secure 400 responses', async () => {
|
||||||
|
for (const path of ['/api//x', '/api/%E0%A4%A']) {
|
||||||
|
const { node, web } = await both(path);
|
||||||
|
expect(node.status).toBe(400);
|
||||||
|
expect(web.status).toBe(400);
|
||||||
|
expect(node.headers.get('x-content-type-options')).toBe('nosniff');
|
||||||
|
expect(web.headers.get('x-content-type-options')).toBe('nosniff');
|
||||||
|
}
|
||||||
|
});
|
||||||
it('SSE first two events', async () => {
|
it('SSE first two events', async () => {
|
||||||
const nodeText = await (await fetch(base + '/api/s')).text();
|
const nodeText = await (await fetch(base + '/api/s')).text();
|
||||||
const webText = await (await app.fetch(new Request(base + '/api/s'))).text();
|
const webText = await (await app.fetch(new Request(base + '/api/s'))).text();
|
||||||
|
|||||||
+77
-4
@@ -1,5 +1,12 @@
|
|||||||
import { describe, it, expect } from 'vitest';
|
import { describe, it, expect } from 'vitest';
|
||||||
import { matchPattern, matchRoute, allowedMethods } from '../src/http/router';
|
import {
|
||||||
|
compilePattern,
|
||||||
|
matchPattern,
|
||||||
|
matchRoute,
|
||||||
|
resolveRoute,
|
||||||
|
allowedMethods,
|
||||||
|
normalizeRequestPath,
|
||||||
|
} from '../src/http/router';
|
||||||
import type { RouteDef } from '../src/http/types';
|
import type { RouteDef } from '../src/http/types';
|
||||||
|
|
||||||
const route = (method: string, pattern: string): RouteDef => ({
|
const route = (method: string, pattern: string): RouteDef => ({
|
||||||
@@ -10,6 +17,11 @@ const route = (method: string, pattern: string): RouteDef => ({
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('matchPattern', () => {
|
describe('matchPattern', () => {
|
||||||
|
it('matches the root pattern only at root', () => {
|
||||||
|
expect(matchPattern('/', '/')).toEqual({});
|
||||||
|
expect(matchPattern('/', '/users')).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
it('matches static and :param segments, decoding params', () => {
|
it('matches static and :param segments, decoding params', () => {
|
||||||
expect(matchPattern('/users/:id', '/users/a%20b')).toEqual({ id: 'a b' });
|
expect(matchPattern('/users/:id', '/users/a%20b')).toEqual({ id: 'a b' });
|
||||||
expect(matchPattern('/users/:id', '/users')).toBeUndefined();
|
expect(matchPattern('/users/:id', '/users')).toBeUndefined();
|
||||||
@@ -24,6 +36,46 @@ describe('matchPattern', () => {
|
|||||||
it(':name* matches zero remaining segments as an empty string', () => {
|
it(':name* matches zero remaining segments as an empty string', () => {
|
||||||
expect(matchPattern('/files/:path*', '/files')).toEqual({ path: '' });
|
expect(matchPattern('/files/:path*', '/files')).toEqual({ path: '' });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('matches safe constraints against the complete decoded segment', () => {
|
||||||
|
expect(matchPattern('/users/:id(\\d+)', '/users/42')).toEqual({ id: '42' });
|
||||||
|
expect(matchPattern('/users/:id(\\d+)', '/users/42x')).toBeUndefined();
|
||||||
|
expect(matchPattern('/posts/:slug([a-z0-9_-]+)', '/posts/green-tea_26')).toEqual({ slug: 'green-tea_26' });
|
||||||
|
expect(matchPattern('/build/:version(\\d{2}\\.\\d{1,2})', '/build/26.8')).toEqual({ version: '26.8' });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('compilePattern', () => {
|
||||||
|
it('records a stable shape independent of parameter names', () => {
|
||||||
|
expect(compilePattern('/users/:id').shape).toBe(compilePattern('/users/:name').shape);
|
||||||
|
expect(compilePattern('/users/:id(\\d+)').shape).not.toBe(compilePattern('/users/:id').shape);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
'/files/:rest*/tail',
|
||||||
|
'/users/:',
|
||||||
|
'/users/:id/:id',
|
||||||
|
'/users//:id',
|
||||||
|
'/users/:id((a+)+)',
|
||||||
|
'/users/:id((?=a)a)',
|
||||||
|
'/users/:id(\\1)',
|
||||||
|
'/users/:id(a|b)',
|
||||||
|
])('rejects invalid or unsafe pattern %s', (pattern) => {
|
||||||
|
expect(() => compilePattern(pattern)).toThrow(/invalid route pattern|unsafe route constraint/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('normalizeRequestPath', () => {
|
||||||
|
it('treats one trailing slash as equivalent and preserves root', () => {
|
||||||
|
expect(normalizeRequestPath('/users')).toBe('/users');
|
||||||
|
expect(normalizeRequestPath('/users/')).toBe('/users');
|
||||||
|
expect(normalizeRequestPath('/')).toBe('/');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects repeated slashes and malformed percent encoding', () => {
|
||||||
|
expect(() => normalizeRequestPath('/users//42')).toThrow(/repeated slash/);
|
||||||
|
expect(() => normalizeRequestPath('/users/%E0%A4%A')).toThrow(/malformed path encoding/);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('matchRoute precedence', () => {
|
describe('matchRoute precedence', () => {
|
||||||
@@ -34,6 +86,12 @@ describe('matchRoute precedence', () => {
|
|||||||
expect(matchRoute(routes, 'GET', '/a/x/y')?.def.pattern).toBe('/a/:rest*');
|
expect(matchRoute(routes, 'GET', '/a/x/y')?.def.pattern).toBe('/a/:rest*');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('constrained params beat unconstrained params regardless of registration order', () => {
|
||||||
|
const routes = [route('GET', '/users/:value'), route('GET', '/users/:id(\\d+)')];
|
||||||
|
expect(matchRoute(routes, 'GET', '/users/42')?.def.pattern).toBe('/users/:id(\\d+)');
|
||||||
|
expect(matchRoute(routes, 'GET', '/users/diego')?.def.pattern).toBe('/users/:value');
|
||||||
|
});
|
||||||
|
|
||||||
it('returns undefined when no pattern matches the path', () => {
|
it('returns undefined when no pattern matches the path', () => {
|
||||||
expect(matchRoute([route('GET', '/a')], 'GET', '/b')).toBeUndefined();
|
expect(matchRoute([route('GET', '/a')], 'GET', '/b')).toBeUndefined();
|
||||||
});
|
});
|
||||||
@@ -44,9 +102,24 @@ describe('matchRoute precedence', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('allowedMethods (405 support)', () => {
|
describe('allowedMethods (405 support)', () => {
|
||||||
it('lists distinct methods whose pattern matches the path', () => {
|
it('lists methods in canonical order with implicit HEAD and OPTIONS', () => {
|
||||||
const routes = [route('GET', '/a'), route('POST', '/a'), route('GET', '/b')];
|
const routes = [route('POST', '/a'), route('GET', '/a'), route('GET', '/b')];
|
||||||
expect(allowedMethods(routes, '/a').sort()).toEqual(['GET', 'POST']);
|
expect(allowedMethods(routes, '/a')).toEqual(['GET', 'HEAD', 'POST', 'OPTIONS']);
|
||||||
expect(allowedMethods(routes, '/nope')).toEqual([]);
|
expect(allowedMethods(routes, '/nope')).toEqual([]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('resolveRoute', () => {
|
||||||
|
it('prefers explicit HEAD and otherwise falls back to buffered GET', () => {
|
||||||
|
const explicit = [route('GET', '/a'), route('HEAD', '/a')];
|
||||||
|
expect(resolveRoute(explicit, 'HEAD', '/a')).toMatchObject({ implicitHead: false, def: { method: 'HEAD' } });
|
||||||
|
|
||||||
|
const fallback = resolveRoute([route('GET', '/a')], 'HEAD', '/a');
|
||||||
|
expect(fallback).toMatchObject({ implicitHead: true, def: { method: 'GET' } });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not use a streaming GET as implicit HEAD', () => {
|
||||||
|
const streaming = { ...route('GET', '/a'), transport: 'sse' as const };
|
||||||
|
expect(resolveRoute([streaming], 'HEAD', '/a')).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
+8
-1
@@ -1,6 +1,13 @@
|
|||||||
import { expect, test } from 'vitest';
|
import { expect, test } from 'vitest';
|
||||||
import { VERSION } from '../src/index';
|
import { Head, Options, VERSION, type HttpMethod } from '../src/index';
|
||||||
|
|
||||||
test('package loads and exposes a CalVer VERSION', () => {
|
test('package loads and exposes a CalVer VERSION', () => {
|
||||||
expect(VERSION).toMatch(/^\d{2}\.\d{1,2}\.\d+(-beta\.\d+)?$/);
|
expect(VERSION).toMatch(/^\d{2}\.\d{1,2}\.\d+(-beta\.\d+)?$/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('public barrel exports HEAD and OPTIONS route decorators', () => {
|
||||||
|
const methods: HttpMethod[] = ['HEAD', 'OPTIONS'];
|
||||||
|
expect(Head).toBeTypeOf('function');
|
||||||
|
expect(Options).toBeTypeOf('function');
|
||||||
|
expect(methods).toEqual(['HEAD', 'OPTIONS']);
|
||||||
|
});
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { readFileSync } from 'node:fs';
|
||||||
|
import { resolve } from 'node:path';
|
||||||
|
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
|
const workflow = readFileSync(resolve(process.cwd(), '.github/workflows/stage.yml'), 'utf8');
|
||||||
|
|
||||||
|
describe('Verdaccio staging workflow', () => {
|
||||||
|
it('replaces mutable prereleases only from release branches', () => {
|
||||||
|
expect(workflow).toContain("branches: ['release/**']");
|
||||||
|
expect(workflow).toContain('npm audit');
|
||||||
|
expect(workflow).toContain('npm run prepublishOnly');
|
||||||
|
expect(workflow).toContain('npm unpublish');
|
||||||
|
expect(workflow).toContain('npm publish --ignore-scripts');
|
||||||
|
expect(workflow).not.toContain('scripts/staging-integrity.ts');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -187,7 +187,7 @@ describe('CORS', () => {
|
|||||||
expect(r.headers.get('access-control-allow-credentials')).toBe('true');
|
expect(r.headers.get('access-control-allow-credentials')).toBe('true');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('disallowed origin → no allow-origin; bare OPTIONS (no ACRM) → 405 Allow for an existing path', async () => {
|
it('disallowed origin → no allow-origin; bare OPTIONS (no ACRM) → automatic 204 Allow', async () => {
|
||||||
@Route('/') class C { @Get('/x') x() { return { ok: 1 }; } }
|
@Route('/') class C { @Get('/x') x() { return { ok: 1 }; } }
|
||||||
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
|
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
|
||||||
app = createApp({ modules: [CMod], cors: { origins: 'https://a.com' } });
|
app = createApp({ modules: [CMod], cors: { origins: 'https://a.com' } });
|
||||||
@@ -195,11 +195,11 @@ describe('CORS', () => {
|
|||||||
const port = (server.address() as any).port;
|
const port = (server.address() as any).port;
|
||||||
const r = await fetch(`http://127.0.0.1:${port}/x`, { headers: { origin: 'https://evil.com' } });
|
const r = await fetch(`http://127.0.0.1:${port}/x`, { headers: { origin: 'https://evil.com' } });
|
||||||
expect(r.headers.get('access-control-allow-origin')).toBeNull();
|
expect(r.headers.get('access-control-allow-origin')).toBeNull();
|
||||||
// A bare OPTIONS (no Access-Control-Request-Method) isn't a CORS preflight; the path exists
|
// A bare OPTIONS (no Access-Control-Request-Method) isn't a CORS preflight; the router
|
||||||
// under GET, so the router answers 405 with an Allow header rather than 404.
|
// answers it automatically and advertises the explicit + implicit methods.
|
||||||
const bare = await fetch(`http://127.0.0.1:${port}/x`, { method: 'OPTIONS' });
|
const bare = await fetch(`http://127.0.0.1:${port}/x`, { method: 'OPTIONS' });
|
||||||
expect(bare.status).toBe(405);
|
expect(bare.status).toBe(204);
|
||||||
expect(bare.headers.get('allow')).toContain('GET');
|
expect(bare.headers.get('allow')).toBe('GET, HEAD, OPTIONS');
|
||||||
});
|
});
|
||||||
|
|
||||||
it("merges a handler's Title-Case Vary with CORS's Origin", async () => {
|
it("merges a handler's Title-Case Vary with CORS's Origin", async () => {
|
||||||
|
|||||||
@@ -3,9 +3,24 @@ 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({
|
||||||
|
// GoatCounter — same site code as the marketing site, so /docs traffic lands in
|
||||||
|
// the same dashboard and referrer paths stay comparable.
|
||||||
|
head: [
|
||||||
|
{
|
||||||
|
tag: 'script',
|
||||||
|
attrs: {
|
||||||
|
'data-goatcounter': 'https://greentea.goatcounter.com/count',
|
||||||
|
async: true,
|
||||||
|
src: '//gc.zgo.at/count.js',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
// Let the content-backed 404.md own /404; otherwise Astro also injects a conflicting route.
|
||||||
|
disable404Route: true,
|
||||||
title: 'Green Tea.',
|
title: 'Green Tea.',
|
||||||
description: 'A zen, opinionated, type-safe framework — your API is a graph, not a chain.',
|
description: 'A zen, opinionated, type-safe framework — your API is a graph, not a chain.',
|
||||||
logo: { src: './src/assets/logo.svg', alt: 'Green Tea' },
|
logo: { src: './src/assets/logo.svg', alt: 'Green Tea' },
|
||||||
@@ -30,6 +45,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' },
|
||||||
|
|||||||
Generated
+161
-174
@@ -6,35 +6,35 @@
|
|||||||
"": {
|
"": {
|
||||||
"name": "green-tea-docs",
|
"name": "green-tea-docs",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@astrojs/starlight": "^0.41.3",
|
"@astrojs/starlight": "^0.41.6",
|
||||||
"astro": "^7.0.6",
|
"astro": "^7.1.6",
|
||||||
"sharp": "^0.35.3"
|
"sharp": "^0.35.3"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/compiler-binding": {
|
"node_modules/@astrojs/compiler-binding": {
|
||||||
"version": "0.3.0",
|
"version": "0.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding/-/compiler-binding-0.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding/-/compiler-binding-0.3.2.tgz",
|
||||||
"integrity": "sha512-zlsOT5COD9hRwplJCgQhS21unxON5AKirf0vgt1ijXwuseYIaZdm2ZOpF8fsz+DY9EyXx+I/ukxtg7uoBep68A==",
|
"integrity": "sha512-8w/9CWmYrAJJ8N0SY3O43ws2BgxoW6u3QsD8u2mE140lMYAlwh+tlNoUeSBq22wVheFuiBbR212l6ixZ2IIgCQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "^20.19.0 || >=22.12.0"
|
"node": "^20.19.0 || >=22.12.0"
|
||||||
},
|
},
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@astrojs/compiler-binding-darwin-arm64": "0.3.0",
|
"@astrojs/compiler-binding-darwin-arm64": "0.3.2",
|
||||||
"@astrojs/compiler-binding-darwin-x64": "0.3.0",
|
"@astrojs/compiler-binding-darwin-x64": "0.3.2",
|
||||||
"@astrojs/compiler-binding-linux-arm64-gnu": "0.3.0",
|
"@astrojs/compiler-binding-linux-arm64-gnu": "0.3.2",
|
||||||
"@astrojs/compiler-binding-linux-arm64-musl": "0.3.0",
|
"@astrojs/compiler-binding-linux-arm64-musl": "0.3.2",
|
||||||
"@astrojs/compiler-binding-linux-x64-gnu": "0.3.0",
|
"@astrojs/compiler-binding-linux-x64-gnu": "0.3.2",
|
||||||
"@astrojs/compiler-binding-linux-x64-musl": "0.3.0",
|
"@astrojs/compiler-binding-linux-x64-musl": "0.3.2",
|
||||||
"@astrojs/compiler-binding-wasm32-wasi": "0.3.0",
|
"@astrojs/compiler-binding-wasm32-wasi": "0.3.2",
|
||||||
"@astrojs/compiler-binding-win32-arm64-msvc": "0.3.0",
|
"@astrojs/compiler-binding-win32-arm64-msvc": "0.3.2",
|
||||||
"@astrojs/compiler-binding-win32-x64-msvc": "0.3.0"
|
"@astrojs/compiler-binding-win32-x64-msvc": "0.3.2"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/compiler-binding-darwin-arm64": {
|
"node_modules/@astrojs/compiler-binding-darwin-arm64": {
|
||||||
"version": "0.3.0",
|
"version": "0.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-darwin-arm64/-/compiler-binding-darwin-arm64-0.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-darwin-arm64/-/compiler-binding-darwin-arm64-0.3.2.tgz",
|
||||||
"integrity": "sha512-3n0uu+uJpnCq8b4JFi3uGDsIisAvHctxSmH+cIO9Gbei1H1Y1QXaYboXyiWJugUmprr3OEYP7+LdodzpVFzLMQ==",
|
"integrity": "sha512-MM8tn8CSimcfytaOla4b6acN8mKWiL/rlAA1fpT3/Wl7dNGSE4y8FjTN/zJVNnb63CsLWG5zZwCt01TXtDKh9g==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -48,9 +48,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/compiler-binding-darwin-x64": {
|
"node_modules/@astrojs/compiler-binding-darwin-x64": {
|
||||||
"version": "0.3.0",
|
"version": "0.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-darwin-x64/-/compiler-binding-darwin-x64-0.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-darwin-x64/-/compiler-binding-darwin-x64-0.3.2.tgz",
|
||||||
"integrity": "sha512-scxNGKjOBydMo1QR4LtK0FMgh7ubQomJDv953nz2msQFkPKke/0FpPv/cQM0T/kuZdReZQFU8Oz3iOrP/6WHEg==",
|
"integrity": "sha512-2lXOlzf8xb7jLomRsf/aswh61/NnGusynB2OwFkK6k4pmOtpfXMYnG0PLfXrEvxXYj69NdCnmUYXtHDd+JOOag==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -64,9 +64,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/compiler-binding-linux-arm64-gnu": {
|
"node_modules/@astrojs/compiler-binding-linux-arm64-gnu": {
|
||||||
"version": "0.3.0",
|
"version": "0.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-arm64-gnu/-/compiler-binding-linux-arm64-gnu-0.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-arm64-gnu/-/compiler-binding-linux-arm64-gnu-0.3.2.tgz",
|
||||||
"integrity": "sha512-NZrWLolVUANmrnl0zrFK/Sx5Sock1gEUT49ALfMTTCA5Ya2ec/BoJXMIg4KgE+wZcrdXJ8e+WyEhM7YLk/FJkA==",
|
"integrity": "sha512-BmU3kWj7qnLrd4vzm49zFEPJ5oFnn1tCT4Vt9hZbqdU5Cmb8GZl7fn6VFsnNfe7B18a2gIFtVzbLINtYl5kBjQ==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -80,9 +80,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/compiler-binding-linux-arm64-musl": {
|
"node_modules/@astrojs/compiler-binding-linux-arm64-musl": {
|
||||||
"version": "0.3.0",
|
"version": "0.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-arm64-musl/-/compiler-binding-linux-arm64-musl-0.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-arm64-musl/-/compiler-binding-linux-arm64-musl-0.3.2.tgz",
|
||||||
"integrity": "sha512-PjwRmKgMFDsFhg82g0poXlIY8Qn3fMA3hXjaR0coJWJzTJsRH9ATU0j2ocigjtU1h3vL/yR7yLUxGj/lTCq73g==",
|
"integrity": "sha512-f0heT9ZZEseSu5bHCeb80eL2DH07ArE6U9xi1WT/PEusNjzPmEr3GJsjG1tRLo5VYUUYX7h3ScaqGmGrMOVGmw==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -96,9 +96,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/compiler-binding-linux-x64-gnu": {
|
"node_modules/@astrojs/compiler-binding-linux-x64-gnu": {
|
||||||
"version": "0.3.0",
|
"version": "0.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-x64-gnu/-/compiler-binding-linux-x64-gnu-0.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-x64-gnu/-/compiler-binding-linux-x64-gnu-0.3.2.tgz",
|
||||||
"integrity": "sha512-Dr69VJYlnSfyL8gzELW6S4mE41P7TDPn1IKjwMnjdZ7+dxgJI50oMLFSk1LVe26bHmWB3ktuh8fDVK1THI9e9A==",
|
"integrity": "sha512-M8fOUt0itRpqiGyoEA/ij184s8O+hqbCz3+YozRusOOM3osgGljpDThhbKAJjqh82wOo6FioQ4w8PBvU1XMD5Q==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -112,9 +112,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/compiler-binding-linux-x64-musl": {
|
"node_modules/@astrojs/compiler-binding-linux-x64-musl": {
|
||||||
"version": "0.3.0",
|
"version": "0.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-x64-musl/-/compiler-binding-linux-x64-musl-0.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-x64-musl/-/compiler-binding-linux-x64-musl-0.3.2.tgz",
|
||||||
"integrity": "sha512-AEt+bRw8PfImCcyRH1lpXVB8CdmQ1K/wPo5u99iec4/U/XdNvQZ715YVuNzIJpbJXelgQeZ5H2+Ea7XwRyWY5g==",
|
"integrity": "sha512-/Kebk8sO6HnLeSd691JkaAPfN7CqR9/KEXmWvyNPkaKNGmj8rTZ/lf2uXtnPu92Lan84UrKdIKVPy1fSo2encQ==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -128,25 +128,25 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/compiler-binding-wasm32-wasi": {
|
"node_modules/@astrojs/compiler-binding-wasm32-wasi": {
|
||||||
"version": "0.3.0",
|
"version": "0.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-wasm32-wasi/-/compiler-binding-wasm32-wasi-0.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-wasm32-wasi/-/compiler-binding-wasm32-wasi-0.3.2.tgz",
|
||||||
"integrity": "sha512-U80tA1j8V6LjhiTZzVCtG4E8hrNVVNXDGV5fCgJ94q8FU9CPH+XwdDDhLzBybfWhKfyItXmQiZNRPTiPCYTpVg==",
|
"integrity": "sha512-pUA6xbcOSB7DhfzIArB8BCAkFfAIqriiR7zl5zOStd6oU2G0kIKj+GUdGnyXyhfiv881Hffyk5tC0mR18sDjDw==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"wasm32"
|
"wasm32"
|
||||||
],
|
],
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@napi-rs/wasm-runtime": "^1.1.6"
|
"@napi-rs/wasm-runtime": "^1.2.0"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=14.0.0"
|
"node": ">=14.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/compiler-binding-win32-arm64-msvc": {
|
"node_modules/@astrojs/compiler-binding-win32-arm64-msvc": {
|
||||||
"version": "0.3.0",
|
"version": "0.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-win32-arm64-msvc/-/compiler-binding-win32-arm64-msvc-0.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-win32-arm64-msvc/-/compiler-binding-win32-arm64-msvc-0.3.2.tgz",
|
||||||
"integrity": "sha512-CpY1RII2r1XMpOUVD1VR/F2wtuRsiOCkFULS10Khyj8/DFZMtxVuUCAWGw+CW2Ka0h6eP3Xc1CA+glFlvXMPxA==",
|
"integrity": "sha512-ESruf+6Qkl1trHUFxI6GSf6t52j8yN2kCNSzMWdzt7V/T09tFHrYzrVaJQohb2C9bJUH76pNvX6Zb51+xCQc9Q==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -160,9 +160,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/compiler-binding-win32-x64-msvc": {
|
"node_modules/@astrojs/compiler-binding-win32-x64-msvc": {
|
||||||
"version": "0.3.0",
|
"version": "0.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-win32-x64-msvc/-/compiler-binding-win32-x64-msvc-0.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-win32-x64-msvc/-/compiler-binding-win32-x64-msvc-0.3.2.tgz",
|
||||||
"integrity": "sha512-qmFbs769oeeGrRebAnCW7aBk8m71vf85W/dX/jddfx5Z06/w0wf7TZCfJPOX1Fld2t+4N+iXzfGEJG+zJQ+bzg==",
|
"integrity": "sha512-wzzVrEbOwbsLWOdEbocskjMRx2aZPxJ7ZbmL+jnpBamFwmigm+2M/wzuM6JWncocgYwLic1csSpalBh96kQKXA==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -176,12 +176,12 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/compiler-rs": {
|
"node_modules/@astrojs/compiler-rs": {
|
||||||
"version": "0.3.0",
|
"version": "0.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/compiler-rs/-/compiler-rs-0.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/compiler-rs/-/compiler-rs-0.3.2.tgz",
|
||||||
"integrity": "sha512-J2qEVHtIDjEM9TxwmwuebOGmZNwhKu/dR7P7qBpnJKGmBBX0vdweQ/4cEXhj8fBbWVUB5V12xWChri3CgKNULQ==",
|
"integrity": "sha512-xlx/T7JovIKduu4ucbTQUxQ5+Q8wxkHxhLjnZk3VlJbhbQ9RLvvuDk1p2YYFYFQ5y14dVm3FGGO4isQXa4F+Tg==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@astrojs/compiler-binding": "0.3.0"
|
"@astrojs/compiler-binding": "0.3.2"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=22.12.0"
|
"node": ">=22.12.0"
|
||||||
@@ -203,41 +203,33 @@
|
|||||||
"unified": "^11.0.5"
|
"unified": "^11.0.5"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/markdown-remark": {
|
"node_modules/@astrojs/markdown-satteri": {
|
||||||
"version": "7.2.1",
|
"version": "0.3.5",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/markdown-remark/-/markdown-remark-7.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/markdown-satteri/-/markdown-satteri-0.3.5.tgz",
|
||||||
"integrity": "sha512-jPVNIqTvk+yKviikszv/Y1U4jGUSKpp/Nw48QZV4qjWgp70j4Lkq3lhSDRbWwCfgKvEyO9GHuVbV1dM2WYXy1w==",
|
"integrity": "sha512-CvWVEFAbay7YO+i9SaqDJubipA5ckiVB89QWoMJ5XC0m5CtFg8JwZ7Kau6X9sYY7FZURH0w2l03ISH2jOS/RDQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@astrojs/internal-helpers": "0.10.1",
|
"@astrojs/internal-helpers": "0.10.2",
|
||||||
"@astrojs/prism": "4.0.2",
|
"@astrojs/prism": "4.0.2",
|
||||||
"github-slugger": "^2.0.0",
|
"github-slugger": "^2.0.0",
|
||||||
"hast-util-from-html": "^2.0.3",
|
"hast-util-from-html": "^2.0.3",
|
||||||
"hast-util-to-text": "^4.0.2",
|
"satteri": "^0.9.1"
|
||||||
"mdast-util-definitions": "^6.0.0",
|
|
||||||
"rehype-raw": "^7.0.0",
|
|
||||||
"rehype-stringify": "^10.0.1",
|
|
||||||
"remark-gfm": "^4.0.1",
|
|
||||||
"remark-parse": "^11.0.0",
|
|
||||||
"remark-rehype": "^11.1.2",
|
|
||||||
"remark-smartypants": "^3.0.2",
|
|
||||||
"unified": "^11.0.5",
|
|
||||||
"unist-util-remove-position": "^5.0.0",
|
|
||||||
"unist-util-visit": "^5.1.0",
|
|
||||||
"unist-util-visit-parents": "^6.0.2",
|
|
||||||
"vfile": "^6.0.3"
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/markdown-satteri": {
|
"node_modules/@astrojs/markdown-satteri/node_modules/@astrojs/internal-helpers": {
|
||||||
"version": "0.3.3",
|
"version": "0.10.2",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/markdown-satteri/-/markdown-satteri-0.3.3.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/internal-helpers/-/internal-helpers-0.10.2.tgz",
|
||||||
"integrity": "sha512-Lje33Ittd8UQGgbIIWQvhPkj5X5c4b1sZnZWX3JQV/AWpfbuQGxVi2ONt6+ScydcwfR4egilslEWyczMclrJ1g==",
|
"integrity": "sha512-yt7fMgPYqSM4Tmr+taTW6Per+hjJ8Pk6lA1PAcDyqzOt8HzJ6Kje5WzCxA2Sd+9wsUW7uhkLeoTMK0cXPwH9rQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@astrojs/internal-helpers": "0.10.1",
|
"@types/hast": "^3.0.4",
|
||||||
"@astrojs/prism": "4.0.2",
|
"@types/mdast": "^4.0.4",
|
||||||
"github-slugger": "^2.0.0",
|
"js-yaml": "^4.3.0",
|
||||||
"satteri": "^0.9.1"
|
"picomatch": "^4.0.4",
|
||||||
|
"retext-smartypants": "^6.2.0",
|
||||||
|
"shiki": "^4.0.2",
|
||||||
|
"smol-toml": "^1.6.0",
|
||||||
|
"unified": "^11.0.5"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/mdx": {
|
"node_modules/@astrojs/mdx": {
|
||||||
@@ -274,6 +266,31 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@astrojs/mdx/node_modules/@astrojs/markdown-remark": {
|
||||||
|
"version": "7.2.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@astrojs/markdown-remark/-/markdown-remark-7.2.1.tgz",
|
||||||
|
"integrity": "sha512-jPVNIqTvk+yKviikszv/Y1U4jGUSKpp/Nw48QZV4qjWgp70j4Lkq3lhSDRbWwCfgKvEyO9GHuVbV1dM2WYXy1w==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@astrojs/internal-helpers": "0.10.1",
|
||||||
|
"@astrojs/prism": "4.0.2",
|
||||||
|
"github-slugger": "^2.0.0",
|
||||||
|
"hast-util-from-html": "^2.0.3",
|
||||||
|
"hast-util-to-text": "^4.0.2",
|
||||||
|
"mdast-util-definitions": "^6.0.0",
|
||||||
|
"rehype-raw": "^7.0.0",
|
||||||
|
"rehype-stringify": "^10.0.1",
|
||||||
|
"remark-gfm": "^4.0.1",
|
||||||
|
"remark-parse": "^11.0.0",
|
||||||
|
"remark-rehype": "^11.1.2",
|
||||||
|
"remark-smartypants": "^3.0.2",
|
||||||
|
"unified": "^11.0.5",
|
||||||
|
"unist-util-remove-position": "^5.0.0",
|
||||||
|
"unist-util-visit": "^5.1.0",
|
||||||
|
"unist-util-visit-parents": "^6.0.2",
|
||||||
|
"vfile": "^6.0.3"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@astrojs/prism": {
|
"node_modules/@astrojs/prism": {
|
||||||
"version": "4.0.2",
|
"version": "4.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/prism/-/prism-4.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/prism/-/prism-4.0.2.tgz",
|
||||||
@@ -298,9 +315,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/starlight": {
|
"node_modules/@astrojs/starlight": {
|
||||||
"version": "0.41.3",
|
"version": "0.41.6",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/starlight/-/starlight-0.41.3.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/starlight/-/starlight-0.41.6.tgz",
|
||||||
"integrity": "sha512-8xsG6UpK581TJmtOc7/pnxHKEbP16rV06VLWaVa7FOyE/VEwnaHOsLtL+miifCEfuiuv0Wn+j8u3JSluRQesMQ==",
|
"integrity": "sha512-Dt0/wY2JbFGUpxMgclw1j2Iqks2GG0LHYKgP7TfBXsFrs4LIbKvQ596lzyhXLz6nFcnPdIB9ZRFyDJeuVcx3Ug==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@astrojs/markdown-satteri": "^0.3.2",
|
"@astrojs/markdown-satteri": "^0.3.2",
|
||||||
@@ -344,16 +361,15 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/telemetry": {
|
"node_modules/@astrojs/telemetry": {
|
||||||
"version": "3.3.2",
|
"version": "3.3.3",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/telemetry/-/telemetry-3.3.2.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/telemetry/-/telemetry-3.3.3.tgz",
|
||||||
"integrity": "sha512-j8DNruA8ors99Al39RYZPJK4DC1bKkoNm93mAMuBhY9TCNC4R8n1q7ovFnJ5qhGh5Lsh7pa1gpQVpYpsJPeTHQ==",
|
"integrity": "sha512-C1TLn5sPJr0x4vk56piHWKbnqlEB8BKyte5Y45V02U+D7BGO5eMqZDH5aPjnkXQWJggvmsTXxH03QMZ9NgWLzQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"ci-info": "^4.4.0",
|
"ci-info": "^4.4.0",
|
||||||
"dset": "^3.1.4",
|
"dset": "^3.1.4",
|
||||||
"is-docker": "^4.0.0",
|
"is-docker": "^4.0.0",
|
||||||
"is-wsl": "^3.1.1",
|
"package-manager-detector": "^1.6.0"
|
||||||
"which-pm-runs": "^1.1.0"
|
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "18.20.8 || ^20.3.0 || >=22.0.0"
|
"node": "18.20.8 || ^20.3.0 || >=22.0.0"
|
||||||
@@ -1625,21 +1641,24 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@napi-rs/wasm-runtime": {
|
"node_modules/@napi-rs/wasm-runtime": {
|
||||||
"version": "1.1.6",
|
"version": "1.2.2",
|
||||||
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.6.tgz",
|
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.2.tgz",
|
||||||
"integrity": "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==",
|
"integrity": "sha512-JfB4kuJQjaoHuCTseIINHtHWeJnvgEcxjwA5t/Y00ZgaOO1Crz3fjT/p8kT28zA/Caz7oiUMn3d6H2yOVCVwuw==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@tybys/wasm-util": "^0.10.3"
|
"@tybys/wasm-util": "^0.10.3"
|
||||||
},
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "^20.19.0 || ^22.13.0 || >=23.5.0"
|
||||||
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"type": "github",
|
"type": "github",
|
||||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@emnapi/core": "^1.7.1",
|
"@emnapi/core": "^1.7.1 || ^2.0.0-alpha.3",
|
||||||
"@emnapi/runtime": "^1.7.1"
|
"@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.3"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@oslojs/encoding": {
|
"node_modules/@oslojs/encoding": {
|
||||||
@@ -2359,15 +2378,15 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/astro": {
|
"node_modules/astro": {
|
||||||
"version": "7.0.6",
|
"version": "7.1.6",
|
||||||
"resolved": "https://registry.npmjs.org/astro/-/astro-7.0.6.tgz",
|
"resolved": "https://registry.npmjs.org/astro/-/astro-7.1.6.tgz",
|
||||||
"integrity": "sha512-Myw0sFia+zs/Y0yqfZEsUYXfDPh3ELcLf1f0Q/qQzVXBh/af1qO62WNT+P89DCcfGVV51nMoQhEfkBYqJmoUOQ==",
|
"integrity": "sha512-83x9rYbHazMaZkYrAFRVZXSQx2moFkz0F7cjTDUF3GWfS0a3p2vZXG1ZdhV86rStHApQCodBJW+XTD37xISIrQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@astrojs/compiler-rs": "^0.3.0",
|
"@astrojs/compiler-rs": "^0.3.2",
|
||||||
"@astrojs/internal-helpers": "0.10.1",
|
"@astrojs/internal-helpers": "0.10.2",
|
||||||
"@astrojs/markdown-satteri": "0.3.3",
|
"@astrojs/markdown-satteri": "0.3.5",
|
||||||
"@astrojs/telemetry": "3.3.2",
|
"@astrojs/telemetry": "3.3.3",
|
||||||
"@capsizecss/unpack": "^4.0.0",
|
"@capsizecss/unpack": "^4.0.0",
|
||||||
"@clack/prompts": "^1.1.0",
|
"@clack/prompts": "^1.1.0",
|
||||||
"@oslojs/encoding": "^1.1.0",
|
"@oslojs/encoding": "^1.1.0",
|
||||||
@@ -2378,7 +2397,7 @@
|
|||||||
"ci-info": "^4.4.0",
|
"ci-info": "^4.4.0",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"common-ancestor-path": "^2.0.0",
|
"common-ancestor-path": "^2.0.0",
|
||||||
"cookie": "^1.1.1",
|
"cookie": "^2.0.1",
|
||||||
"devalue": "^5.8.1",
|
"devalue": "^5.8.1",
|
||||||
"diff": "^8.0.3",
|
"diff": "^8.0.3",
|
||||||
"dset": "^3.1.4",
|
"dset": "^3.1.4",
|
||||||
@@ -2390,12 +2409,12 @@
|
|||||||
"github-slugger": "^2.0.0",
|
"github-slugger": "^2.0.0",
|
||||||
"html-escaper": "3.0.3",
|
"html-escaper": "3.0.3",
|
||||||
"http-cache-semantics": "^4.2.0",
|
"http-cache-semantics": "^4.2.0",
|
||||||
"js-yaml": "^4.1.1",
|
"js-yaml": "^4.3.0",
|
||||||
"jsonc-parser": "^3.3.1",
|
"jsonc-parser": "^3.3.1",
|
||||||
"magic-string": "^0.30.21",
|
"magic-string": "^1.0.0",
|
||||||
"magicast": "^0.5.2",
|
"magicast": "^0.5.2",
|
||||||
"mrmime": "^2.0.1",
|
"mrmime": "^2.0.1",
|
||||||
"neotraverse": "^0.6.18",
|
"neotraverse": "^1.0.1",
|
||||||
"obug": "^2.1.1",
|
"obug": "^2.1.1",
|
||||||
"p-limit": "^7.3.0",
|
"p-limit": "^7.3.0",
|
||||||
"p-queue": "^9.1.0",
|
"p-queue": "^9.1.0",
|
||||||
@@ -2434,7 +2453,7 @@
|
|||||||
"sharp": "^0.34.0 || ^0.35.0"
|
"sharp": "^0.34.0 || ^0.35.0"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@astrojs/markdown-remark": "7.2.1"
|
"@astrojs/markdown-remark": "7.2.2"
|
||||||
},
|
},
|
||||||
"peerDependenciesMeta": {
|
"peerDependenciesMeta": {
|
||||||
"@astrojs/markdown-remark": {
|
"@astrojs/markdown-remark": {
|
||||||
@@ -2455,6 +2474,31 @@
|
|||||||
"astro": "^4.0.0-beta || ^5.0.0-beta || ^3.3.0 || ^6.0.0-beta || ^7.0.0"
|
"astro": "^4.0.0-beta || ^5.0.0-beta || ^3.3.0 || ^6.0.0-beta || ^7.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/astro/node_modules/@astrojs/internal-helpers": {
|
||||||
|
"version": "0.10.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@astrojs/internal-helpers/-/internal-helpers-0.10.2.tgz",
|
||||||
|
"integrity": "sha512-yt7fMgPYqSM4Tmr+taTW6Per+hjJ8Pk6lA1PAcDyqzOt8HzJ6Kje5WzCxA2Sd+9wsUW7uhkLeoTMK0cXPwH9rQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@types/hast": "^3.0.4",
|
||||||
|
"@types/mdast": "^4.0.4",
|
||||||
|
"js-yaml": "^4.3.0",
|
||||||
|
"picomatch": "^4.0.4",
|
||||||
|
"retext-smartypants": "^6.2.0",
|
||||||
|
"shiki": "^4.0.2",
|
||||||
|
"smol-toml": "^1.6.0",
|
||||||
|
"unified": "^11.0.5"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/astro/node_modules/magic-string": {
|
||||||
|
"version": "1.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.1.0.tgz",
|
||||||
|
"integrity": "sha512-kS3VHe0nEPST2saQV4Rbkchcd3UBRkVTQHo1D3h/ZTwFDhai/mfKkmtPAtD129EOI7K3HlHIsFOt0WrI2/oU9g==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@jridgewell/sourcemap-codec": "^1.5.5"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/axobject-query": {
|
"node_modules/axobject-query": {
|
||||||
"version": "4.1.0",
|
"version": "4.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz",
|
||||||
@@ -2633,12 +2677,12 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/cookie": {
|
"node_modules/cookie": {
|
||||||
"version": "1.1.1",
|
"version": "2.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/cookie/-/cookie-2.0.1.tgz",
|
||||||
"integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==",
|
"integrity": "sha512-yuToqVvRrj6pfDXREyQAAv8SkAEk/8GS3jQRTiUMm66TVtBYmqQeoEjL2Lmq8Rpo6271vH76InTChTitEAm65w==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=18"
|
"node": ">=22"
|
||||||
},
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"type": "opencollective",
|
"type": "opencollective",
|
||||||
@@ -3779,39 +3823,6 @@
|
|||||||
"url": "https://github.com/sponsors/wooorm"
|
"url": "https://github.com/sponsors/wooorm"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/is-inside-container": {
|
|
||||||
"version": "1.0.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/is-inside-container/-/is-inside-container-1.0.0.tgz",
|
|
||||||
"integrity": "sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"is-docker": "^3.0.0"
|
|
||||||
},
|
|
||||||
"bin": {
|
|
||||||
"is-inside-container": "cli.js"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=14.16"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"url": "https://github.com/sponsors/sindresorhus"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/is-inside-container/node_modules/is-docker": {
|
|
||||||
"version": "3.0.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/is-docker/-/is-docker-3.0.0.tgz",
|
|
||||||
"integrity": "sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"bin": {
|
|
||||||
"is-docker": "cli.js"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"url": "https://github.com/sponsors/sindresorhus"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/is-plain-obj": {
|
"node_modules/is-plain-obj": {
|
||||||
"version": "4.1.0",
|
"version": "4.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz",
|
||||||
@@ -3824,25 +3835,10 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/is-wsl": {
|
|
||||||
"version": "3.1.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-3.1.1.tgz",
|
|
||||||
"integrity": "sha512-e6rvdUCiQCAuumZslxRJWR/Doq4VpPR82kqclvcS0efgt430SlGIk05vdCN58+VrzgtIcfNODjozVielycD4Sw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"is-inside-container": "^1.0.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=16"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"url": "https://github.com/sponsors/sindresorhus"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/js-yaml": {
|
"node_modules/js-yaml": {
|
||||||
"version": "4.3.0",
|
"version": "4.3.1",
|
||||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.1.tgz",
|
||||||
"integrity": "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==",
|
"integrity": "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==",
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
"type": "github",
|
"type": "github",
|
||||||
@@ -5267,9 +5263,9 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/nanoid": {
|
"node_modules/nanoid": {
|
||||||
"version": "3.3.15",
|
"version": "3.3.16",
|
||||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.15.tgz",
|
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz",
|
||||||
"integrity": "sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA==",
|
"integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==",
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
"type": "github",
|
"type": "github",
|
||||||
@@ -5285,9 +5281,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/neotraverse": {
|
"node_modules/neotraverse": {
|
||||||
"version": "0.6.18",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/neotraverse/-/neotraverse-0.6.18.tgz",
|
"resolved": "https://registry.npmjs.org/neotraverse/-/neotraverse-1.0.1.tgz",
|
||||||
"integrity": "sha512-Z4SmBUweYa09+o6pG+eASabEpP6QkQ70yHj351pQoEXIs8uHbaU2DWVmzBANKgflPa47A50PtB2+NgRpQvr7vA==",
|
"integrity": "sha512-WmmLty1YWwJl9yZi77v2dVIV6X2kuYV8YYBI/G3LWGKdGHmHUvL1z7FW0iDvEvGAwNEoc5x1tOOOyDnf5jJw/w==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">= 10"
|
"node": ">= 10"
|
||||||
@@ -5533,9 +5529,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/postcss": {
|
"node_modules/postcss": {
|
||||||
"version": "8.5.16",
|
"version": "8.5.25",
|
||||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.16.tgz",
|
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.25.tgz",
|
||||||
"integrity": "sha512-vuwillviilfKZsg0VGj5R/YwwcHx4SLsIOI/7K6mQkWx+l5cUHTjj5g0AasTBcyXsbfTgrwsUNmVUb5xVwyPwg==",
|
"integrity": "sha512-DTPx3RWSSnWyzLxQnlH0rJP+EW5ekl16ZU4/psbIhA0e53kJfdgaN5vKM+xP7yJtXVu+nfdVFmlgFDEKAe4Pyw==",
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
"type": "opencollective",
|
"type": "opencollective",
|
||||||
@@ -5552,7 +5548,7 @@
|
|||||||
],
|
],
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"nanoid": "^3.3.12",
|
"nanoid": "^3.3.16",
|
||||||
"picocolors": "^1.1.1",
|
"picocolors": "^1.1.1",
|
||||||
"source-map-js": "^1.2.1"
|
"source-map-js": "^1.2.1"
|
||||||
},
|
},
|
||||||
@@ -6264,9 +6260,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/svgo": {
|
"node_modules/svgo": {
|
||||||
"version": "4.0.1",
|
"version": "4.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/svgo/-/svgo-4.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/svgo/-/svgo-4.0.2.tgz",
|
||||||
"integrity": "sha512-XDpWUOPC6FEibaLzjfe0ucaV0YrOjYotGJO1WpF0Zd+n6ZGEQUsSugaoLq9QkEZtAfQIxT42UChcssDVPP3+/w==",
|
"integrity": "sha512-ekx94z1rRc5LDi6oSUaeRnYhd0UOJxdtQCL2rF8xpWxD3TPAsISWOrxezqGovqS38GRZOdpDfvQe3ts6F7nsng==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"commander": "^11.1.0",
|
"commander": "^11.1.0",
|
||||||
@@ -6807,15 +6803,6 @@
|
|||||||
"url": "https://github.com/sponsors/wooorm"
|
"url": "https://github.com/sponsors/wooorm"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/which-pm-runs": {
|
|
||||||
"version": "1.1.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/which-pm-runs/-/which-pm-runs-1.1.0.tgz",
|
|
||||||
"integrity": "sha512-n1brCuqClxfFfq/Rb0ICg9giSZqCS+pLtccdag6C2HyufBrh3fBOiy9nb6ggRMvWOVH5GrdJskj5iGTZNxd7SA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=4"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/xxhash-wasm": {
|
"node_modules/xxhash-wasm": {
|
||||||
"version": "1.1.0",
|
"version": "1.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/xxhash-wasm/-/xxhash-wasm-1.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/xxhash-wasm/-/xxhash-wasm-1.1.0.tgz",
|
||||||
|
|||||||
@@ -8,8 +8,8 @@
|
|||||||
"preview": "astro preview"
|
"preview": "astro preview"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@astrojs/starlight": "^0.41.3",
|
"@astrojs/starlight": "^0.41.6",
|
||||||
"astro": "^7.0.6",
|
"astro": "^7.1.6",
|
||||||
"sharp": "^0.35.3"
|
"sharp": "^0.35.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
---
|
||||||
|
title: Page not found
|
||||||
|
description: "The requested Green Tea documentation page does not exist."
|
||||||
|
template: splash
|
||||||
|
hero:
|
||||||
|
tagline: The documentation page you requested could not be found.
|
||||||
|
actions:
|
||||||
|
- text: Back to documentation
|
||||||
|
link: /docs/
|
||||||
|
icon: right-arrow
|
||||||
|
---
|
||||||
@@ -3,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/).
|
||||||
@@ -46,12 +46,12 @@ throw new HttpError(409, 'conflict', { code: 'DUP_EMAIL', field: 'email' });
|
|||||||
Not everything should be JSON. Pass `onError` to `createApp` to render errors however you like — HTML, [RFC 7807](https://www.rfc-editor.org/rfc/rfc7807), content-negotiated, anything. It receives the error and the request, and returns a response — or `undefined` to fall back to the default JSON.
|
Not everything should be JSON. Pass `onError` to `createApp` to render errors however you like — HTML, [RFC 7807](https://www.rfc-editor.org/rfc/rfc7807), content-negotiated, anything. It receives the error and the request, and returns a response — or `undefined` to fall back to the default JSON.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import { isHttpError } from '@green-tea/core';
|
import { HttpError } from '@green-tea/core';
|
||||||
|
|
||||||
const app = createApp({
|
const app = createApp({
|
||||||
modules: [ApiModule],
|
modules: [ApiModule],
|
||||||
onError(error, req) {
|
onError(error, req) {
|
||||||
const status = isHttpError(error) ? error.status : 500;
|
const status = error instanceof HttpError ? error.status : 500;
|
||||||
// negotiate: HTML for browsers, JSON for API clients
|
// negotiate: HTML for browsers, JSON for API clients
|
||||||
if (String(req.headers.accept).includes('text/html')) {
|
if (String(req.headers.accept).includes('text/html')) {
|
||||||
return { status, headers: { 'content-type': 'text/html' }, body: `<h1>${status}</h1>` };
|
return { status, headers: { 'content-type': 'text/html' }, body: `<h1>${status}</h1>` };
|
||||||
@@ -61,8 +61,8 @@ const app = createApp({
|
|||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
`onError` intercepts **every** HTTP error response — handler/step throws, a `404` for an unmatched route, `405`, a `413` (body too large), and a `400` (malformed body) — so your error surface is consistent across the whole app. Streaming and WebSocket errors are out of scope (they surface as an error frame or a WebSocket close code, not a response body).
|
`onError` intercepts **every** HTTP error response — handler/step throws, a `404` for an unmatched route, `405`, a `413` (body too large), and a `400` (malformed body, repeated slash, or malformed path encoding) — so your error surface is consistent across the whole app. HEAD error responses keep the same status and headers but suppress the body. Streaming and WebSocket errors are out of scope (they surface as an error frame or a WebSocket close code, not a response body).
|
||||||
|
|
||||||
:::note
|
:::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
|
||||||
|
|
||||||
@@ -67,7 +67,7 @@ Same filesystem requirement as file mode: Node/Deno/Bun only.
|
|||||||
`string`; `@Html('file.html', { template: true })` returns the data object rendered into the
|
`string`; `@Html('file.html', { template: true })` returns the data object rendered into the
|
||||||
template; `@Html('file.html')` (no template) ignores the return entirely — annotate it `: void`
|
template; `@Html('file.html')` (no template) ignores the return entirely — annotate it `: void`
|
||||||
by convention, e.g. `page(@needs('x')): void {}`. Returning an `AsyncIterable` from any `@Html`
|
by convention, e.g. `page(@needs('x')): void {}`. Returning an `AsyncIterable` from any `@Html`
|
||||||
handler is the same buffered-route mismatch as any other `@Get`/`@Post`/`@Put`/`@Patch`/`@Delete`
|
handler is the same buffered-route mismatch as any other `@Get`/`@Head`/`@Post`/`@Put`/`@Patch`/`@Delete`/`@Options`
|
||||||
handler: a 500 `TransportMismatchError`, not a silent raw stream.
|
handler: a 500 `TransportMismatchError`, not a silent raw stream.
|
||||||
:::
|
:::
|
||||||
|
|
||||||
@@ -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
|
||||||
|
|
||||||
@@ -145,7 +145,7 @@ Like the file/template modes of `@Html`, `static` needs a filesystem: it's Node/
|
|||||||
@Html
|
@Html
|
||||||
ticks() { /* ... */ }
|
ticks() { /* ... */ }
|
||||||
// throws at createApp(): "@Html on GET /ticks is not allowed —
|
// throws at createApp(): "@Html on GET /ticks is not allowed —
|
||||||
// @Html only supports buffered GET/POST routes (not SSE/WS/PUT/PATCH/DELETE)"
|
// @Html only supports buffered GET/POST routes (not SSE/WS/HEAD/PUT/PATCH/DELETE/OPTIONS)"
|
||||||
```
|
```
|
||||||
|
|
||||||
`@Html` and `@Transformer` also can't be combined on the same handler — pick one:
|
`@Html` and `@Transformer` also can't be combined on the same handler — pick one:
|
||||||
|
|||||||
@@ -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.
|
||||||
|
|
||||||
@@ -94,17 +94,17 @@ Mesh proxies **buffered** endpoints. `@Sse`, `@Stream` and `@Ws` routes are not
|
|||||||
|
|
||||||
## One teapot per route
|
## One teapot per route
|
||||||
|
|
||||||
A route must be exported by exactly **one** teapot. If two export the same `method + pattern`, the boot **fails**, naming the route and both teapots:
|
A route must be exported by exactly **one** teapot. If two export the same method and effective match shape — including patterns that differ only by parameter name, such as `/:id` and `/:name` — boot **fails**, naming both patterns and both teapots:
|
||||||
|
|
||||||
```
|
```
|
||||||
mesh: route 'GET /api/svc/ping' is exported by more than one teapot
|
mesh: ambiguous remote route 'GET /api/shape/:name' from ws://b/__mesh__/control
|
||||||
(ws://a/__mesh__/control and ws://b/__mesh__/control) — load balancing across
|
conflicts with 'GET /api/shape/:id' from ws://a/__mesh__/control — load balancing
|
||||||
teapots is not implemented yet, so green-tea will not choose one for you.
|
across teapots is not implemented yet, so green-tea will not choose one for you.
|
||||||
```
|
```
|
||||||
|
|
||||||
This is a hard error rather than a silent pick because there is no load balancing to fall back on: choosing one would be an arbitrary answer you could come to depend on. Scope tokens (`@Provider`/`@Step`) are unique for the same reason — and balancing them would be meaningless anyway, since an app-scope export is resolved once and cached.
|
This is a hard error rather than a silent pick because there is no load balancing to fall back on: choosing one would be an arbitrary answer you could come to depend on. Scope tokens (`@Provider`/`@Step`) are unique for the same reason — and balancing them would be meaningless anyway, since an app-scope export is resolved once and cached.
|
||||||
|
|
||||||
**Local routes win.** If you declare a route locally *and* import it from a teapot, yours takes precedence — that is how you override a teapot — and green-tea warns so a shadowed export doesn't look like a broken one:
|
**Local routes win.** If you declare a route locally *and* import the same effective method/shape from a teapot, yours takes precedence — that is how you override a teapot — and green-tea warns so a shadowed export doesn't look like a broken one:
|
||||||
|
|
||||||
```
|
```
|
||||||
[green-tea] mesh: route 'GET /api/svc/ping' is exported by teapot ws://a/… but also
|
[green-tea] mesh: route 'GET /api/svc/ping' is exported by teapot ws://a/… but also
|
||||||
|
|||||||
@@ -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()`
|
||||||
|
|
||||||
@@ -15,14 +15,16 @@ const spec = app.openapi({ title: 'My API', version: '1.0.0' });
|
|||||||
|
|
||||||
It reads the routes and handler signatures and produces, for each route:
|
It reads the routes and handler signatures and produces, for each route:
|
||||||
|
|
||||||
- the **path**, templated — `/users/:id` → `/users/{id}`, catch-all `:path*` → `{path}`;
|
- the **path**, templated — `/users/:id` → `/users/{id}`, constrained `:id(\d+)` → `{id}`, catch-all `:path*` → `{path}`;
|
||||||
- the **method**;
|
- the **explicitly declared method**, including `@Head` and `@Options`;
|
||||||
- **parameters** — path params from the pattern, plus query/header params from the handler's `@query` / `@headers` / `@header` decorators;
|
- **parameters** — path params from the pattern, plus query/header params from the handler's `@query` / `@headers` / `@header` decorators;
|
||||||
- a **request body** entry for routes that read `@body()`;
|
- a **request body** entry for routes that read `@body()`;
|
||||||
- the systematic **responses** — `200`, a `422` when any argument is schema-validated, and `500`.
|
- the systematic **responses** — `200`, a `422` when any argument is schema-validated, and `500`.
|
||||||
|
|
||||||
WebSocket routes are omitted (they aren't request/response).
|
WebSocket routes are omitted (they aren't request/response).
|
||||||
|
|
||||||
|
A constrained path parameter remains a string parameter and carries its route expression as `schema.pattern`. Only declared operations appear: implicit HEAD and automatic OPTIONS fallbacks are runtime conveniences and are not invented in the OpenAPI document.
|
||||||
|
|
||||||
## Serve it — `devOpenapi`
|
## Serve it — `devOpenapi`
|
||||||
|
|
||||||
Opt in to a `GET /__openapi__` endpoint that returns the document as JSON — point Swagger UI, Redoc, or a codegen client at it:
|
Opt in to a `GET /__openapi__` endpoint that returns the document as JSON — point Swagger UI, Redoc, or a codegen client at it:
|
||||||
@@ -36,6 +38,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/).
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
title: Routing
|
title: Routing
|
||||||
description: "Route patterns, the catch-all, specificity precedence, and 405 handling."
|
description: "Route constraints, specificity, HEAD and OPTIONS semantics, and path validation."
|
||||||
---
|
---
|
||||||
|
|
||||||
Routes are declared with method decorators on a `@Route`-prefixed controller. Patterns are matched **by segment**.
|
Routes are declared with method decorators on a `@Route`-prefixed controller. Patterns are matched **by segment**.
|
||||||
@@ -9,7 +9,7 @@ Routes are declared with method decorators on a `@Route`-prefixed controller. Pa
|
|||||||
|
|
||||||
| Decorator | Method / transport |
|
| Decorator | Method / transport |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `@Get` `@Post` `@Put` `@Patch` `@Delete` | buffered HTTP response |
|
| `@Get` `@Head` `@Post` `@Put` `@Patch` `@Delete` `@Options` | buffered HTTP response |
|
||||||
| `@Sse` | server-sent events (`text/event-stream`) |
|
| `@Sse` | server-sent events (`text/event-stream`) |
|
||||||
| `@Ws` | WebSocket duplex |
|
| `@Ws` | WebSocket duplex |
|
||||||
| `@Stream` | negotiated — SSE / ndjson / WS, picked from the client's `Accept` / `Upgrade` |
|
| `@Stream` | negotiated — SSE / ndjson / WS, picked from the client's `Accept` / `Upgrade` |
|
||||||
@@ -28,37 +28,47 @@ The path a route matches is `joinPath(module.mountpoint, route.path)` — a cont
|
|||||||
|
|
||||||
- **Static** — `users` matches exactly.
|
- **Static** — `users` matches exactly.
|
||||||
- **`:param`** — matches exactly one segment; the decoded value lands in `params.name` (`@param('id')`).
|
- **`:param`** — matches exactly one segment; the decoded value lands in `params.name` (`@param('id')`).
|
||||||
|
- **`:param(constraint)`** — matches one complete decoded segment when it satisfies a safe regex subset, for example `:id(\d+)`.
|
||||||
- **`:name*` catch-all** — a trailing segment that captures the **rest of the path, slashes included**, into `params.name`.
|
- **`:name*` catch-all** — a trailing segment that captures the **rest of the path, slashes included**, into `params.name`.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
|
@Get('/users/:id(\\d+)') // /users/42 matches; /users/alice does not
|
||||||
@Get('/files/:path*') // /files/img/2026/logo.png → params.path = "img/2026/logo.png"
|
@Get('/files/:path*') // /files/img/2026/logo.png → params.path = "img/2026/logo.png"
|
||||||
```
|
```
|
||||||
|
|
||||||
A catch-all also matches zero remaining segments (`/files` → `params.path = ""`).
|
A catch-all also matches zero remaining segments (`/files` → `params.path = ""`).
|
||||||
|
|
||||||
|
Constraints are anchored to the whole segment automatically. They allow character classes, alphanumeric/literal atoms, the escaped character classes `\d`, `\D`, `\s`, `\S`, `\w`, `\W`, and simple quantifiers (`+`, `*`, `?`, `{n}`, `{n,m}`). Groups, alternation, lookarounds, backreferences, anchors, and other arbitrary regex features are rejected at boot. Expressions are limited to 128 characters, counted quantifiers are capped, and unsafe adjacent unbounded quantifiers are rejected. This deliberately small subset avoids accepting route regexes with obvious ReDoS shapes.
|
||||||
|
|
||||||
|
Patterns must start with `/`, parameter names must be unique and use identifier syntax, and a catch-all must be the final segment. Repeated slashes in a declared pattern fail at boot.
|
||||||
|
|
||||||
## Precedence
|
## Precedence
|
||||||
|
|
||||||
When more than one route matches the same path, the **most specific wins** — `static ▸ :param ▸ catch-all` — compared segment by segment, **independent of registration order**. Genuine ties (two equally-specific patterns) fall back to registration order.
|
When more than one route matches the same path, the **most specific wins** — `static ▸ constrained :param ▸ plain :param ▸ catch-all` — compared segment by segment, independent of registration order.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
@Get('/a/b') // wins for /a/b
|
@Get('/a/b') // wins for /a/b
|
||||||
|
@Get('/a/:id(\\d+)') // wins for /a/42 over the plain parameter
|
||||||
@Get('/a/:id') // wins for /a/x
|
@Get('/a/:id') // wins for /a/x
|
||||||
@Get('/a/:rest*') // wins for /a/x/y
|
@Get('/a/:rest*') // wins for /a/x/y
|
||||||
```
|
```
|
||||||
|
|
||||||
## 404 vs 405
|
Two routes under the same method cannot have the same effective shape: `/users/:id` and `/users/:name` are ambiguous and make boot fail with both declarations named. The same rule applies after mesh routes join. Different methods may reuse a shape.
|
||||||
|
|
||||||
|
## HEAD and OPTIONS
|
||||||
|
|
||||||
|
An explicit `@Head` or `@Options` route always wins. Without an explicit HEAD route, HEAD falls back to a matching **buffered** GET handler, preserves its status and headers, and suppresses the body. Streaming GET routes do not become implicit HEAD routes.
|
||||||
|
|
||||||
|
Without an explicit OPTIONS route, OPTIONS on an existing path returns `204` with a canonical `Allow` header. GET implies HEAD, and any existing path implies OPTIONS, so a GET/POST path reports `GET, HEAD, POST, OPTIONS`. A CORS preflight (OPTIONS with `Access-Control-Request-Method`) is handled before explicit or automatic OPTIONS when CORS is configured.
|
||||||
|
|
||||||
|
## Path policy and 404 vs 405
|
||||||
|
|
||||||
|
`/path` and `/path/` are equivalent. Repeated slashes such as `/path//item` are rejected rather than collapsed, and malformed percent encoding is rejected; both return `400 Bad Request` with the configured security/CORS headers. Query strings do not participate in route matching.
|
||||||
|
|
||||||
A path that no route matches returns `404`. A path that **does** exist but under a different method returns **`405 Method Not Allowed`** with an `Allow` header listing the methods that do match — not a `404`.
|
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
|
## Matcher scale
|
||||||
A bare `OPTIONS` request (without an `Access-Control-Request-Method` header — i.e. not a CORS preflight) to an existing path therefore returns `405` with `Allow`. CORS preflights are handled separately; see [Transport security](/guides/security/).
|
|
||||||
:::
|
|
||||||
|
|
||||||
## Not yet
|
Route matching remains a **linear scan** — fine for typical route tables. A radix-tree matcher for very large route tables remains on the roadmap.
|
||||||
|
|
||||||
The matcher is intentionally small for beta. **Not built** (on the roadmap):
|
See [Streaming & real-time](/docs/guides/streaming/) for `@Sse` / `@Ws` / `@Stream`, and [Argument decorators](/docs/guides/arguments/) for everything a handler can read from a request.
|
||||||
|
|
||||||
- Regex / typed param constraints such as `:id(\d+)`.
|
|
||||||
- Route matching is a **linear scan** — fine for typical route tables, but a radix-tree matcher for very large ones isn't implemented.
|
|
||||||
|
|
||||||
See [Streaming & real-time](/guides/streaming/) for `@Sse` / `@Ws` / `@Stream`, and [Argument decorators](/guides/arguments/) for everything a handler can read from a request.
|
|
||||||
@@ -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)
|
||||||
@@ -44,7 +44,9 @@ const app = createApp({
|
|||||||
```
|
```
|
||||||
|
|
||||||
`origins` accepts `string | string[] | '*' | (origin) => boolean`. A preflight `OPTIONS`
|
`origins` accepts `string | string[] | '*' | (origin) => boolean`. A preflight `OPTIONS`
|
||||||
request (with `Access-Control-Request-Method`) is auto-answered with 204.
|
request (with `Access-Control-Request-Method`) is auto-answered with 204 before explicit or
|
||||||
|
automatic OPTIONS routing. A bare OPTIONS request is instead handled by an explicit `@Options`
|
||||||
|
route or the router's automatic `204` + `Allow` response.
|
||||||
|
|
||||||
- With `credentials: true`, the server **never** sends `Access-Control-Allow-Origin: *` — it
|
- With `credentials: true`, the server **never** sends `Access-Control-Allow-Origin: *` — it
|
||||||
echoes the concrete allowed origin (or blocks the request).
|
echoes the concrete allowed origin (or blocks the request).
|
||||||
@@ -97,5 +99,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
|
||||||
|
|
||||||
@@ -110,7 +109,7 @@ A route streams **because** it's declared `@Sse`, `@Stream`, or `@Ws` — never
|
|||||||
|
|
||||||
| Declare | Handler must return | Otherwise |
|
| Declare | Handler must return | Otherwise |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `@Get` / `@Post` / `@Put` / `@Patch` / `@Delete` (buffered) | a value | returning an `AsyncIterable` fails with a 500 `TransportMismatchError` |
|
| `@Get` / `@Head` / `@Post` / `@Put` / `@Patch` / `@Delete` / `@Options` (buffered) | a value | returning an `AsyncIterable` fails with a 500 `TransportMismatchError` |
|
||||||
| `@Sse` / `@Ws` (streaming) | an `AsyncIterable` | returning a plain value fails with a 500 `TransportMismatchError` |
|
| `@Sse` / `@Ws` (streaming) | an `AsyncIterable` | returning a plain value fails with a 500 `TransportMismatchError` |
|
||||||
| `@Stream` (negotiate) | either | the client picks via `Accept` / `Upgrade` — no mismatch |
|
| `@Stream` (negotiate) | either | the client picks via `Accept` / `Upgrade` — no mismatch |
|
||||||
|
|
||||||
|
|||||||
@@ -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,22 +12,23 @@ 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`) |
|
||||||
|
| `warnGraphDepth` | `number \| false` | `20` | warn when one route resolves to more than this many steps; `false` disables the design warning |
|
||||||
|
|
||||||
### `RequestLimits`
|
### `RequestLimits`
|
||||||
|
|
||||||
@@ -53,7 +54,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`
|
||||||
|
|
||||||
@@ -63,14 +64,17 @@ const app = createApp(options);
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `listen(port)` | `Promise<http.Server>` | boots providers, then serves |
|
| `listen(port)` | `Promise<http.Server>` | boots providers, then serves |
|
||||||
| `close()` | `Promise<void>` | drains in-flight, closes streams + mesh links |
|
| `close()` | `Promise<void>` | drains in-flight, closes streams + mesh links |
|
||||||
|
| `ready()` | `Promise<void>` | resolves the graph and mesh links without booting providers |
|
||||||
|
| `fetch(request)` | `Promise<Response>` | Web-Standards HTTP/SSE handler for Node, Deno, Bun, and edge |
|
||||||
|
| `upgrade(request, socket)` | `Promise<void>` | neutral WebSocket upgrade used by non-Node adapters |
|
||||||
| `inspect(route)` | `InspectLine[]` | the provider/step/handler chain for a route |
|
| `inspect(route)` | `InspectLine[]` | the provider/step/handler chain for a route |
|
||||||
| `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 providers boot through `fetch`, `upgrade`, or `listen`) |
|
||||||
| `bus` | `Bus` | lifecycle + request event bus |
|
| `bus` | `Bus` | lifecycle + request event bus |
|
||||||
|
|
||||||
:::note
|
:::note
|
||||||
On mesh apps, `graph` / `explain` / `inspect` / `degraded` are only available **after** `listen()` — the graph is finalized once remote scopes connect.
|
On mesh apps, `graph` / `explain` / `inspect` / `degraded` are only available after `ready()` or the first serving call — the graph is finalized once remote scopes connect.
|
||||||
:::
|
:::
|
||||||
@@ -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,23 +48,23 @@ 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 |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `@Get` `@Post` `@Put` `@Patch` `@Delete` | as named | buffered response |
|
| `@Get` `@Head` `@Post` `@Put` `@Patch` `@Delete` `@Options` | as named | buffered response |
|
||||||
| `@Sse` | GET | `text/event-stream` |
|
| `@Sse` | GET | `text/event-stream` |
|
||||||
| `@Ws` | GET | WebSocket duplex |
|
| `@Ws` | GET | WebSocket duplex |
|
||||||
| `@Stream` | GET | negotiated (SSE / ndjson / WS) |
|
| `@Stream` | GET | negotiated (SSE / ndjson / WS) |
|
||||||
@@ -75,7 +75,9 @@ 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.
|
||||||
|
|
||||||
|
`@Head` and `@Options` declare explicit handlers. When they are absent, the router can provide an implicit buffered-GET HEAD response or an automatic `204` OPTIONS response; those fallbacks are runtime behavior, not decorator metadata.
|
||||||
|
|
||||||
## Arguments
|
## Arguments
|
||||||
|
|
||||||
@@ -93,4 +95,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