chore: move the documentation site out to its own repository

website/ is now github.com/Expressive-Tea/green-tea-docs, carrying its own
history — 31 commits, extracted with `git subtree split`, not squashed into
an import that pretends the pages appeared all at once.

What this repository gives up is real and worth naming: the site had no
deploy pipeline at all, and CI here was the only thing proving it still
built. That is why the new repository got a build gate and a tagged release
before this deletion landed, rather than after.

Removed with it: the three website steps in ci.yml (including the second
setup-node that re-pinned 22.12 purely for the docs build — the core job
stays on 18, the minimum supported version), the two package.json scripts,
and the .astro/ and website/dist/ ignore rules that now belong over there.

SECURITY.md pointed at `website/` as an out-of-scope path; it now points at
the repository, since the path no longer exists to be out of scope.

The split trades a CI coupling for a drift risk — nothing fails now when
the docs and the API disagree. Both READMEs state the rule that replaces
the build: a change to public API updates the page documenting it. That is
the weakest of the options considered, and it is written down rather than
assumed.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-08-17 10:05:04 -05:00
1 parent a4bb3c02d6
commit 101c4fe65a
37 files changed
+3 -9153

No files matched your search

-7
View File
@@ -56,13 +56,6 @@ jobs:
- run: npm audit --omit=dev
- run: npm audit
continue-on-error: true
- uses: actions/setup-node@v4
with:
node-version: '22.12'
- run: npm ci --prefix website
- run: npm audit --prefix website
continue-on-error: true
- run: npm run docs:build
# Runs everywhere is the headline claim, so it gets tested rather than asserted. `npm test` is
# Node only: a change to shared code can pass it and still be broken on Deno or Bun, which is
-3
View File
@@ -11,9 +11,6 @@ coverage/
.env
.env.*
# Astro (docs site)
.astro/
website/dist/
# Edge (Miniflare) test bundle artifact
test/edge/_worker.mjs
+1 -2
View File
@@ -254,7 +254,7 @@ green-tea is **beta**, on the road to a release candidate. Express and Fastify h
## Docs & development
- **[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.
- **[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. Its source lives in [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs); a change to public API here needs a matching change there, because nothing fails when the two disagree.
- **[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
@@ -266,7 +266,6 @@ npm run test:edge # workerd via miniflare
npm run typecheck # tsc --noEmit (includes the compile-time-guarantee type test)
npm run build # emit dist/ (tsup: dual ESM + CJS)
npm run bench # regenerate BENCHMARKS.md
npm run docs:dev # the documentation site (website/)
```
## Roadmap
+2 -1
View File
@@ -57,7 +57,8 @@ In scope: anything in `src/` that ships in the published package — route match
pipeline, body parsing and its limits, the security headers and CORS handling, TLS setup, the
WebSocket upgrade path, the mesh wire protocol, static file serving and view rendering.
Out of scope: the benchmarks in `bench/`, the docs site in `website/`, dev-only tooling, and
Out of scope: the benchmarks in `bench/`, the documentation site (now its own repository,
[green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs)), dev-only tooling, and
anything that requires an attacker to already control your application code. Advisories in
build-time dependencies are worth telling us about, but they are not vulnerabilities in
green-tea and we handle them as ordinary dependency updates.
-2
View File
@@ -97,8 +97,6 @@
"lint:fix": "eslint src --fix",
"format": "prettier --write \"src/**/*.ts\"",
"format:check": "prettier --check \"src/**/*.ts\"",
"docs:dev": "npm --prefix website run dev",
"docs:build": "npm --prefix website run build",
"complexity": "ccts src",
"complexity:check": "node scripts/check-complexity.mjs",
"complexity:cyclomatic": "cyclomatic-complexity \"src/**/*.ts\" -tw 15 -te 25",
-77
View File
@@ -1,77 +0,0 @@
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';
// Docs site for @green-tea/core. Content lives in src/content/docs/**.
export default defineConfig({
site: 'https://green-tea.expressive-tea.io',
base: '/docs',
integrations: [
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.',
description: 'A zen, opinionated, type-safe framework — your API is a graph, not a chain.',
logo: { src: './src/assets/logo.svg', alt: 'Green Tea' },
favicon: '/favicon.svg',
customCss: ['./src/styles/brand.css'],
tableOfContents: { minHeadingLevel: 2, maxHeadingLevel: 3 },
sidebar: [
{
label: 'Start here',
items: [
{ label: 'Introduction', link: '/' },
{ label: 'Getting started', slug: 'getting-started' },
],
},
{
label: 'Concepts',
items: [
{ label: 'The dependency graph', slug: 'concepts/the-graph' },
{ label: 'The typed flow core', slug: 'concepts/flow' },
],
},
{
label: 'Guides',
items: [
{ label: 'The matcha CLI', slug: 'guides/cli' },
{ label: 'Routing', slug: 'guides/routing' },
{ label: 'Dependency injection', slug: 'guides/dependency-injection' },
{ label: 'Argument decorators', slug: 'guides/arguments' },
{ label: 'Validation', slug: 'guides/validation' },
{ label: 'Error handling', slug: 'guides/errors' },
{ label: 'Streaming & real-time', slug: 'guides/streaming' },
{ label: 'File uploads', slug: 'guides/uploads' },
{ label: 'HTML & views', slug: 'guides/html' },
{ label: 'Transport security', slug: 'guides/security' },
{ label: 'Plugins', slug: 'guides/plugins' },
{ label: 'Observability', slug: 'guides/observability' },
{ label: 'Graph introspection', slug: 'guides/introspection' },
{ label: 'OpenAPI', slug: 'guides/openapi' },
{ label: 'Runtimes', slug: 'guides/runtimes' },
{ label: 'Testing', slug: 'guides/testing' },
{ label: 'Mesh (alpha)', slug: 'guides/mesh', badge: { text: 'alpha', variant: 'caution' } },
],
},
{
label: 'Reference',
items: [
{ label: 'Decorators', slug: 'reference/decorators' },
{ label: 'createApp options', slug: 'reference/createapp' },
],
},
],
}),
],
});
-6853
View File
File diff suppressed because it is too large. Load diff
-15
View File
@@ -1,15 +0,0 @@
{
"name": "green-tea-docs",
"type": "module",
"private": true,
"scripts": {
"dev": "astro dev",
"build": "astro build",
"preview": "astro preview"
},
"dependencies": {
"@astrojs/starlight": "^0.41.6",
"astro": "^7.1.6",
"sharp": "^0.35.3"
}
}
-16
View File
@@ -1,16 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 611 620" fill="none">
<path d="M0 0 C6.4 4.22 7.06 11.7 8.6 18.74 C9.17 21.55 9.71 24.37 10.23 27.2 C10.43 28.25 10.63 29.3 10.84 30.39 C11.48 33.82 12.12 37.25 12.75 40.69 C12.86 41.28 12.86 41.28 13.41 44.27 C19.74 78.61 25.24 113.17 28 148 C28.1 149.25 28.2 150.5 28.31 151.78 C33.71 219.69 29.07 297.74 -17 352 C-37.58 376.04 -63.34 393.66 -92.79 405.14 C-94.83 405.93 -96.85 406.75 -98.87 407.58 C-119.07 415.67 -140.54 420.66 -162 424 C-163.26 424.2 -164.52 424.4 -165.82 424.6 C-213.88 431.88 -265.63 431.11 -313 420 C-313.8 419.81 -314.6 419.63 -315.42 419.43 C-321.96 417.87 -328.02 416.17 -334 413 C-333.4 408.16 -331.32 404.45 -329 400.25 C-328.63 399.57 -328.26 398.88 -327.88 398.18 C-325.16 393.16 -325.16 393.16 -324 392 C-316.45 391.5 -309.28 393.04 -301.88 394.38 C-266.77 400.41 -230.41 401.2 -195 397 C-193.89 396.88 -192.78 396.75 -191.63 396.63 C-143.03 391.12 -90.07 376.55 -53 343 C-52.13 342.26 -51.26 341.53 -50.37 340.77 C-13.69 309.26 -0.6 260.49 3 214 C6.89 162.68 1.22 110.21 -9.66 60.01 C-10 58 -10 58 -10 54 C-10.66 54 -11.32 54 -12 54 C-12.08 54.65 -12.16 55.3 -12.24 55.98 C-13.28 60.13 -15.18 63.61 -17.19 67.38 C-17.63 68.2 -18.06 69.02 -18.51 69.87 C-27.46 86.43 -37.3 102.24 -49 117 C-49.73 117.94 -50.46 118.88 -51.21 119.85 C-55.22 124.97 -59.47 129.83 -63.85 134.63 C-65.75 136.73 -67.6 138.85 -69.44 141 C-76.06 148.56 -83.19 155.34 -91.04 161.6 C-93.13 163.29 -95.16 165 -97.18 166.77 C-122.17 188.79 -151.25 205.29 -180.04 221.76 C-192.95 229.14 -205.58 236.83 -218 245 C-218.85 245.56 -219.7 246.12 -220.58 246.7 C-229.87 252.82 -238.77 259.13 -247.12 266.49 C-249.7 268.74 -252.35 270.84 -255.06 272.94 C-267.05 282.7 -278.61 294.17 -288.03 306.45 C-289.89 308.86 -291.81 311.22 -293.74 313.57 C-298.14 319.07 -302.07 324.81 -305.94 330.69 C-306.64 331.75 -307.34 332.82 -308.07 333.91 C-310.06 336.94 -312.03 339.97 -314 343 C-314.45 343.69 -314.9 344.38 -315.36 345.1 C-333.78 373.72 -347.37 405.97 -360.01 437.47 C-367.19 455.23 -367.19 455.23 -373 459 C-381.02 461.67 -388.52 459.36 -396 456 C-400.94 452.9 -406.06 449.11 -409 444 C-409.81 440.26 -409.56 438.01 -407.71 434.64 C-404.3 429.62 -400.39 425.15 -396.3 420.68 C-391.69 415.32 -387.56 409.58 -383.38 403.88 C-382.15 402.21 -380.9 400.55 -379.64 398.89 C-379 398.02 -378.35 397.15 -377.69 396.25 C-377.13 395.51 -376.58 394.78 -376.01 394.02 C-375 392 -375 392 -375.3 390.07 C-376.44 386.69 -378.78 384.1 -380.94 381.31 C-403.08 351.79 -416.04 315.59 -420 279 C-420.11 278.07 -420.22 277.14 -420.34 276.18 C-425.19 227.03 -413.92 174.12 -382.44 135.12 C-380.97 133.41 -379.49 131.7 -378 130 C-377.28 129.17 -376.56 128.34 -375.82 127.49 C-358.11 107.42 -337.64 91.46 -314 79 C-313.38 78.67 -312.76 78.33 -312.12 77.99 C-300.18 71.58 -287.7 66.68 -275 62 C-274.14 61.68 -273.29 61.36 -272.4 61.03 C-234.24 47.03 -193.39 42.56 -153.28 37.74 C-131.4 35.11 -109.62 32.33 -88 28 C-87.42 27.89 -87.42 27.89 -84.51 27.32 C-61.65 22.81 -40.27 14.77 -19.21 4.91 C-6.48 -0.98 -6.48 -0.98 0 0 Z M-36.19 37.49 C-71.76 55.45 -113.52 58.93 -152.55 63.46 C-196.61 68.6 -196.61 68.6 -216 73 C-217 73.22 -218 73.43 -219.03 73.65 C-264.38 83.45 -306.87 101.06 -341 133 C-341.95 133.88 -342.9 134.77 -343.88 135.68 C-373.91 164.27 -390.12 205.53 -391.38 246.65 C-392.35 288.29 -383.46 327.6 -361 363 C-358.84 360.25 -357.1 357.49 -355.47 354.39 C-354.99 353.5 -354.52 352.61 -354.03 351.69 C-353.78 351.21 -353.78 351.21 -352.5 348.81 C-342.16 329.63 -330.05 311.66 -316 295 C-315.08 293.89 -314.16 292.78 -313.24 291.68 C-308.88 286.45 -304.51 281.32 -299.6 276.6 C-297.85 274.85 -296.28 273.01 -294.69 271.12 C-278.78 252.73 -256.54 237.48 -235.78 225.07 C-233.06 223.44 -230.38 221.74 -227.69 220.06 C-219.23 214.87 -210.61 209.95 -202 205 C-193.33 200.01 -184.66 195.01 -176 190 C-174.99 189.42 -173.99 188.84 -172.95 188.24 C-161.6 181.67 -150.51 174.92 -139.83 167.3 C-137.99 165.99 -136.14 164.7 -134.29 163.41 C-123.48 155.83 -113.46 147.55 -103.79 138.57 C-101.47 136.44 -99.13 134.36 -96.75 132.31 C-89.94 126.39 -83.79 119.91 -78 113 C-77.55 112.46 -77.1 111.93 -76.64 111.38 C-57.15 88.05 -39.86 63.1 -28 35 C-31.34 35 -33.25 36 -36.19 37.49 Z " fill="#5FB88A" transform="translate(501,80)"/>
<g stroke="#5FB88A" stroke-width="12" stroke-linecap="round" fill="none">
<path d="M277 312 Q255 263 221 247"/>
<path d="M338 276 Q382 305 393 340"/>
<path d="M366 258 Q348 214 317 200"/>
<path d="M443 186 Q469 204 475 224"/>
</g>
<g fill="#5FB88A">
<circle cx="221" cy="247" r="13"/>
<circle cx="393" cy="340" r="13"/>
<circle cx="475" cy="224" r="11"/>
</g>
<circle cx="317" cy="200" r="18" fill="#7C6CF0"/>
</svg>

Before

Width:  |  Height:  |  Size: 4.6 KiB

-16
View File
@@ -1,16 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 611 620" fill="none">
<path d="M0 0 C6.4 4.22 7.06 11.7 8.6 18.74 C9.17 21.55 9.71 24.37 10.23 27.2 C10.43 28.25 10.63 29.3 10.84 30.39 C11.48 33.82 12.12 37.25 12.75 40.69 C12.86 41.28 12.86 41.28 13.41 44.27 C19.74 78.61 25.24 113.17 28 148 C28.1 149.25 28.2 150.5 28.31 151.78 C33.71 219.69 29.07 297.74 -17 352 C-37.58 376.04 -63.34 393.66 -92.79 405.14 C-94.83 405.93 -96.85 406.75 -98.87 407.58 C-119.07 415.67 -140.54 420.66 -162 424 C-163.26 424.2 -164.52 424.4 -165.82 424.6 C-213.88 431.88 -265.63 431.11 -313 420 C-313.8 419.81 -314.6 419.63 -315.42 419.43 C-321.96 417.87 -328.02 416.17 -334 413 C-333.4 408.16 -331.32 404.45 -329 400.25 C-328.63 399.57 -328.26 398.88 -327.88 398.18 C-325.16 393.16 -325.16 393.16 -324 392 C-316.45 391.5 -309.28 393.04 -301.88 394.38 C-266.77 400.41 -230.41 401.2 -195 397 C-193.89 396.88 -192.78 396.75 -191.63 396.63 C-143.03 391.12 -90.07 376.55 -53 343 C-52.13 342.26 -51.26 341.53 -50.37 340.77 C-13.69 309.26 -0.6 260.49 3 214 C6.89 162.68 1.22 110.21 -9.66 60.01 C-10 58 -10 58 -10 54 C-10.66 54 -11.32 54 -12 54 C-12.08 54.65 -12.16 55.3 -12.24 55.98 C-13.28 60.13 -15.18 63.61 -17.19 67.38 C-17.63 68.2 -18.06 69.02 -18.51 69.87 C-27.46 86.43 -37.3 102.24 -49 117 C-49.73 117.94 -50.46 118.88 -51.21 119.85 C-55.22 124.97 -59.47 129.83 -63.85 134.63 C-65.75 136.73 -67.6 138.85 -69.44 141 C-76.06 148.56 -83.19 155.34 -91.04 161.6 C-93.13 163.29 -95.16 165 -97.18 166.77 C-122.17 188.79 -151.25 205.29 -180.04 221.76 C-192.95 229.14 -205.58 236.83 -218 245 C-218.85 245.56 -219.7 246.12 -220.58 246.7 C-229.87 252.82 -238.77 259.13 -247.12 266.49 C-249.7 268.74 -252.35 270.84 -255.06 272.94 C-267.05 282.7 -278.61 294.17 -288.03 306.45 C-289.89 308.86 -291.81 311.22 -293.74 313.57 C-298.14 319.07 -302.07 324.81 -305.94 330.69 C-306.64 331.75 -307.34 332.82 -308.07 333.91 C-310.06 336.94 -312.03 339.97 -314 343 C-314.45 343.69 -314.9 344.38 -315.36 345.1 C-333.78 373.72 -347.37 405.97 -360.01 437.47 C-367.19 455.23 -367.19 455.23 -373 459 C-381.02 461.67 -388.52 459.36 -396 456 C-400.94 452.9 -406.06 449.11 -409 444 C-409.81 440.26 -409.56 438.01 -407.71 434.64 C-404.3 429.62 -400.39 425.15 -396.3 420.68 C-391.69 415.32 -387.56 409.58 -383.38 403.88 C-382.15 402.21 -380.9 400.55 -379.64 398.89 C-379 398.02 -378.35 397.15 -377.69 396.25 C-377.13 395.51 -376.58 394.78 -376.01 394.02 C-375 392 -375 392 -375.3 390.07 C-376.44 386.69 -378.78 384.1 -380.94 381.31 C-403.08 351.79 -416.04 315.59 -420 279 C-420.11 278.07 -420.22 277.14 -420.34 276.18 C-425.19 227.03 -413.92 174.12 -382.44 135.12 C-380.97 133.41 -379.49 131.7 -378 130 C-377.28 129.17 -376.56 128.34 -375.82 127.49 C-358.11 107.42 -337.64 91.46 -314 79 C-313.38 78.67 -312.76 78.33 -312.12 77.99 C-300.18 71.58 -287.7 66.68 -275 62 C-274.14 61.68 -273.29 61.36 -272.4 61.03 C-234.24 47.03 -193.39 42.56 -153.28 37.74 C-131.4 35.11 -109.62 32.33 -88 28 C-87.42 27.89 -87.42 27.89 -84.51 27.32 C-61.65 22.81 -40.27 14.77 -19.21 4.91 C-6.48 -0.98 -6.48 -0.98 0 0 Z M-36.19 37.49 C-71.76 55.45 -113.52 58.93 -152.55 63.46 C-196.61 68.6 -196.61 68.6 -216 73 C-217 73.22 -218 73.43 -219.03 73.65 C-264.38 83.45 -306.87 101.06 -341 133 C-341.95 133.88 -342.9 134.77 -343.88 135.68 C-373.91 164.27 -390.12 205.53 -391.38 246.65 C-392.35 288.29 -383.46 327.6 -361 363 C-358.84 360.25 -357.1 357.49 -355.47 354.39 C-354.99 353.5 -354.52 352.61 -354.03 351.69 C-353.78 351.21 -353.78 351.21 -352.5 348.81 C-342.16 329.63 -330.05 311.66 -316 295 C-315.08 293.89 -314.16 292.78 -313.24 291.68 C-308.88 286.45 -304.51 281.32 -299.6 276.6 C-297.85 274.85 -296.28 273.01 -294.69 271.12 C-278.78 252.73 -256.54 237.48 -235.78 225.07 C-233.06 223.44 -230.38 221.74 -227.69 220.06 C-219.23 214.87 -210.61 209.95 -202 205 C-193.33 200.01 -184.66 195.01 -176 190 C-174.99 189.42 -173.99 188.84 -172.95 188.24 C-161.6 181.67 -150.51 174.92 -139.83 167.3 C-137.99 165.99 -136.14 164.7 -134.29 163.41 C-123.48 155.83 -113.46 147.55 -103.79 138.57 C-101.47 136.44 -99.13 134.36 -96.75 132.31 C-89.94 126.39 -83.79 119.91 -78 113 C-77.55 112.46 -77.1 111.93 -76.64 111.38 C-57.15 88.05 -39.86 63.1 -28 35 C-31.34 35 -33.25 36 -36.19 37.49 Z " fill="#5FB88A" transform="translate(501,80)"/>
<g stroke="#5FB88A" stroke-width="12" stroke-linecap="round" fill="none">
<path d="M277 312 Q255 263 221 247"/>
<path d="M338 276 Q382 305 393 340"/>
<path d="M366 258 Q348 214 317 200"/>
<path d="M443 186 Q469 204 475 224"/>
</g>
<g fill="#5FB88A">
<circle cx="221" cy="247" r="13"/>
<circle cx="393" cy="340" r="13"/>
<circle cx="475" cy="224" r="11"/>
</g>
<circle cx="317" cy="200" r="18" fill="#7C6CF0"/>
</svg>

Before

Width:  |  Height:  |  Size: 4.6 KiB

-7
View File
@@ -1,7 +0,0 @@
import { defineCollection } from 'astro:content';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';
export const collections = {
docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
};
-11
View File
@@ -1,11 +0,0 @@
---
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
---
-24
View File
@@ -1,24 +0,0 @@
---
title: The typed flow core
description: "The functional flow API where the compile-time dependency guarantee lives."
---
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
import { flow } from '@green-tea/core';
const pipeline = flow()
.step('db', () => ({ find: (id: string) => id }))
.step('user', (ctx) => ctx.db.find('u1')); // referencing a missing 'db' would not compile
```
Each `.step(name, fn)` adds its output to the accumulated context **type** (`Acc & Out`). The next step's `ctx` is typed with everything produced so far — so reading `ctx.db` compiles only because a previous step provided `db`. Reference a key nothing produced and it is a **compile error**, not a runtime `undefined`.
This is the strongest guarantee green-tea offers: the type *is* the dependency contract, checked statically. The decorator layer gives you the same graph with boot-time validation and the ergonomics of classes and decorators; `flow` gives you compile-time proof.
:::note
`npm run typecheck` in the repo includes a type-level test that asserts this accumulation behaves — a step that reads a missing key is expected to fail compilation.
:::
See [The dependency graph](/docs/concepts/the-graph/) for how both layers describe the same model.
@@ -1,47 +0,0 @@
---
title: The dependency graph
description: "How green-tea models the request and boot pipeline as an explicit dependency graph."
---
Most frameworks make you keep the whole request in your head: which middleware ran, whether `req.user` exists by now, what order things fire in, which plugin quietly deleted your body parser. That bookkeeping is where bugs live.
green-tea puts the request **on the page**. You declare what each unit **needs** and **produces**; the framework computes the order, checks the wiring, and can print the whole thing.
## needs / provides
Every node declares its inputs and outputs:
- A **provider** produces an app-scope value (a database handle, a config object) — resolved once at boot and cached.
- A **step** reads the request context and merges new keys into it (authentication producing `user`, say) — runs per request.
- A **handler** (a route method) declares, through its argument decorators, exactly which keys it depends on.
green-tea builds a directed graph from these declarations and **topologically sorts** it. You never write "put this before that" — order is derived from `needs`/`provides`.
```typescript
@Step({ provides: 'user', needs: ['db', 'req'] }) // user depends on db and req
class Authenticate { /* ... */ }
```
## Why it matters
- **No ordering bugs.** There's no positional `app.use()` sequence to get wrong; the sort is the order.
- **Each route runs only its slice.** A route runs the transitive closure of what its handler `@needs` (plus always-run observer steps) — an auth step doesn't run on a public route.
- **Boot fails loudly.** If a handler needs a key nothing provides, `createApp` throws at boot with a "did you mean…?" hint — you never serve `undefined`.
- **You can read it.** `app.explain(route)` prints the ordered chain with origins; `app.graph()` / `GET /__graph__` render it as a diagram. See [Graph introspection](/docs/guides/introspection/).
## Two layers
green-tea exposes the graph two ways:
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](/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.
## Why legacy decorators
green-tea uses **legacy** (experimental) TypeScript decorators — set `experimentalDecorators: true` in your `tsconfig`. This is a design decision, not inertia.
The argument-injection API (`@param`, `@query`, `@body`, `@header`, `@needs`, `@ctx`, `@inbound`, `@abort`) relies on **parameter decorators**, and the TC39 standard decorators proposal (Stage 3) deliberately does **not** include them. There is no standards-track way to decorate a parameter today, so `handler(@param('id') id: string)` is only expressible with legacy decorators.
"Stage 3" also means *not finalized* — the proposal can still change before engines ship it. green-tea tracks it and will revisit if parameter injection ever gets a standard path. It does **not** rely on `emitDecoratorMetadata` / `design:type` reflection — argument positions are recorded explicitly — so this is the only legacy surface it depends on.
@@ -1,95 +0,0 @@
---
title: Getting started
description: Install green-tea, configure TypeScript decorators, and build your first graph-based route.
---
## 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
npm install @green-tea/core reflect-metadata
# optional, only if you use them:
npm install ws # WebSocket routes (@Ws) and mesh
npm install busboy # multipart/form-data file uploads
```
green-tea 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
{
"compilerOptions": {
"experimentalDecorators": true,
"target": "es2020",
"moduleResolution": "node"
}
}
```
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
A provider produces a value, a step transforms the request context, and a controller handler declares exactly what it needs:
```typescript
import {
createApp, Provider, Step, Route, Get, Module,
Unauthorized, needs, param,
} from '@green-tea/core';
@Provider({ provides: 'db' })
class Database {
provide() {
const users = { u1: { id: 'u1', name: 'Diego' } };
return { db: { find: (token: string) => users[token] ?? null } };
}
}
@Step({ provides: 'user', needs: ['db', 'req'] })
class Authenticate {
run(ctx) {
const user = ctx.db.find(ctx.req.headers['x-token']);
if (!user) throw new Unauthorized('invalid token'); // cut the request
return { user }; // continue
}
}
@Route('/users')
class UserController {
@Get('/:id')
getUser(@needs('user') user, @param('id') id) { // the signature IS the contract
return { requested: id, you: user };
}
}
@Module({ mountpoint: '/api', providers: [Database], steps: [Authenticate], controllers: [UserController] })
class ApiModule {}
const app = createApp({ modules: [ApiModule] });
console.log(app.explain('/api/users/:id')); // auditable: the ordered chain, with origins
app.listen(3000);
```
```bash
curl -H 'x-token: u1' http://localhost:3000/api/users/9
# {"requested":"9","you":{"id":"u1","name":"Diego"}}
```
The handler asked for `user` via `@needs('user')`. If nothing in the graph produced `user`, `createApp` would **throw at boot** with a "did you mean…" hint — you never serve `undefined`.
## Where to next
- [The dependency graph](/docs/concepts/the-graph/) — the mental model behind everything.
- [Dependency injection](/docs/guides/dependency-injection/) — providers, steps, and modules in depth.
- [Argument decorators](/docs/guides/arguments/) — everything a handler can inject.
- [Streaming & real-time](/docs/guides/streaming/) — SSE, WebSocket, and ndjson from one primitive.
@@ -1,148 +0,0 @@
---
title: Argument decorators
description: "Everything a handler can inject with needs, ctx, param, query, body, header, inbound, and abort."
---
A handler's signature declares exactly what it wants — in any order, nothing more. Each
parameter decorator injects one thing: a graph-produced value, part of the request envelope,
or a stream handle. Some decorators add a **dependency edge** to the graph (boot-validated);
most just read from the request.
## The decorators at a glance
| Decorator | Injects | Adds a graph dependency? | Forms |
|---|---|---|---|
| `@needs('user')` | a value produced by a provider/step (boot-validated) | **yes** | `('key')` |
| `@ctx()` | the whole accumulated context | no | `()` |
| `@param(...)` | route params | no | `()` · `('id')` · `('id', schema)` |
| `@query(...)` | parsed query string | no | `()` · `('q')` · `(['a','b'])` · `(schema)` |
| `@body(...)` | parsed body (JSON / urlencoded / multipart) | no | `()` · `('field')` · `(schema)` |
| `@headers(...)` | request headers (whole bag or picked) | no | `()` · `('authorization')` · `(['a','b'])` · `(schema)` |
| `@header('name')` | one request header (singular alias of `@headers`) | no | `('x-trace')` · `('x-count', schema)` |
| `@inbound()` | the incoming WS message channel | no (WS only) | `()` |
| `@abort()` | an `AbortSignal` that fires on disconnect | no (stream/WS) | `()` |
## `@needs` — a graph-produced value
`@needs('token')` injects a value a provider or step produces, and declares a dependency edge
in the graph. Its keys are **validated at boot**: if nothing provides the token, `createApp`
throws with a clear error instead of serving `undefined`.
```typescript
getUser(@needs('user') user: any, @param('id') id: string) {
return { requested: id, you: user };
}
```
See [Dependency injection](/docs/guides/dependency-injection/) for how `needs`/`provides` build the
graph.
## `@ctx` — the whole context
`@ctx()` hands you the entire accumulated context — everything providers and steps have merged
in, plus built-ins. Use it to read values like `ctx.protocol` and `ctx.ip` (populated when
`trustProxy` is on).
## Envelope decorators — `@param`, `@query`, `@body`, `@headers`
These read from the parsed request. Each envelope decorator has **three access forms**:
- `@query()` — the whole object
- `@query('q')` — one key
- `@query(['q','date'])` — a subset
```typescript
@Get('/:id')
getUser(@param('id') id: string) { /* ... */ }
```
- **`@param`** reads route params. It always needs a name to say which param it binds
(`@param('id')`).
- **`@query`** reads the parsed query string. Query values are always strings on the wire — a
schema is often the coercion point (see below).
- **`@body`** reads the parsed body. It handles `application/json`,
`application/x-www-form-urlencoded`, and `multipart/form-data` (see the multipart note).
- **`@headers`** reads request headers — the whole bag (`@headers()`), one key
(`@headers('authorization')`), or a subset (`@headers(['a','b'])`).
## `@header` — one header, singular alias
`@header('name')` is the singular alias of `@headers`: it picks exactly one request header.
```typescript
who(@header('x-trace') trace: string) { /* ... */ }
```
It also accepts a schema in slot 2 — `@header('x-count', schema)`.
## Schema forms — validation & coercion
`@body`, `@query`, `@headers`, and `@param` accept an optional **Standard Schema** (zod,
valibot, arktype, …). The value the handler receives is the schema's **parsed/coerced output**,
already typed:
```typescript
create(@body(CreateUser) user: { email: string }) {
return { created: user.email };
}
```
:::note[Access shape (asymmetry)]
`@param('id', Schema)` takes the **key in slot 1** and the schema in slot 2 — `@param` always
needs a name to say which route param it binds. `@body(Schema)`, `@query(Schema)`, and
`@headers(Schema)` take the schema as their **only** argument, validating the whole parsed
object.
:::
A failing schema short-circuits the request with **422**. See [Validation](/docs/guides/validation/)
for the full contract (fail-fast order, error shape, async schemas, and caveats).
## Multipart access asymmetry
A request with `Content-Type: multipart/form-data` makes `@body()` resolve to `{ fields, files }`
instead of a plain object.
:::caution[Access note]
For multipart, `@body('title')` returns `undefined` — the value lives at `body.fields.title`,
not `body.title`, unlike JSON/urlencoded where `@body('title')` picks the value directly. Use
`@body()` and read `.fields` / `.files`, or key into the envelope itself with `@body('fields')`
/ `@body('files')`.
:::
```typescript
upload(@body() form: MultipartBody) {
const name = form.fields.name; // string | string[]
const avatar = form.files.avatar; // UploadedFile | UploadedFile[]
return { name, size: Array.isArray(avatar) ? undefined : avatar?.size };
}
```
## Stream decorators — `@inbound` and `@abort`
These are for streaming handlers:
- **`@inbound()`** (WS only) gives you the incoming WebSocket message channel — the client's
messages to consume. A `@Ws` handler returns the **outbound** channel.
- **`@abort()`** (stream / WS) hands you an `AbortSignal` that fires on disconnect, so you can
tear down work when the client goes away.
```typescript
@Ws('/echo')
echo(@inbound() incoming: AsyncIterable<string>) {
const out = channel<string>();
(async () => {
for await (const msg of incoming) out.push(`echo: ${msg}`);
out.close();
})();
return out;
}
```
See [Streaming](/docs/guides/streaming/) for SSE, WebSocket duplex, and channels.
## Where to go next
- How injected values are produced: [Dependency injection](/docs/guides/dependency-injection/).
- The mental model: [The graph](/docs/concepts/the-graph/).
- Validating and coercing injected values: [Validation](/docs/guides/validation/).
- The full API surface: [Decorator reference](/docs/reference/decorators/).
-79
View File
@@ -1,79 +0,0 @@
---
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.
@@ -1,147 +0,0 @@
---
title: Dependency injection
description: "Providers, steps, and modules, and how values flow through the graph."
---
In green-tea the request pipeline is an explicit **dependency graph**. You declare what each
piece needs and produces; the framework computes the order, validates the wiring at boot, and
runs only the slice a route actually depends on. You never write "put this before that."
There are three building blocks:
- A **provider** is an app-scope singleton — constructed once, its value memoized for the
lifetime of the app.
- A **step** runs per request and transforms the context.
- A **module** sets a mountpoint and wires providers, steps, and controllers together.
A handler's **argument decorators are its dependency declaration** — ask for what you want, in
any order. If you `@needs` a token nothing produces, you get a **boot error**, not an
`undefined` at runtime.
## The full example
```typescript
import 'reflect-metadata';
import { createApp, Provider, Step, Route, Get, Module, Unauthorized, needs, param } from '@green-tea/core';
@Provider({ provides: 'db' })
class Database {
provide() { return { db: { find: (id: string) => ({ id, name: 'Diego' }) } }; }
}
@Step({ provides: 'user', needs: ['db', 'req'] })
class Authenticate {
run(ctx: any) {
const user = ctx.db.find(ctx.req.headers['x-token']);
if (!user) throw new Unauthorized('bad token'); // throw = short-circuit the pipeline
return { user }; // return = continue, merge into ctx
}
}
@Route('/users')
class UserController {
@Get('/:id')
getUser(@needs('user') user: any, @param('id') id: string) {
return { requested: id, you: user }; // auto-serialized as JSON
}
}
@Module({ mountpoint: '/api', providers: [Database], steps: [Authenticate], controllers: [UserController] })
class ApiModule {}
const app = createApp({ modules: [ApiModule] });
await app.listen(3000);
// GET /api/users/9 (header x-token) → { "requested": "9", "you": { "id": "...", "name": "Diego" } }
await app.close(); // graceful shutdown: drains in-flight, closes streams + mesh links,
// then force-closes whatever is left after 10s — app.close({ timeoutMs })
```
## `@Provider` — app-scope, memoized
A provider produces a value once, when the app boots, and reuses it for every request. Its
`provide()` method returns an object whose keys become tokens in the graph — here `db`.
```typescript
@Provider({ provides: 'db' })
class Database {
provide() { return { db: { find: (id: string) => ({ id, name: 'Diego' }) } }; }
}
```
Because it's app-scope, a provider is the right home for things you build once and share:
database clients, config, connection pools.
:::note
An optional provider (`optional: true`) that throws on boot does **not** abort startup — it is
left unregistered and logged, and the failure surfaces at request time for routes that need it.
Query the degraded set with `app.degraded()` or listen for the `boot:provider:fail` bus event.
:::
## `@Step` — request-scope, transforms the context
A step runs once per request. Its `run(ctx)` receives the accumulated context and either:
- **returns an object** → the pipeline continues and the object is merged into `ctx`, or
- **throws** → the request short-circuits (here `Unauthorized` becomes a `401`).
```typescript
@Step({ provides: 'user', needs: ['db', 'req'] })
class Authenticate {
run(ctx: any) {
const user = ctx.db.find(ctx.req.headers['x-token']);
if (!user) throw new Unauthorized('bad token'); // throw = short-circuit the pipeline
return { user }; // return = continue, merge into ctx
}
}
```
This step `provides: 'user'` and `needs: ['db', 'req']` — so green-tea knows the `db` provider
and the built-in `req` must resolve before it runs, and it topologically sorts accordingly.
## How `needs` / `provides` build the graph
Every node declares what it **produces** (`provides`) and what it **consumes** (`needs`). The
framework reads those declarations and computes a topological order — you never specify
ordering by hand. A handler's argument decorators extend the same graph: `@needs('user')` on a
parameter is a dependency edge exactly like a step's `needs`.
Because the graph is explicit, **each route runs only the transitive closure of its handler's
`@needs`** — nothing else.
:::caution[Per-route execution]
A route that doesn't `@needs('user')` does **not** run the `Authenticate` step. A cross-cutting
*enforcement* step (e.g. auth that throws `401`) only protects routes that actually `@needs`
its token. To run something on **every** route regardless of needs (logging, audit, a global
guard), add it as a **plugin step** via `scope.add({ ..., provides: [] })` — steps that produce
nothing run unconditionally. Don't rely on a token-providing step to guard routes that don't
declare it.
:::
## `@Module` — mountpoint and wiring
A module ties everything together: a `mountpoint` prefix for the routes, and the lists of
`providers`, `steps`, and `controllers` that belong to it.
```typescript
@Module({ mountpoint: '/api', providers: [Database], steps: [Authenticate], controllers: [UserController] })
class ApiModule {}
```
Pass modules to `createApp({ modules: [ApiModule] })` to assemble the app.
## Boot validation of `@needs`
The payoff of declaring dependencies is that the wiring is checked before a single request is
served. When you `@needs` a token, green-tea verifies some provider or step actually produces
it. If nothing does, **`createApp` throws with a clear error** instead of letting your handler
receive `undefined`. Boot fails loudly, so you never serve `undefined`.
## Where to go next
- New to green-tea? Start with [Getting started](/docs/getting-started/).
- The mental model behind all of this: [The graph](/docs/concepts/the-graph/).
- Everything a handler can inject: [Argument decorators](/docs/guides/arguments/) and the
[decorator reference](/docs/reference/decorators/).
- Coerce and validate injected values with Standard Schema: [Validation](/docs/guides/validation/).
- Declare `@Sse` and return an `AsyncIterable` to push data over time: [Streaming](/docs/guides/streaming/).
-68
View File
@@ -1,68 +0,0 @@
---
title: Error handling
description: "Throw typed errors anywhere; render them however you like with onError."
---
Errors are **thrown, not returned**. Throw a typed error anywhere in the pipeline — a provider, a step, or a handler — and green-tea converts it to a response at one place.
## The typed errors
All live in `@green-tea/core`:
| Throw | Status |
|---|---|
| `Unauthorized(msg?)` | `401` |
| `NotFound(msg?)` | `404` |
| `NotModified()` | `304` |
| `Redirect(location)` | `302` + `Location` |
| `ValidationError` | `422` (raised for you by schema validation) |
| `HttpError(status, msg?, body?)` | any status |
| anything else | `500` (message hidden — internals never leak) |
```typescript
@Step({ provides: 'user', needs: ['db', 'req'] })
class Authenticate {
run(ctx) {
const user = ctx.db.find(ctx.req.headers['x-token']);
if (!user) throw new Unauthorized('invalid token'); // → 401, cuts the request
return { user };
}
}
```
By default an error becomes JSON: `{ "error": "<message>" }` (validation adds `source` + per-field `issues`).
## Structured error bodies
An `HttpError` can carry a **body** — return a structured payload instead of the default `{ error }`:
```typescript
throw new HttpError(409, 'conflict', { code: 'DUP_EMAIL', field: 'email' });
// → 409 { "code": "DUP_EMAIL", "field": "email" }
```
## Render errors your way — `onError`
Not everything should be JSON. Pass `onError` to `createApp` to render errors however you like — HTML, [RFC 7807](https://www.rfc-editor.org/rfc/rfc7807), content-negotiated, anything. It receives the error and the request, and returns a response — or `undefined` to fall back to the default JSON.
```typescript
import { HttpError } from '@green-tea/core';
const app = createApp({
modules: [ApiModule],
onError(error, req) {
const status = error instanceof HttpError ? error.status : 500;
// negotiate: HTML for browsers, JSON for API clients
if (String(req.headers.accept).includes('text/html')) {
return { status, headers: { 'content-type': 'text/html' }, body: `<h1>${status}</h1>` };
}
return undefined; // fall back to the default JSON
},
});
```
`onError` intercepts **every** HTTP error response — handler/step throws, a `404` for an unmatched route, `405`, a `413` (body too large), and a `400` (malformed body, repeated slash, or malformed path encoding) — so your error surface is consistent across the whole app. HEAD error responses keep the same status and headers but suppress the body. Streaming and WebSocket errors are out of scope (they surface as an error frame or a WebSocket close code, not a response body).
:::note
Errors are also observable without changing the response: subscribe to `request:step:error` (and `stream:error`) on [`app.bus`](/docs/guides/plugins/) to log or trace them.
:::
-161
View File
@@ -1,161 +0,0 @@
---
title: HTML & views
description: "The @Html decorator, the built-in template engine, and zero-config static file serving."
---
Most of green-tea assumes JSON, but not every route is an API endpoint. `@Html` marks a handler as serving HTML instead of going through the JSON transformer — a string, a file, or a file rendered with data. Add a static directory on top and you've got a small server-rendered site without reaching for a template framework.
## `@Html` — three modes
### 1. Return a string — every runtime
Bare `@Html` sends the handler's return value as `text/html; charset=utf-8`. No filesystem involved, so this mode runs on Node, Deno, Bun, and the edge.
```typescript
import { Route, Get, Html } from '@green-tea/core';
@Route('/')
class PageController {
@Get('/')
@Html
home() {
return '<h1>Hello from green-tea</h1>';
}
}
```
### 2. Serve a file — Node/Deno/Bun
`@Html('file.html')` reads the file at boot, caches it, and serves it verbatim — the handler still runs (for side effects, guards, etc.) but its return value is ignored.
```typescript
@Route('/about')
class AboutController {
@Get('/')
@Html('about.html')
about() {}
}
```
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
`@Html('file.html', { template: true })` reads the file at boot and renders it with whatever object the handler returns, on every request.
```typescript
@Route('/user')
class UserController {
@Get('/:id')
@Html('user.html', { template: true })
show(@param('id') id: string) {
return { name: lookupName(id) };
}
}
```
`user.html`:
```html
<h1>Hi {{ name }}</h1>
```
Same filesystem requirement as file mode: Node/Deno/Bun only.
:::caution[Return the right shape for each mode — never an `AsyncIterable`]
`@Html` is a buffered route, so its return contract follows the mode: bare `@Html` returns a
`string`; `@Html('file.html', { template: true })` returns the data object rendered into the
template; `@Html('file.html')` (no template) ignores the return entirely — annotate it `: void`
by convention, e.g. `page(@needs('x')): void {}`. Returning an `AsyncIterable` from any `@Html`
handler is the same buffered-route mismatch as any other `@Get`/`@Head`/`@Post`/`@Put`/`@Patch`/`@Delete`/`@Options`
handler: a 500 `TransportMismatchError`, not a silent raw stream.
:::
## The `views` base directory
`@Html('file.html')` paths resolve against `createApp({ views })` — a relative path joins `views`, an absolute path is used as-is (handy for a template stored outside the project, e.g. on an NFS mount). `views` defaults to `process.cwd()` when unset.
```typescript
const app = createApp({ modules: [ApiModule], views: 'templates' });
// @Html('about.html') -> <cwd>/templates/about.html
// @Html('/srv/shared/about.html') -> /srv/shared/about.html (absolute, used as-is)
```
Files are read once, at boot — not on every request.
## The built-in template engine
Template mode renders with a small, dependency-free engine, also exported as `render` if you want to call it directly:
```typescript
import { render } from '@green-tea/core';
render('<h1>{{ name }}</h1>', { name: '<b>hi</b>' });
// '<h1>&lt;b&gt;hi&lt;/b&gt;</h1>' — {{ x }} HTML-escapes
render('{{{ html }}}', { html: '<b>hi</b>' });
// '<b>hi</b>' — {{{ x }}} is raw, unescaped
render('{{ user.name }} / {{ nope }}', { user: { name: 'Diego' } });
// 'Diego / ' — {{ a.b }} walks nested keys; a missing key renders empty
```
That's the whole engine: interpolation, escaped or raw, with dotted-key lookup. No loops, conditionals, or partials — reach for `viewEngine` below if you need those.
## Bring your own engine — `viewEngine`
`createApp({ viewEngine })` swaps in any `(source, data) => string` function for template mode — EJS, Handlebars, or your own:
```typescript
import ejs from 'ejs';
const app = createApp({
modules: [ApiModule],
views: 'templates',
viewEngine: (source, data) => ejs.render(source, data as object),
});
```
`viewEngine` only affects `@Html(..., { template: true })`; string and plain file modes are unaffected.
## Static files — `createApp({ static })`
`static` serves a directory as a GET/HEAD fallback, tried after your declared routes and before a `404`:
```typescript
const app = createApp({ modules: [ApiModule], static: true }); // ./public, relative to cwd
const app2 = createApp({ modules: [ApiModule], static: 'assets' }); // ./assets, relative to cwd
const app3 = createApp({ modules: [ApiModule], static: '/srv/site' }); // absolute, used as-is
```
- Files are served at their URL path; content-type is inferred from the extension.
- `/` (and any directory-shaped path) resolves to `index.html`.
- Only `GET` and `HEAD` are handled — other methods fall through.
- **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.
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
`@Html` only supports **buffered `GET`/`POST`** routes. Boot fails fast rather than misbehaving at request time:
```typescript
@Sse('/ticks')
@Html
ticks() { /* ... */ }
// throws at createApp(): "@Html on GET /ticks is not allowed —
// @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:
```typescript
@Get('/g')
@Html
@Transformer(myTransformer)
g() { /* ... */ }
// throws at createApp(): "@Html and @Transformer on /g conflict — use one"
```
Both checks run once, at boot, alongside the rest of the route validation — never per-request.
@@ -1,55 +0,0 @@
---
title: Graph introspection
description: "explain, graph, toMermaid, and the graph endpoint."
---
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
single route runs.
## Visualize with Mermaid
`app.toMermaid()` renders a flowchart of every node and route. `app.toDOT()` produces the
same graph as Graphviz DOT.
```typescript
console.log(app.toMermaid()); // flowchart diagram of all nodes and routes
```
Enable a live `GET /__graph__` endpoint — it renders an HTML viewer with Mermaid, or the
raw Mermaid source with `Accept: text/plain`:
```typescript
const app = createApp({ modules: [ApiModule], devGraph: true });
// GET /__graph__ → HTML viewer
// GET /__graph__ (text/plain) → raw Mermaid source
```
:::caution
`devGraph` exposes your graph structure over HTTP. Keep it on in development; leave it off
in production.
:::
## Explain a route
`app.explain(route)` returns the exact execution chain for one route — the ordered nodes,
each with its kind, origin, and declared `needs`/`provides`:
```typescript
const e = app.explain('/api/users/:id');
// { pattern, method, transport, chain: [{ name, kind, origin, needs, provides }, ...] }
console.log(e.chain.map((n) => `${n.kind}:${n.name}`));
// → ['provider:db', 'step:user', 'handler:getUser']
```
The chain is the transitive closure of the handler's `@needs` — the same set the framework
actually runs for that route, and nothing more.
`app.graph()` returns the underlying graph structure programmatically if you'd rather walk
it yourself than render it.
## Degraded optional providers
`app.degraded()` returns the names of optional providers that are running in a **degraded**
state — for example, an optional dependency that failed to initialize but didn't abort boot.
Use it as a health signal to surface partial availability.
-145
View File
@@ -1,145 +0,0 @@
---
title: Mesh (alpha)
description: "Distributed dependency injection over a secret-gated WebSocket control channel."
---
:::caution[Alpha]
Mesh is **alpha** — its API and wire protocol may change between releases, and discovery, load-balancing, and failover are not built. It is gated behind an explicit opt-in: `createApp({ mesh, experimental: true })`, and `createApp` **throws** if you configure `mesh` without `experimental: true`. **Don't ship mesh to production yet.**
:::
A **teacup** can depend on a token that physically lives on another node — a **teapot**. `@needs('billing')` resolves the same whether `billing` runs in this process or on a remote one. There's no gRPC layer or message-pattern DSL: there's the [graph](/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.
## What runs where
Mesh runs on **Node, Deno and Bun**, as both teapot and teacup, in any combination — a Deno teapot can serve a Node teacup. The wire is JSON over a WebSocket, so peers only have to agree on the protocol version, not the runtime.
**Edge (Cloudflare Workers) is not supported.** The teapot's secret comparison uses `node:crypto`'s `timingSafeEqual`, which workerd's `nodejs_compat` does not provide.
You do **not** need `listen()`. The graph boots on first use, so `Deno.serve`/`Bun.serve` work through `app.fetch`/`app.upgrade` like any other route:
```typescript
serveDeno(teapot, { port: 3002 }); // control channel served via app.upgrade
serveBun(teacup, { port: 3003 }); // teapots connected on the first request
```
## Node A — teapot (exposes `config`, `auth`, and a route)
```typescript
@Provider({ provides: 'config', export: true })
class Config { provide() { return { config: { region: 'mx', tier: 'pro' } }; } }
@Step({ provides: 'auth', needs: [], export: true })
class Auth { run(ctx: any) { return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; } }
@Route('/svc')
class Svc { @Get('/ping', { export: true }) ping() { return { pong: true }; } }
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth], controllers: [Svc] })
class TeapotModule {}
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'shh' } });
await teapot.listen(3002);
```
## Node B — teacup (uses `config` + `auth` with no local providers)
```typescript
@Route('/local')
class LocalCtl {
@Get('/who')
who(@needs('config') config: any, @needs('auth') auth: any) {
return { config, auth }; // both resolved by RPC to the teapot
}
}
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: 'ws://A-host:3002/__mesh__/control', secret: 'shh' }] },
});
await teacup.listen(3003);
// GET B:3003/api/local/who (x-token: abc)
// → { "config": { "region": "mx", "tier": "pro" }, "auth": { "token": "abc" } }
```
## How it resolves
`@needs('config' | 'auth')` validates at boot because the teapot announced them in its **manifest** on connect. Scope determines the RPC cost:
- A **provider** export is **app-scope** — resolved once and cached.
- A **step** export is **request-scope** — one RPC per request, carrying the request envelope.
Remote tokens become synthetic nodes in the local graph with RPC-backed runners, so the rest of the pipeline is unchanged. For non-mesh apps `createApp` stays synchronous; a mesh app defers graph finalization until it boots — connecting to teapots is network I/O — and boots on whichever comes first: `app.fetch`, `app.upgrade` or `listen()`. Whoever triggers it, it happens once.
## Inspecting a mesh graph
`inspect()`, `graph()` and `explain()` are synchronous, but a mesh graph is not knowable until its teapots have been asked — so on a mesh app they throw until the graph is resolved. `await app.ready()` resolves it:
```typescript
await app.ready(); // connects the teapots; a no-op on a non-mesh app
app.graph(); // now includes the remote scopes
```
Write those two lines and your code works against either kind of app without knowing which it got. `ready()` deliberately does **not** boot providers — resolving the graph and being ready to serve are different things, and drawing a diagram should not open your database connections. Serving (`fetch`/`upgrade`/`listen`) boots them too and shares the same memoized step, so calling both never resolves the graph twice.
The dev routes (`/__graph__`, `/__openapi__`) need none of this: a request boots the app before the route runs.
## Buffered routes only
Mesh proxies **buffered** endpoints. `@Sse`, `@Stream` and `@Ws` routes are not exportable: a remote route is registered as `transport: 'buffer'`, and a handler that returns an `AsyncIterable` over a mesh call fails with `cannot proxy a streaming route`. Streams are a live socket between client and server; there is no meaningful way to relay one through an RPC hop today.
## One teapot per route
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: ambiguous remote route 'GET /api/shape/:name' from ws://b/__mesh__/control
conflicts with 'GET /api/shape/:id' from ws://a/__mesh__/control — load balancing
across teapots is not implemented yet, so green-tea will not choose one for you.
```
This is a hard error rather than a silent pick because there is no load balancing to fall back on: choosing one would be an arbitrary answer you could come to depend on. Scope tokens (`@Provider`/`@Step`) are unique for the same reason — and balancing them would be meaningless anyway, since an app-scope export is resolved once and cached.
**Local routes win.** If you declare a route locally *and* import 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
declared locally — the local route takes precedence and the remote one will not be
reached. Remove one if that is not what you meant.
```
## When a teapot goes away
A dead upstream is not a broken service, and the status says which:
| What happened | Status |
| --- | --- |
| The link is down (closed, or the heartbeat gave up) | **503** Service Unavailable |
| The link is up but the teapot didn't answer in `timeoutMs` | **504** Gateway Timeout |
| The teapot answered with an error | whatever it said |
503 arrives **immediately** — a closed socket cannot deliver the frame, so waiting `timeoutMs` (30s by default) would just make the caller pay for a verdict already known.
Each teacup pings its teapots every `heartbeatMs` (15s by default) and closes a link after two unanswered rounds. This is what catches a **half-open** connection — a dropped route, a killed container, a NAT that timed out — where the socket still looks open with nobody home. Without it, a teacup only finds out on the next request, which pays the full timeout first.
```typescript
mesh: { teapots: [...], heartbeatMs: 5000 } // notice sooner, chatter more
```
Ping and pong are ordinary mesh frames rather than WebSocket protocol pings, because the platform `WebSocket` on Deno and Bun does not expose `ws.ping()` — a protocol-level heartbeat could not work on every runtime mesh supports.
**An app-scope export survives its teapot.** It is resolved once and memoised, so a provider keeps answering from cache after the link drops — with a value that can go stale. Reconnect reconciliation is a known gap.
## Protocol version
Peers are separate processes on separate deploy cadences, so the wire is versioned: `MESH_PROTOCOL_VERSION` travels in the `hello` and `manifest` frames, and a mismatch is refused on both sides with both versions named. A teapot checks the version **before** the secret — a skewed peer is not an authentication failure, and reporting it as one would send you hunting the wrong bug.
Bump the version and old peers refuse the connection loudly instead of misreading a frame.
:::note[Skeleton limitations (by design)]
No discovery, load-balancing, or failover yet; app-scope remote values are not reconciled on reconnect; the request envelope omits `req.url`.
:::
@@ -1,145 +0,0 @@
---
title: Observability
description: A correlated lifecycle event stream, an injectable logger, and where exporters go.
---
green-tea does not integrate with an observability vendor. It emits a **correlated event stream** and
lets you read it. A logger, a metrics exporter and a tracing bridge are three consumers of that one
stream — not three features, which is why they are one design.
The rule that shapes all of it: core has one runtime dependency, `reflect-metadata`, and keeps it.
Nothing here imports an exporter.
## Correlation
Every request gets an id. Every event it causes carries that id.
```ts
app.bus.on('request:step:leave', (event) => {
event.requestId; // "9f0c…" — the same value on every event of this request
event.route; // "/users/:id" — the pattern, never the concrete path
event.durationMs; // how long this step took
});
```
Without that id the stream is unusable under any concurrency: two requests interleave their step
events and nothing tells you which is which.
**An incoming `x-request-id` is adopted, not replaced.** A service behind a gateway must not open a
second identity for a request that already has one.
**A `traceparent` header is carried through untouched** as `traceId`. Core parses nothing and
implements no propagation spec — W3C Trace Context belongs to the exporter that understands it.
### `route` is the pattern, always
`route` is `/users/:id`, never `/users/42`. This is a contract, not an implementation detail: a
metrics consumer that labels a counter with the concrete path gets one label per distinct URL, and
unbounded label cardinality takes down the metrics backend rather than the application.
## The events
| Event | When |
|---|---|
| `request:start` / `request:end` | a request enters and leaves the handler |
| `request:failed` | the request produced an error |
| `route:matched` / `route:unmatched` | a route matched, or none did (covers **404 and 405**) |
| `request:step:enter` / `:leave` / `:error` | one step of the pipeline |
| `boot:provider:start` / `:ok` / `:fail` | a provider booting |
| `stream:open` / `:close` / `:error` | an SSE, ndjson or WebSocket connection |
| `mesh:connect` / `:disconnect` / `:rpc:error` | mesh links |
| `plugin:mounted` | a plugin registered |
### Where a streaming request ends
`request:end` fires **when the handler returns**, not when a stream it produced finishes.
A streaming route returns in milliseconds while its connection may live for hours. Ending the
request span at stream close would put hour-long SSE connections and 2 ms buffered replies in one
latency distribution, ruining both. The connection is described by `stream:open` / `stream:close`,
which carry the same `requestId` — so you can join the two yourself, and you get a meaningful
latency histogram either way.
### Streams do not emit per message
Lifecycle only. A per-message event on a high-rate stream is a firehose that costs more than it
reports, and the cost lands on the workload least able to absorb it. Instrument your own handler if
you need it, where you know what the messages mean.
## The logger
```ts
const app = createApp({ modules: [AppModule], logger: myLogger });
```
Any object with `debug`, `info`, `warn` and `error` — each taking a message and optional structured
fields. Bridging `pino` or `winston` is a few lines in either direction; core defines the shape it
needs rather than adopting anyone's.
Given none, the default writes structured JSON, or a human-readable line when the process is
attached to a TTY — decided once at boot, not per record.
**Nothing in core writes to `console`.** That is enforced by a lint rule, not by good intentions, so
every framework diagnostic is redirectable.
The logger is also injectable:
```ts
@Step({ provides: 'user', needs: ['db'] })
class LoadUser {
run(@needs('logger') log: Logger) { … }
}
```
Same object, two access paths. It is registered rather than declared as a provider because it has to
outlive the graph on both ends: a provider cannot report its own boot failing, and shutdown warnings
happen after the graph is gone.
## Request logging
Off by default. A framework that writes to stdout uninvited is one you have to configure before you
can use it.
```ts
createApp({ modules: [AppModule], logRequests: true });
```
It is an ordinary subscriber, so you can do it by hand and take it back:
```ts
import { logRequests } from '@green-tea/core';
const stop = logRequests(app.bus, app.logger);
stop(); // removable, not merely optional
```
A logger that throws does **not** silently stop writing: the subscriber is wrapped so failures fall
back to `console`. `Bus.emit` isolates listener failures by design — an observer must never break a
request — and the wrapper keeps that guarantee without paying for it in silence.
## Metrics and tracing
There is no metrics registry in core and no OpenTelemetry exporter in core. Both read the stream
above from outside:
```ts
app.bus.on('request:end', (e) => histogram.observe(e.durationMs, { route: e.route, status: e.status }));
```
Per-step timings are already on the events, so a per-node timing breakdown needs no extra
instrumentation — the graph already knows every node.
## What it costs
**About 0.29 µs per request** — roughly **7% of the framework's own work**, or **~2% of a request
measured over a real socket**, where the transport dominates.
The cost is **per request, not per step**. Per-step timing and payload construction are skipped
entirely when nothing is subscribed, so a deep pipeline pays no more than a shallow one. What
remains is fixed: generating the request id, reading two headers, and the checks that decide
whether anyone is listening.
Absolute throughput numbers are deliberately not quoted here. The figure above comes from an
interleaved A/B — alternating both versions round by round — because the same code measured at the
start and end of one session on the same machine differed by 12% as it warmed up. Any before/after
that does not interleave is measuring the clock as much as the code.
@@ -1,43 +0,0 @@
---
title: OpenAPI
description: "Generate a structural OpenAPI 3.1 document from the route graph."
---
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()`
```typescript
const app = createApp({ modules: [ApiModule] });
const spec = app.openapi({ title: 'My API', version: '1.0.0' });
// → OpenAPI 3.1 document
```
It reads the routes and handler signatures and produces, for each route:
- the **path**, templated — `/users/:id` → `/users/{id}`, constrained `:id(\d+)` → `{id}`, catch-all `:path*` → `{path}`;
- the **explicitly declared method**, including `@Head` and `@Options`;
- **parameters** — path params from the pattern, plus query/header params from the handler's `@query` / `@headers` / `@header` decorators;
- a **request body** entry for routes that read `@body()`;
- the systematic **responses** — `200`, a `422` when any argument is schema-validated, and `500`.
WebSocket routes are omitted (they aren't request/response).
A constrained path parameter remains a string parameter and carries its route expression as `schema.pattern`. Only declared operations appear: implicit HEAD and automatic OPTIONS fallbacks are runtime conveniences and are not invented in the OpenAPI document.
## Serve it — `devOpenapi`
Opt in to a `GET /__openapi__` endpoint that returns the document as JSON — point Swagger UI, Redoc, or a codegen client at it:
```typescript
const app = createApp({ modules: [ApiModule], devOpenapi: true });
// GET /__openapi__ → application/json
```
## What's structural (and what isn't 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](/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.
@@ -1,64 +0,0 @@
---
title: Plugins
description: "Extending the app safely via bus.on and scope.add."
---
A plugin is a function that receives the app's API at boot. It gets exactly two
capabilities: **observe** the running system through `bus.on(...)`, and **extend its own
scope** through `scope.add(...)`. That's the whole surface — and it's deliberately narrow.
```typescript
const logger = (api: any) => {
api.bus.on('request:step:enter', (p: any) => console.log(`→ ${p.name}`));
api.bus.on('stream:open', (p: any) => console.log(`stream open ${p.name}`));
api.bus.on('mesh:rpc:error', (p: any) => console.error('mesh rpc failed', p.error));
};
const app = createApp({ modules: [ApiModule], plugins: [logger] });
```
## Isolation is structural
A plugin can add steps and providers to **its own scope** via `scope.add(...)`. It
**cannot** reorder or delete another scope's steps. The graph — not a policy check —
enforces this: each scope owns its nodes, and a plugin has no handle on anyone else's.
There's no ordering hook to abuse and no step registry to mutate. If you want a plugin to
influence execution, it does so by contributing a node with declared `needs`/`provides`,
and the framework computes where that node lands.
:::note
Because execution is per-route (a route runs only the transitive closure of its handler's
`@needs`), a plugin step that should run on **every** route must produce nothing — add it
with `provides: []`. A step that produces no token has nothing to gate on, so the framework
runs it unconditionally. See [The graph](/docs/concepts/the-graph/) for how the closure is
computed.
:::
## Lifecycle & request events
Subscribe to events on the `Bus` to observe boot, per-request execution, streaming, and
mesh activity without touching the pipeline itself:
```typescript
api.bus.on('boot:provider:ready', (p: any) => { /* ... */ });
api.bus.on('request:step:enter', (p: any) => { /* ... */ });
api.bus.on('request:step:leave', (p: any) => { /* ... */ });
```
The full event vocabulary, what each payload carries, and how requests are correlated across
them live in [Observability](/docs/guides/observability/). The short version:
- `request:start | request:end | request:failed` — the request itself
- `route:matched | route:unmatched` — routing (`unmatched` covers both 404 and 405)
- `request:step:*` — a step entering/exiting/failing, with its own `durationMs`
- `boot:provider:*` — provider lifecycle during boot
- `stream:open | stream:close | stream:error` — SSE/WS stream lifecycle
- `mesh:connect | mesh:disconnect | mesh:rpc:error` — mesh link and RPC activity
- `plugin:mounted` — a plugin finished mounting
Every per-request payload carries a `requestId`, so a plugin can attribute events to the request
that caused them — which matters the moment two requests overlap.
Observation is read-only: handlers see the event payload but can't alter control flow. To
change behavior, contribute a node to your scope — see
[Dependency injection](/docs/guides/dependency-injection/).
@@ -1,74 +0,0 @@
---
title: Routing
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**.
## Method decorators
| Decorator | Method / transport |
|---|---|
| `@Get` `@Head` `@Post` `@Put` `@Patch` `@Delete` `@Options` | buffered HTTP response |
| `@Sse` | server-sent events (`text/event-stream`) |
| `@Ws` | WebSocket duplex |
| `@Stream` | negotiated — SSE / ndjson / WS, picked from the client's `Accept` / `Upgrade` |
```typescript
@Route('/users')
class Users {
@Get('/:id') get(@param('id') id: string) { /* ... */ }
@Post('/') create(@body() data: unknown) { /* ... */ }
}
```
The path a route matches is `joinPath(module.mountpoint, route.path)` — a controller under `@Module({ mountpoint: '/api' })` with `@Route('/users')` + `@Get('/:id')` serves `/api/users/:id`.
## Pattern segments
- **Static** — `users` matches exactly.
- **`:param`** — matches exactly one segment; the decoded value lands in `params.name` (`@param('id')`).
- **`:param(constraint)`** — matches one complete decoded segment when it satisfies a safe regex subset, for example `:id(\d+)`.
- **`:name*` catch-all** — a trailing segment that captures the **rest of the path, slashes included**, into `params.name`.
```typescript
@Get('/users/:id(\\d+)') // /users/42 matches; /users/alice does not
@Get('/files/:path*') // /files/img/2026/logo.png → params.path = "img/2026/logo.png"
```
A catch-all also matches zero remaining segments (`/files` → `params.path = ""`).
Constraints are anchored to the whole segment automatically. They allow character classes, alphanumeric/literal atoms, the escaped character classes `\d`, `\D`, `\s`, `\S`, `\w`, `\W`, and simple quantifiers (`+`, `*`, `?`, `{n}`, `{n,m}`). Groups, alternation, lookarounds, backreferences, anchors, and other arbitrary regex features are rejected at boot. Expressions are limited to 128 characters, counted quantifiers are capped, and unsafe adjacent unbounded quantifiers are rejected. This deliberately small subset avoids accepting route regexes with obvious ReDoS shapes.
Patterns must start with `/`, parameter names must be unique and use identifier syntax, and a catch-all must be the final segment. Repeated slashes in a declared pattern fail at boot.
## Precedence
When more than one route matches the same path, the **most specific wins** — `static ▸ constrained :param ▸ plain :param ▸ catch-all` — compared segment by segment, independent of registration order.
```typescript
@Get('/a/b') // wins for /a/b
@Get('/a/:id(\\d+)') // wins for /a/42 over the plain parameter
@Get('/a/:id') // wins for /a/x
@Get('/a/:rest*') // wins for /a/x/y
```
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`.
## Matcher scale
Route matching remains a **linear scan** — fine for typical route tables. A radix-tree matcher for very large route tables remains on the roadmap.
See [Streaming & real-time](/docs/guides/streaming/) for `@Sse` / `@Ws` / `@Stream`, and [Argument decorators](/docs/guides/arguments/) for everything a handler can read from a request.
-174
View File
@@ -1,174 +0,0 @@
---
title: Runtimes (Node, Deno, Bun, edge)
description: "Run Green Tea anywhere with app.fetch — the Web-Standards handler."
---
Green Tea exposes a Web-Standards handler, `app.fetch(request): Promise<Response>`, so the
same app runs on any runtime that speaks the Fetch API — for **HTTP and SSE** today.
```ts
const app = createApp({ modules: [ApiModule] });
// Node (native listener, TLS, timeouts)
app.listen(3000);
// Deno
Deno.serve(app.fetch);
// Bun
Bun.serve({ fetch: app.fetch });
// Cloudflare / edge
export default { fetch: app.fetch };
```
**Node is the reference implementation.** A parity suite pins `app.fetch` to Node's native
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 via `app.listen()`, Deno and Bun via
`serveDeno` / `serveBun`, and Cloudflare Workers / edge via `edgeHandler` (see below) — same graph,
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)
runs on Node, Deno and Bun** — teapot and teacup, in any combination — but not on edge.
**Connection-limit enforcement is Node-only:** `limits.maxConnections` defaults to `1000`; values
`<= 0` leave Node's connection count unlimited. Positive values map to Node's
`server.maxConnections` when the app runs through `app.listen()`. When the cap is reached, Node
destroys excess sockets without sending an HTTP response. `Deno.serve` and `Bun.serve` expose no
equivalent active-socket cap, so `serveDeno` and `serveBun` cannot enforce this option. Apply the
connection limit at the deployment platform or reverse proxy on those runtimes.
**Shutdown belongs to whoever owns the server.** `app.close()` is Node-only. On Deno and Bun the
app is served through `app.fetch` and never through `app.listen()`, so `app.close()` has no server
to drain and returns immediately — it warns if you passed `timeoutMs`. The server `serveDeno()` and
`serveBun()` return carries the same `close({ timeoutMs })` instead:
```ts
const server = serveBun(app, { port: 3000 }); // or serveDeno(app, { port: 3000 })
await server.close({ timeoutMs: 5_000 });
```
On Cloudflare Workers there is nothing to close: `edgeHandler` is a handler, not a server, and the
platform owns the lifecycle.
One difference the deadline cannot hide:
| Runtime | After the deadline |
|---|---|
| Node | warns, then `closeAllConnections()` — the remainder is cut |
| Bun | warns, then `stop(true)` — the remainder is cut |
| Deno | warns, then **returns anyway**; the remainder ends with the process |
Deno offers no force-close that composes with a drain already under way — aborting the signal its
server was started with throws `BadResource` once `shutdown()` is pending. So on Deno the deadline
bounds how long `close()` waits, not when the connections die. Exit the process after `close()`
resolves and the effect is the same; keep serving and it is not.
**Body-size enforcement differs slightly:** on `app.fetch`, an oversized body is read in full
before the `413` is returned, whereas Node aborts mid-stream once the limit is hit — so on
non-Node runtimes, also bound request size at the platform/runtime layer.
## WebSocket on Deno
`app.fetch` covers HTTP + SSE on every runtime. WebSocket needs a runtime-specific
upgrade, so Deno gets a dedicated adapter at `@green-tea/core/deno`:
```ts
import { createApp } from '@green-tea/core';
import { serveDeno } from '@green-tea/core/deno';
const app = createApp({ modules: [ChatModule] });
// HTTP + SSE via app.fetch, WebSocket via Deno.upgradeWebSocket — one call:
serveDeno(app, { port: 8000 });
```
`serveDeno` routes normal requests through `app.fetch` and WebSocket upgrades through
`app.upgrade` — the same graph, the same `@Ws` handlers, the same rooms/channels you
run on Node. Behaviour matches the Node reference.
**Advanced:** `app.upgrade(request, socket)` is the neutral primitive `serveDeno` uses.
Any runtime can build a `WsSocket` capability (`inbound`, `abort`, `isOpen`, `send`,
`close`, `terminate`) and drive the graph — `serveBun` and `edgeHandler` build on the
same primitive (see below).
**Still Node-only:** `app.listen()`, TLS and per-request timeouts. On Deno you get
`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`.
## WebSocket on Bun
`app.fetch` covers HTTP + SSE on every runtime. WebSocket needs a runtime-specific
upgrade, so Bun gets a dedicated adapter at `@green-tea/core/bun`:
```ts
import { createApp } from '@green-tea/core';
import { serveBun } from '@green-tea/core/bun';
const app = createApp({ modules: [ChatModule] });
// HTTP + SSE via app.fetch, WebSocket via Bun's server-level handler — one call:
serveBun(app, { port: 8000 });
```
`serveBun` routes normal requests through `app.fetch` and WebSocket upgrades through
`app.upgrade` — the same graph, the same `@Ws` handlers, the same rooms/channels you
run on Node and Deno. Behaviour matches the Node reference.
**Still Node-only:** `app.listen()`, TLS and per-request timeouts. On Bun you get
`app.fetch` + `serveBun`. [Mesh](/docs/guides/mesh/) works here too.
## Cloudflare Workers / edge
`app.fetch` covers HTTP + SSE on every runtime. WebSocket needs a runtime-specific
upgrade, so Cloudflare Workers get a dedicated adapter at `@green-tea/core/edge`:
```ts
import { createApp } from '@green-tea/core';
import { edgeHandler } from '@green-tea/core/edge';
const app = createApp({ modules: [ChatModule] });
export default { fetch: edgeHandler(app) };
```
`edgeHandler` routes normal requests through `app.fetch` and WebSocket upgrades through
`WebSocketPair` and `app.upgrade` — the same neutral primitive `serveDeno` and `serveBun`
use. Same graph, same `@Ws` handlers, same rooms/channels as Node/Deno/Bun; behaviour
matches the Node reference; validated on real workerd (Miniflare).
**Requirement:** the Worker must enable the `nodejs_compat` compatibility flag —
`wrangler.toml`:
```toml
compatibility_flags = ["nodejs_compat"]
compatibility_date = "2024-09-23" # or later
```
Green Tea's core statically imports Node built-ins that workerd only provides under
this flag; without it, the Worker fails to load.
**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
`timingSafeEqual`, which `nodejs_compat` does not provide. Cloudflare's
Durable Objects and WebSocket Hibernation are **not** used — `edgeHandler` accepts
WebSockets with the standard `WebSocketPair` model, so a Worker holds the connection
open for its lifetime rather than hibernating between messages.
## Filesystem features — Node/Deno/Bun only
A few [HTML & views](/docs/guides/html/) features read from disk, so they need a runtime with
a filesystem:
- `@Html('file.html')` — reads and caches the file at boot.
- `@Html('file.html', { template: true })` — same, then renders it per request.
- `createApp({ static })` — serves a directory of files.
All three throw at boot (`createApp()`/route-build time) on a runtime without a
filesystem, rather than failing per-request. On the edge, use bare `@Html` returning a
string instead — pair it with the exported `render` over a template string you `import`
as a module (so it ships in the bundle, no disk read), and serve other assets (images,
CSS, JS) from a CDN in front of the Worker.
-103
View File
@@ -1,103 +0,0 @@
---
title: Transport security
description: "TLS and wss, secure-by-default headers, CORS, and trustProxy."
---
Four `createApp` options cover TLS, proxying, CORS, and response headers: `tls`,
`trustProxy`, `cors`, and `security`. See the [`createApp` reference](/docs/reference/createapp/)
for the full option list.
## TLS (native https/wss)
```typescript
import { readFileSync } from 'fs';
const app = createApp({
modules: [App],
tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') },
});
```
When `tls` is set the server serves https, and WebSocket upgrades become wss on the same
port — no other changes.
## `trustProxy`
```typescript
const app = createApp({ modules: [App], trustProxy: true });
```
Behind a reverse proxy, reads `X-Forwarded-Proto` / `X-Forwarded-For` to populate
`ctx.protocol` (`'http' | 'https'`) and `ctx.ip` (read via `@ctx()`). Off by default —
forwarded headers are ignored (and spoofable) until you opt in. It trusts the immediate hop
unconditionally; there's no CIDR allowlist yet.
## CORS
Off unless `origins` is set.
```typescript
const app = createApp({
modules: [App],
cors: { origins: 'https://app.example.com', credentials: true },
});
```
`origins` accepts `string | string[] | '*' | (origin) => boolean`. A preflight `OPTIONS`
request (with `Access-Control-Request-Method`) is auto-answered with 204 before explicit or
automatic OPTIONS routing. A bare OPTIONS request is instead handled by an explicit `@Options`
route or the router's automatic `204` + `Allow` response.
- With `credentials: true`, the server **never** sends `Access-Control-Allow-Origin: *` — it
echoes the concrete allowed origin (or blocks the request).
:::caution[Reflect-any foot-gun]
`origins: '*'` together with `credentials: true` reflects *any* origin with credentials
attached. Only combine them if you truly intend an open credentialed API; prefer an explicit
allowlist.
:::
## `security` (headers, ON by default)
Applied to every HTTP response. Disable everything with `security: false`, or override
individual headers with an options object.
| Header | Default |
|---|---|
| `X-Content-Type-Options` | `nosniff` |
| `X-Frame-Options` | `SAMEORIGIN` |
| `Referrer-Policy` | `no-referrer` |
| `X-DNS-Prefetch-Control` | `off` |
| `Strict-Transport-Security` | `max-age=15552000` (180d) — **only when the connection is secure** (native TLS, or `trustProxy` + `X-Forwarded-Proto: https`); no `includeSubDomains`/`preload` |
| `Content-Security-Policy` | not set — pass `security: { csp: "..." }` |
```typescript
const app = createApp({ modules: [App], security: { csp: "default-src 'self'" } });
```
:::note[Scope caveat]
`security` and `cors` headers apply to HTTP responses; they do **not** apply to the
WebSocket handshake (101/upgrade) response.
:::
:::caution[TLS + trustProxy]
HSTS is emitted only when the connection is judged secure. With `trustProxy: true` that
judgement trusts the incoming `X-Forwarded-Proto` header — so a client that spoofs
`X-Forwarded-Proto: http` past a permissive proxy can make the server treat the request as
insecure and **suppress the HSTS header**. Only enable `trustProxy` behind a proxy that
strips and sets forwarded headers itself, and terminate TLS where you control that hop.
:::
## Defaults
| Option | Default |
|---|---|
| `tls` | off (plain http/ws) |
| `trustProxy` | off |
| `cors` | off (same-origin only) |
| `security` | ON (HSTS only when the connection is secure) |
## Related
- [`createApp` reference](/docs/reference/createapp/) — every construction option
- [File uploads / multipart](/docs/guides/uploads/) — request-body handling
@@ -1,116 +0,0 @@
---
title: Streaming & real-time
description: "SSE, ndjson, and WebSocket duplex from one AsyncIterable primitive."
---
Most stacks treat "push data over time" as a bolt-on: Express reaches for a `ws` or SSE library, Fastify for a plugin, NestJS for a separate **WebSocket Gateway** with its own adapter and decorators. That's a second mental model, a second error surface, glued to your HTTP app.
green-tea has one model: an **`AsyncIterable`**. A handler that returns a sequence of values over time *is* a stream — the same shape you'd return from any function. You **declare the mode** with a decorator; the framework handles framing, backpressure, cleanup, and disconnects.
## One primitive, three modes
| Declare | Direction | Transport | Reach for it when |
|---|---|---|---|
| `@Sse` | server → client | `text/event-stream` | live updates to a browser (`EventSource`) |
| `@Ws` | duplex | WebSocket | chat, collaboration — anything two-way |
| `@Stream` | negotiated | SSE / ndjson / WS, picked from the client's `Accept` / `Upgrade` | one handler, the client chooses |
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`** — you return **one** iterable: the *outbound* stream. Each `yield` becomes an SSE event, or an ndjson line.
- **`@Ws` (duplex)** — **two** iterables. `@inbound()` gives you the client's *incoming* messages to consume; the one you **return** is the *outbound* stream to the client. `@abort()` hands you an `AbortSignal` for teardown.
- **`@Stream`** — you write the handler once; the client's request decides whether it arrives as SSE, ndjson, or a WebSocket. No branching in your code.
:::note
Streaming bypasses the response transformer — the transport frames each value directly, handles backpressure, and cleans up on disconnect. See [arguments](/docs/guides/arguments/) for the full list of argument decorators, including the stream-only `@inbound()` and `@abort()`.
:::
## Streaming — SSE
A route decorated `@Sse` streams — that's what triggers it, not the return value. It must return an `AsyncIterable`; the transport frames each value as an SSE event, handles backpressure, and cleans up on disconnect (the transformer is bypassed).
```typescript
import { Route, Sse } from '@green-tea/core';
@Route('/feed')
class FeedController {
@Sse('/ticks')
ticks() {
return (async function* () {
for (let n = 1; n <= 3; n++) yield { tick: n };
})();
}
}
// GET /feed/ticks (Accept: text/event-stream)
// data: {"tick":1}
// data: {"tick":2}
// data: {"tick":3}
```
`@Stream(path)` negotiates the transport by header (`Accept: text/event-stream` → SSE, `Upgrade: websocket` → WS, else ndjson chunked).
## Streaming — WebSocket duplex
A WS handler receives the **inbound** channel and returns the **outbound** channel — a step that consumes one channel and produces another.
```typescript
import { Route, Ws, inbound, channel } from '@green-tea/core';
@Route('/chat')
class ChatController {
@Ws('/echo')
echo(@inbound() incoming: AsyncIterable<string>) {
const out = channel<string>();
(async () => {
for await (const msg of incoming) out.push(`echo: ${msg}`);
out.close();
})();
return out;
}
}
```
`channel<T>()` is a multicast `AsyncIterable` with `push` / `close` / `fail` and an optional bounded buffer (`channel({ buffer: 100 })`, drop-oldest).
:::note[WebSocket needs the `ws` peer]
`@Ws` (and mesh) require the optional [`ws`](https://github.com/websockets/ws) peer dependency — `npm i ws`. SSE, ndjson, and plain HTTP need nothing extra.
:::
## Fan-out — `channel()` and `rooms`
Fan-out is a primitive too: `channel()` is a **multicast** `AsyncIterable` (bounded, drop-oldest) so one source feeds many subscribers, and `rooms` are named broadcast hubs — publish once, every connection in the room receives it.
```typescript
@Route('/live')
class Live {
@Sse('/prices') // one iterable out — each yield is an event
prices() {
return (async function* () {
while (true) { yield { btc: await getPrice() }; await sleep(1000); }
})();
}
@Ws('/echo') // duplex — consume @inbound, return the outbound stream
echo(@inbound() incoming: AsyncIterable<string>) {
const out = channel<string>();
(async () => { for await (const m of incoming) out.push(`echo: ${m}`); out.close(); })();
return out;
}
}
```
Same `@Route`, same handler shape, same `AsyncIterable` — real-time is not a separate framework you also have to learn.
`rooms` is the built-in shared `Rooms` primitive (one instance app-wide). A typical chat handler pumps the `@inbound()` channel into `rooms.room(name)` and returns that same room as its outbound channel, so every joined socket multicasts to the others. A handshake `@Step` can read `?token=` and throw `Unauthorized` — which closes the socket with code **4401** (`4000 + status`). See [security](/docs/guides/security/) for handshake authentication.
## Transport is declared, not inferred
A route streams **because** it's declared `@Sse`, `@Stream`, or `@Ws` — never because a handler happened to return an `AsyncIterable`. In most frameworks the return type decides the wire format; in green-tea the decorator decides, and the return value is enforced against it:
| Declare | Handler must return | Otherwise |
|---|---|---|
| `@Get` / `@Head` / `@Post` / `@Put` / `@Patch` / `@Delete` / `@Options` (buffered) | a value | returning an `AsyncIterable` fails with a 500 `TransportMismatchError` |
| `@Sse` / `@Ws` (streaming) | an `AsyncIterable` | returning a plain value fails with a 500 `TransportMismatchError` |
| `@Stream` (negotiate) | either | the client picks via `Accept` / `Upgrade` — no mismatch |
This is the anti-Express guarantee: your wire contract is what you **declared**, never a surprise sprung by a return value. A buffered route can't accidentally start streaming because someone returned a generator; a streaming route can't silently downgrade to a buffered response because someone forgot a `yield`. Declare `@Sse` / `@Stream` / `@Ws` to stream — the return value never changes a route's transport.
@@ -1,33 +0,0 @@
---
title: Testing
description: "Swap any node with createApp overrides for fast, isolated tests."
---
Any provider or step is addressable by its **token**, so you can swap it for a test double
at construction time — no monkey-patching, no module rewiring.
## Override tokens in tests
Pass `overrides` to `createApp`. Each key is a token; each value is either a plain object
(wrapped as `{ token: value }`) or a function runner:
```typescript
const app = createApp({
modules: [ApiModule],
overrides: {
db: { find: () => ({ id: 'test-user' }) }, // plain object — wrapped as { db: value }
user: () => ({ user: { id: 'stub' } }), // function runner
},
});
```
Overrides replace **only** the named token's runner; the rest of the graph is untouched. The
route still runs its full closure — you've just substituted what one node produces.
:::note
An override for an unknown token throws. The set of tokens is validated against the real
graph, so a typo'd or stale override is a construction-time error, not a silent no-op.
:::
This pairs well with [`app.explain(route)`](/docs/guides/introspection/) — explain the chain to
see which tokens a route actually depends on, then override exactly those.
@@ -1,71 +0,0 @@
---
title: File uploads
description: "multipart parsing via the optional busboy peer dependency."
---
A request with `Content-Type: multipart/form-data` makes `@body()` resolve to `{ fields, files }` instead of a plain object.
:::caution[multipart needs the optional `busboy` peer]
Multipart parsing uses the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency — install it with `npm i busboy`. A `multipart/form-data` request to a server without busboy installed returns **`501`**. (JSON and urlencoded need nothing extra.)
:::
```typescript
import { Route, Post, body } from '@green-tea/core';
import type { MultipartBody } from '@green-tea/core';
@Route('/profile')
class ProfileController {
@Post('/avatar')
upload(@body() form: MultipartBody) {
const name = form.fields.name; // string | string[]
const avatar = form.files.avatar; // UploadedFile | UploadedFile[]
return { name, size: Array.isArray(avatar) ? undefined : avatar?.size };
}
}
```
`UploadedFile` is `{ filename, contentType, data: Buffer, size }` — the whole file is buffered in memory, no temp files.
:::note[Access asymmetry]
For multipart, `@body('title')` returns `undefined` — the value lives at `body.fields.title`, not `body.title`, unlike JSON/urlencoded where `@body('title')` picks the value directly. Use `@body()` and read `.fields`/`.files`, or key into the envelope itself with `@body('fields')` / `@body('files')`. See [arguments](/docs/guides/arguments/) for how `@body()` behaves across content types.
:::
## Repeated fields — `bodyDuplicates`
By default, a repeated field name keeps the **last** value (`'last'`, matching urlencoded). Set `bodyDuplicates: 'array'` on `createApp` to accumulate repeats into a `string[]` instead — this applies to **both** urlencoded and multipart text fields:
```typescript
const app = createApp({ modules: [ApiModule], bodyDuplicates: 'array' });
```
Files under a repeated field name always become an array (`UploadedFile[]`), regardless of `bodyDuplicates`.
## Per-endpoint override
```typescript
@Post('/upload', { duplicates: 'array' })
upload(@body() form: MultipartBody) { /* ... */ }
```
Precedence: route `duplicates` → app `bodyDuplicates` → `'last'`.
## Limits
Uploaded files are held in memory, so they're bounded by the same `maxBodyBytes` limit as any other request body (over the limit → **413**). `maxParts` (default `1000`) caps the number of multipart parts per request:
```typescript
const app = createApp({ modules: [ApiModule], limits: { maxParts: 500 } });
```
Both limits can be overridden **per route** — an upload endpoint can allow a larger body than the rest of the API:
```typescript
@Post('/avatar', { maxBodyBytes: 5_000_000, maxParts: 20 })
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**.
:::note
To validate parsed fields against a schema, pass a Standard Schema to `@body()` — see [validation](/docs/guides/validation/).
:::
@@ -1,84 +0,0 @@
---
title: Validation
description: "Validate and coerce input with Standard Schema (zod, valibot, arktype)."
---
`@body`, `@query`, `@headers`, and `@param` accept an optional **Standard Schema**
(the [`~standard` interface](https://standardschema.dev) shared by zod, valibot, arktype,
and others). green-tea's core has **zero runtime dependency** on any of them — bring
whichever validator you already use.
```typescript
import { z } from 'zod';
import { Route, Post, body } from '@green-tea/core';
const CreateUser = z.object({ email: z.string().email() });
@Route('/users')
class UserController {
@Post('/')
create(@body(CreateUser) user: { email: string }) {
return { created: user.email };
}
}
```
## Parsed value replaces the argument; `ctx` stays raw
The value the handler receives is the schema's **parsed/coerced output**, not the raw
input — `ctx.body` (via `@ctx()` or a `@needs`-fed step) stays exactly what the transport
parsed. Query strings are always strings on the wire, so a schema is often the coercion
point:
```typescript
const ListQuery = z.object({ page: z.coerce.number() });
@Get('/list')
list(@query(ListQuery) q: { page: number }) {
return { page: q.page, isNum: typeof q.page === 'number' }; // GET /list?page=2 → true
}
```
## Where the schema goes (the one asymmetry)
:::note[Access shape]
`@param('id', Schema)` takes the key in slot 1 and the schema in slot 2 — `@param` always
needs a name to say which route param it binds. `@body(Schema)`, `@query(Schema)`, and
`@headers(Schema)` take the schema as their **only** argument, validating the whole parsed
object (all of `body`/`query`/`headers`).
:::
See [Argument decorators](/docs/guides/arguments/) for the full slot semantics of each decorator.
## Failure: 422 with per-field issues
A failing schema short-circuits the request with **422**:
```json
{ "error": "Validation failed", "source": "body", "issues": [{ "path": "email", "message": "Invalid email" }] }
```
`source` is which envelope failed (`'body' | 'query' | 'params' | 'headers'`); `issues` is
the schema's issues flattened to `{ path, message }` (`path` is dot-joined).
## Caveats
- **Fail-fast.** Arguments validate in order; the **first** failing one throws — later args in
the same handler are not checked in that request.
- **Steps see raw input.** Only the resolved handler argument is coerced/validated; a `@Step`
reading the same data via `ctx.body`/`ctx.query`/etc. always sees the untouched value.
- **A throwing schema is a 500, not a 422.** The Standard Schema contract says `validate()`
returns `{ issues }` on failure — it isn't supposed to throw. If it does anyway, that
propagates as an uncaught error (→ 500), since it signals a bug in the schema, not user input.
- **Async schemas are awaited** — `validate()` returning a `Promise` works transparently.
:::note[Not covered yet]
Response/output validation, validating a `@Step`'s own inputs, and mesh remote-route
validation are all out of scope for this feature.
:::
## Related
- [Argument decorators](/docs/guides/arguments/) — every slot decorator and its parsing rules
- [File uploads / multipart](/docs/guides/uploads/) — how multipart bodies are parsed before validation
- [`createApp` reference](/docs/reference/createapp/) — app construction options
-47
View File
@@ -1,47 +0,0 @@
---
title: Green Tea.
description: A zen, opinionated, type-safe framework — your API is a graph you can see, slice, and trust, not a chain.
template: splash
hero:
image:
file: ../../assets/logo.svg
alt: Green 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:
- text: Get started
link: /docs/getting-started/
icon: right-arrow
variant: primary
- text: The idea
link: /docs/concepts/the-graph/
icon: open-book
variant: minimal
---
import { Card, CardGrid } from '@astrojs/starlight/components';
## Less to hold in your head
Most frameworks make you keep the whole request in your head: which middleware ran, whether `req.user` exists by now, what fired in what order. green-tea puts the request **on the page** — you declare what each step _needs_ and _produces_, and the framework computes the order, type-checks the wiring, and can print the whole thing.
<CardGrid stagger>
<Card title="A graph, not a chain" icon="puzzle">
Declare `needs`/`provides`; green-tea topologically sorts it. No ordering bugs, no positional guesswork — each route runs only its slice of the graph.
</Card>
<Card title="The type is the contract" icon="approve-check">
In the typed `flow` core, a handler that reads `ctx.user` **fails to compile** if no step produces `user`. "It was undefined in prod" disappears at build time.
</Card>
<Card title="See the request before it runs" icon="magnifier">
`app.explain('/users/:id')` prints the ordered chain; `GET /__graph__` renders it as a live diagram. Onboarding and audits are reading, not archaeology.
</Card>
<Card title="One primitive for real-time" icon="rocket">
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 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>
:::note[Beta]
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.
:::
@@ -1,85 +0,0 @@
---
title: createApp options
description: "Every option accepted by createApp and every method on the App it returns."
---
```typescript
const app = createApp(options);
```
## Options
| Option | Type | Default | Meaning |
|---|---|---|---|
| `modules` | `Ctor[]` | — | the `@Module` classes to wire (required) |
| `plugins` | `Plugin[]` | `[]` | plugins, each limited to `bus.on` + `scope.add` ([plugins](/docs/guides/plugins/)) |
| `limits` | `RequestLimits` | see below | body-size and timeout ceilings |
| `devGraph` | `boolean` | `false` | mount `GET /__graph__` ([introspection](/docs/guides/introspection/)) |
| `devOpenapi` | `boolean` | `false` | mount `GET /__openapi__` serving the [OpenAPI](/docs/guides/openapi/) document |
| `overrides` | `Record<string, unknown>` | — | swap any node by token ([testing](/docs/guides/testing/)) |
| `tls` | `TlsOptions` | — | serve over https/wss |
| `trustProxy` | `boolean` | `false` | honor `X-Forwarded-*` for `ctx.protocol` / `ctx.ip` |
| `security` | `boolean \| SecurityOptions` | `true` | secure-by-default headers ([security](/docs/guides/security/)) |
| `cors` | `CorsOptions` | — | CORS handling |
| `bodyDuplicates` | `'array' \| 'last'` | `'last'` | policy for repeated form fields |
| `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](/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](/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](/docs/guides/html/)) |
| `logger` | `Logger` | structured JSON (readable on a TTY) | where every framework diagnostic is written; also injectable as `@needs('logger')` ([observability](/docs/guides/observability/)) |
| `logRequests` | `boolean` | `false` | log one line per completed request and per failure; a removable Bus subscriber, not a middleware ([observability](/docs/guides/observability/)) |
| `shutdownTimeoutMs` | `number` | `10_000` | how long `close()` gives in-flight work before forcing the rest shut; `close({ timeoutMs })` still wins per call. Set it here when `close()` is reached from a signal handler or shutdown hook you do not own ([runtimes](/docs/guides/runtimes/)) |
| `mesh` | `MeshConfig` | — | distributed DI — **requires `experimental: true`** ([mesh](/docs/guides/mesh/)) |
| `experimental` | `boolean` | `false` | opt in to alpha features (currently gates `mesh`) |
| `warnGraphDepth` | `number \| false` | `20` | warn when one route resolves to more than this many steps; `false` disables the design warning |
### `RequestLimits`
| Field | Default |
|---|---|
| `maxBodyBytes` | `1_000_000` (→ `413` when exceeded) |
| `maxConnections` | `1000` (Node only; `<= 0` means unlimited) |
| `requestTimeoutMs` | `30_000` |
| `headersTimeoutMs` | `10_000` |
| `keepAliveTimeoutMs` | `5_000` |
| `maxParts` | `1000` (multipart) |
### `TlsOptions`
`{ key, cert, ca?, passphrase? }` — `key`/`cert` are `Buffer | string`.
### `CorsOptions`
`{ origins, methods?, allowedHeaders?, exposedHeaders?, credentials?, maxAge? }`. `origins` is a string, array, `'*'`, or a `(origin) => boolean` predicate. `credentials: true` is never combined with `'*'`.
### `SecurityOptions`
`{ hsts?, frameOptions?, referrerPolicy?, noSniff?, dnsPrefetchControl?, csp? }`. HSTS is only emitted on secure connections. `csp` is opt-in.
### `MeshConfig`
`{ secret?, teapots?, timeoutMs?, 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`
`createApp` returns an `App`:
| Member | Returns | Notes |
|---|---|---|
| `listen(port)` | `Promise<http.Server>` | boots providers, then serves |
| `close({ timeoutMs? })` | `Promise<void>` | drains in-flight, closes streams + mesh links; after the deadline (default `10s`, or `createApp({ shutdownTimeoutMs })`) it warns and force-closes what is left. Node-only — see [runtimes](/docs/guides/runtimes/) |
| `ready()` | `Promise<void>` | resolves the graph and mesh links without booting providers |
| `fetch(request)` | `Promise<Response>` | Web-Standards HTTP/SSE handler for Node, Deno, Bun, and edge |
| `upgrade(request, socket)` | `Promise<void>` | neutral WebSocket upgrade used by non-Node adapters |
| `inspect(route)` | `InspectLine[]` | the provider/step/handler chain for a route |
| `explain(route)` | `Explain` | the chain annotated with each node's needs/provides |
| `graph()` | `GraphView` | the full node + route graph |
| `toMermaid()` / `toDOT()` | `string` | render the graph |
| `openapi(info?)` | `OpenApiDoc` | structural OpenAPI 3.1 document ([details](/docs/guides/openapi/)) |
| `degraded()` | `string[]` | optional providers running degraded (empty until providers boot through `fetch`, `upgrade`, or `listen`) |
| `bus` | `Bus` | lifecycle + request event bus ([observability](/docs/guides/observability/)) |
| `logger` | `Logger` | the app's logger — the one passed in, or the default |
:::note
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.
:::
@@ -1,98 +0,0 @@
---
title: Decorators
description: "Full reference for every class, method, and argument decorator."
---
Every decorator green-tea exports, grouped by where it applies. All require `experimentalDecorators: true` in your `tsconfig` — see [Why legacy decorators](/docs/concepts/the-graph/#why-legacy-decorators).
## Structure
### `@Module(options)`
Marks a class as a module and records what it wires together.
```typescript
@Module({
mountpoint: '/api', // path prefix for this module's controllers (required)
providers: [Database], // app-scope @Provider classes
steps: [Authenticate], // request-scope @Step classes
controllers: [UserCtl], // @Route classes
})
class ApiModule {}
```
### `@Route(prefix)`
Marks a class as a controller; `prefix` is prepended to each route path.
## Providers & steps
### `@Provider(options)`
An app-scope value, built once at boot and cached, addressable by `provides`.
| Option | Type | Default | Meaning |
|---|---|---|---|
| `provides` | `string` | — | the token this provider produces (required) |
| `needs` | `string[]` | `[]` | tokens it depends on |
| `optional` | `boolean` | `false` | if it throws on boot, degrade instead of aborting ([details](/docs/guides/dependency-injection/)) |
| `export` | `boolean` | `false` | expose over the mesh control channel ([mesh](/docs/guides/mesh/)) |
### `@Step(options)`
A request-scope transform that merges keys into the context. Same options as `@Provider`.
### `@Transformer(fn)`
Method decorator. Turns a handler's return value into `{ status?, headers?, body }`. `JsonTransformer` is the default.
### `@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](/docs/guides/html/)):
| Form | Behavior |
|---|---|
| `@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', { 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.
## 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`](/docs/reference/createapp/) for this route only.
| Decorator | Method | Transport |
|---|---|---|
| `@Get` `@Head` `@Post` `@Put` `@Patch` `@Delete` `@Options` | as named | buffered response |
| `@Sse` | GET | `text/event-stream` |
| `@Ws` | GET | WebSocket duplex |
| `@Stream` | GET | negotiated (SSE / ndjson / WS) |
```typescript
@Get('/ping', { export: true }) // exportable over mesh
@Post('/upload', { duplicates: 'array' }) // repeated form fields → arrays
@Post('/avatar', { maxBodyBytes: 5_000_000, maxParts: 20 }) // per-route upload limits
```
See [Routing](/docs/guides/routing/) for pattern matching and [Streaming](/docs/guides/streaming/) for the transports.
`@Head` and `@Options` declare explicit handlers. When they are absent, the router can provide an implicit buffered-GET HEAD response or an automatic `204` OPTIONS response; those fallbacks are runtime behavior, not decorator metadata.
## Arguments
A handler's signature declares exactly what it wants, in any order.
| Decorator | Injects | Forms |
|---|---|---|
| `@needs('user')` | a graph-produced value (boot-validated) | `('key')` |
| `@ctx()` | the whole accumulated context | `()` |
| `@param(...)` | route params | `()` · `('id')` · `('id', schema)` |
| `@query(...)` | parsed query string | `()` · `('q')` · `(['a','b'])` · `(schema)` |
| `@body(...)` | parsed body (JSON / urlencoded / multipart) | `()` · `('field')` · `(schema)` |
| `@headers(...)` | request headers (whole bag or picked) | `()` · `('authorization')` · `(['a','b'])` · `(schema)` |
| `@header('name')` | one request header (singular alias of `@headers`) | `('x-trace')` · `('x-count', schema)` |
| `@inbound()` | the incoming message stream (WebSocket) | `()` |
| `@abort()` | the request's `AbortSignal` | `()` |
Passing a [Standard Schema](/docs/guides/validation/) validates and coerces the value before the handler sees it. Full details in [Argument decorators](/docs/guides/arguments/).
-32
View File
@@ -1,32 +0,0 @@
/* Green Tea. — brand theme for Starlight */
@import url('https://fonts.googleapis.com/css2?family=Zen+Maru+Gothic:wght@500;700&display=swap');
/* Accent = matcha (dark theme in :root, light overridden below) */
:root {
--sl-color-accent-low: #14352a;
--sl-color-accent: #348a5f;
--sl-color-accent-high: #b9e8cf;
--sl-color-text-accent: #6fc599;
--gt-purple: #a78bfa;
}
:root[data-theme='light'] {
--sl-color-accent-low: #d3efe1;
--sl-color-accent: #2f8a5f;
--sl-color-accent-high: #123528;
--sl-color-text-accent: #2f8a5f;
--gt-purple: #7c6cf0;
}
/* Brand type: Zen Maru for the site title and headings */
.site-title,
h1, h2, h3 {
font-family: 'Zen Maru Gothic', var(--sl-font, sans-serif);
}
.site-title { font-weight: 700; }
.site-title img { height: 1.7rem; width: auto; }
/* Splash hero logo */
.hero img { max-height: 190px; width: auto; }
/* A little zen: soften the accent link underlines */
a { text-underline-offset: 0.15em; }
-5
View File
@@ -1,5 +0,0 @@
{
"extends": "astro/tsconfigs/strict",
"include": [".astro/types.d.ts", "**/*"],
"exclude": ["dist"]
}