Compare commits
154
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
180de79462 | ||
|
|
4f504eda11 | ||
|
|
94ab334d85 | ||
|
|
3a8d93320d | ||
|
|
270480b2d6 | ||
|
|
27f1d103ea | ||
|
|
0ad53fa284 | ||
|
|
5fccd3cc8c | ||
|
|
9398a5a2df | ||
|
|
29aafde84c | ||
|
|
dbb996dd4c | ||
|
|
f45ee7d309 | ||
|
|
00aef4541b | ||
|
|
bd3b2556bc | ||
|
|
87c1226e97 | ||
|
|
1db4e01e40 | ||
|
|
74f09d2e0b | ||
|
|
fcd3df7022 | ||
|
|
934fbd4c19 | ||
|
|
d9276a4769 | ||
|
|
3a56e656bd | ||
|
|
a2acec69bf | ||
|
|
9a61ba8646 | ||
|
|
63be0ef8f7 | ||
|
|
8e38fffd77 | ||
|
|
790db661e5 | ||
|
|
63a61aeb0b | ||
|
|
e343ae501f | ||
|
|
e0212d14e5 | ||
|
|
ab6b1b1ef2 | ||
|
|
1a313c21ad | ||
|
|
3ff90b418d | ||
|
|
8e822cad17 | ||
|
|
3fe0016dbd | ||
|
|
8bd2a3f61c | ||
|
|
96d863d402 | ||
|
|
33df70730b | ||
|
|
5fc37a2df7 | ||
|
|
2a84331022 | ||
|
|
91fe8f8aff | ||
|
|
3a4cd5a7ce | ||
|
|
642ef109b2 | ||
|
|
4081106813 | ||
|
|
b72883c2ed | ||
|
|
489aa685bb | ||
|
|
c12be9a2f5 | ||
|
|
0541464093 | ||
|
|
502b2c6b72 | ||
|
|
dba40b0c8b | ||
|
|
5e7d952f45 | ||
|
|
9886e53747 | ||
|
|
34dbb32b2c | ||
|
|
033af2d1fc | ||
|
|
a74417494f | ||
|
|
0c68cba532 | ||
|
|
db9a7712af | ||
|
|
0ea4db3fef | ||
|
|
71b59e7c25 | ||
|
|
87772868ab | ||
|
|
dd0ea91a1b | ||
|
|
d56eeafcd8 | ||
|
|
9421b102d9 | ||
|
|
922700674c | ||
|
|
44cf547f1b | ||
|
|
76267b74ec | ||
|
|
2b646eaec6 | ||
|
|
535392baba | ||
|
|
4d1ff33f74 | ||
|
|
f613a6427b | ||
|
|
35861f0fc1 | ||
|
|
2d6306b318 | ||
|
|
289ca5f8ff | ||
|
|
ad3a06f057 | ||
|
|
b8ebb9d04b | ||
|
|
e1a2c3253b | ||
|
|
da5cc936a3 | ||
|
|
e54de8c1db | ||
|
|
df13a62d93 | ||
|
|
6833293ccf | ||
|
|
cb4ecd6801 | ||
|
|
70925035d7 | ||
|
|
a4c9df9a74 | ||
|
|
9344cc7d43 | ||
|
|
86c206d2c9 | ||
|
|
82824e5f6d | ||
|
|
3d21117a07 | ||
|
|
4351b41038 | ||
|
|
fd6446f514 | ||
|
|
8d3a4ca420 | ||
|
|
4a6ef784ec | ||
|
|
47b7bf5f24 | ||
|
|
f85b39c2c3 | ||
|
|
e9357efb5c | ||
|
|
12eccd941c | ||
|
|
d72452d9b6 | ||
|
|
7a8be39d57 | ||
|
|
5e68d2de65 | ||
|
|
179a58f0e4 | ||
|
|
0aab3ed123 | ||
|
|
58853e8ba8 | ||
|
|
43a4316a29 | ||
|
|
1fee7de543 | ||
|
|
b75f127b2c | ||
|
|
08cb8554e6 | ||
|
|
93a4246de5 | ||
|
|
fc75cc05e5 | ||
|
|
16823408c7 | ||
|
|
118eb5516d | ||
|
|
9d97443847 | ||
|
|
aaafe76d8f | ||
|
|
27a984f070 | ||
|
|
2db5de6858 | ||
|
|
7c20d74fe4 | ||
|
|
40d3390ddb | ||
|
|
654c0563fc | ||
|
|
d6c5cee0ee | ||
|
|
9d79972f62 | ||
|
|
3ca4c8680e | ||
|
|
bb960ee669 | ||
|
|
0df82479ee | ||
|
|
5bab8da84b | ||
|
|
c0c6e7fa57 | ||
|
|
1abcc51620 | ||
|
|
90359e3907 | ||
|
|
fe1831a80a | ||
|
|
7593d1425a | ||
|
|
daa13f6f78 | ||
|
|
926ca3901c | ||
|
|
32b0087650 | ||
|
|
768d8d0fd5 | ||
|
|
92ca5f96da | ||
|
|
67133ca4ce | ||
|
|
1fdb7e11e5 | ||
|
|
b8670772e9 | ||
|
|
0f11ad1e61 | ||
|
|
456dd52df8 | ||
|
|
eb494ff254 | ||
|
|
101833d52d | ||
|
|
81dc9d3a70 | ||
|
|
9316397694 | ||
|
|
97284935aa | ||
|
|
34017f6ab2 | ||
|
|
ec2e3a0e62 | ||
|
|
5808da8012 | ||
|
|
0f7932c696 | ||
|
|
d2d4fc1d21 | ||
|
|
258130bf30 | ||
|
|
cb77216a53 | ||
|
|
0982873462 | ||
|
|
04da79721f | ||
|
|
0dba41606a | ||
|
|
b8ee1b14a5 | ||
|
|
b87bdc698f | ||
|
|
881bc59419 |
No files matched your search
Executable
+17
@@ -0,0 +1,17 @@
|
||||
#!/bin/sh
|
||||
# Pre-commit gate. Auto-fixes formatting/lint on staged source, then enforces
|
||||
# lint + cognitive-complexity. Enabled via `git config core.hooksPath .githooks`
|
||||
# (run automatically by the `prepare` npm script on install).
|
||||
set -e
|
||||
|
||||
# Auto-fix format + lint on staged TypeScript sources, then re-stage them.
|
||||
staged=$(git diff --cached --name-only --diff-filter=ACM -- 'src/*.ts' 'src/**/*.ts')
|
||||
if [ -n "$staged" ]; then
|
||||
echo "$staged" | xargs npx prettier --write
|
||||
echo "$staged" | xargs npx eslint --fix
|
||||
echo "$staged" | xargs git add
|
||||
fi
|
||||
|
||||
# Enforce (no auto-fix): lint must be clean, and no function over the complexity gate.
|
||||
npm run lint
|
||||
npm run complexity:check
|
||||
@@ -13,6 +13,16 @@ jobs:
|
||||
with:
|
||||
node-version: '18'
|
||||
- run: npm ci
|
||||
- run: npm audit
|
||||
- run: npm run lint
|
||||
- run: npm run format:check
|
||||
- run: npm run complexity:check
|
||||
- run: npm run typecheck
|
||||
- run: npm test
|
||||
- run: npm run build
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22.12'
|
||||
- run: npm ci --prefix website
|
||||
- run: npm audit --prefix website
|
||||
- run: npm run docs:build
|
||||
@@ -0,0 +1,30 @@
|
||||
name: Promote → GitHub
|
||||
|
||||
# Promotion. Runs on GITEA ONLY. Mirrors ONLY `main` + version tags to the public GitHub
|
||||
# repo — develop and feature branches stay Gitea-private (this is why we don't use Gitea's
|
||||
# push-mirror, which would expose every branch). A pushed tag lands on GitHub and triggers
|
||||
# its release workflow (production publish).
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ['v*']
|
||||
|
||||
jobs:
|
||||
push-github:
|
||||
if: ${{ github.server_url != 'https://github.com' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # full history + tags for a clean push
|
||||
- name: Push main + tags to GitHub
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GH_PROMOTE_TOKEN }}
|
||||
run: |
|
||||
git remote add github "https://x-access-token:${GH_TOKEN}@github.com/Expressive-Tea/green-tea.git"
|
||||
if [ "${{ github.ref_type }}" = "tag" ]; then
|
||||
git push github "refs/tags/${{ github.ref_name }}"
|
||||
else
|
||||
git push github "HEAD:refs/heads/main"
|
||||
git push github --tags
|
||||
fi
|
||||
@@ -0,0 +1,35 @@
|
||||
name: Release → npmjs
|
||||
|
||||
# Production publish. Runs on GITHUB ONLY, on a version tag (`v*`). Publishes the stable
|
||||
# package to npmjs via OIDC **Trusted Publishing** — no long-lived token. Requires a trusted
|
||||
# publisher configured on npmjs for this package (org Expressive-Tea, repo green-tea,
|
||||
# workflow release.yml). npm also attaches build provenance automatically.
|
||||
on:
|
||||
push:
|
||||
tags: ['v*']
|
||||
|
||||
jobs:
|
||||
publish-prod:
|
||||
if: ${{ github.server_url == 'https://github.com' }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
id-token: write # OIDC for Trusted Publishing (also enables provenance)
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
- run: npm install -g npm@latest # npm >= 11.5.1 is required for OIDC trusted publishing
|
||||
- run: npm ci
|
||||
- run: npm audit
|
||||
# `npm publish` runs prepublishOnly (lint + complexity + typecheck + test + build) first.
|
||||
# No NODE_AUTH_TOKEN — npm exchanges the OIDC id-token for a short-lived publish token.
|
||||
# A prerelease (26.7.0-beta.N) publishes under its channel tag (beta/alpha/rc) so `latest`
|
||||
# never points at a beta; a stable version publishes under `latest`.
|
||||
- name: Publish
|
||||
run: |
|
||||
TAG=$(node -e "const v=require('./package.json').version;const m=v.match(/-([a-z]+)/);console.log(m?m[1]:'latest')")
|
||||
echo "dist-tag: $TAG"
|
||||
npm publish --access public --tag "$TAG"
|
||||
@@ -0,0 +1,35 @@
|
||||
name: Stage → Verdaccio
|
||||
|
||||
# Staging publish. Runs on GITEA ONLY (the `if` guards against GitHub) for release
|
||||
# branches. Publishes prereleases to the internal Verdaccio under the `stg` dist-tag.
|
||||
# Staging versions are intentionally mutable: an existing prerelease is removed before
|
||||
# publishing the updated release candidate under the same version.
|
||||
on:
|
||||
push:
|
||||
branches: ['release/**']
|
||||
|
||||
jobs:
|
||||
publish-stg:
|
||||
if: ${{ github.server_url != 'https://github.com' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
- run: npm ci
|
||||
- run: npm audit
|
||||
- name: Validate release candidate
|
||||
run: npm run prepublishOnly
|
||||
- name: Publish prerelease to Verdaccio
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_AUTH }}
|
||||
run: |
|
||||
npm config set //npm.svc.zoit.services/:_authToken "$NODE_AUTH_TOKEN"
|
||||
VER=$(node -p "require('./package.json').version")
|
||||
case "$VER" in
|
||||
*-*) ;;
|
||||
*) echo "Refusing to stage non-prerelease version: $VER" >&2; exit 1 ;;
|
||||
esac
|
||||
npm unpublish "@green-tea/core@$VER" --registry https://npm.svc.zoit.services --force 2>/dev/null || true
|
||||
npm publish --ignore-scripts --registry https://npm.svc.zoit.services --tag stg
|
||||
@@ -10,3 +10,10 @@ coverage/
|
||||
# Env
|
||||
.env
|
||||
.env.*
|
||||
|
||||
# Astro (docs site)
|
||||
.astro/
|
||||
website/dist/
|
||||
|
||||
# Edge (Miniflare) test bundle artifact
|
||||
test/edge/_worker.mjs
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"printWidth": 120,
|
||||
"tabWidth": 2,
|
||||
"singleQuote": true,
|
||||
"semi": true,
|
||||
"trailingComma": "all",
|
||||
"arrowParens": "always"
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
> **TL;DR**: `raw-http` posted the highest median req/s in the first benchmarked scenario on this box — see the single-box caveat below before reading anything into the absolute numbers.
|
||||
|
||||
# green-tea Benchmarks
|
||||
|
||||
## Environment
|
||||
|
||||
- **Date**: 2026-07-07
|
||||
- **Commit**: fe1831a
|
||||
- **Node**: v22.22.2
|
||||
- **OS**: darwin
|
||||
- **CPU**: Apple M4 Max (16 cores)
|
||||
- **RAM**: 69 GB
|
||||
- **Core-pinned**: no
|
||||
- **autocannon config**: 100 connections, 5s duration, 3 runs (1 warmup discarded), pipelining 1
|
||||
|
||||
> **A note on honesty: this is a single-box benchmark.** All frameworks were driven with autocannon over
|
||||
> loopback on the same machine, sharing the same cores as the server processes they measured. That
|
||||
> contention overstates absolute throughput for every framework and compresses the differences *between*
|
||||
> frameworks — do not read the raw req/s numbers as what you would see on separate client/server hardware.
|
||||
> The honest takeaway is the **ratio** between frameworks in the same table, not any single absolute
|
||||
> number. Note also that green-tea runs with `security:false` in the cross-framework tables below, purely
|
||||
> for response-header parity with the other frameworks (none of which set the same security headers by
|
||||
> default) — the real cost of running green-tea secure-by-default is measured separately in its own
|
||||
> section further down.
|
||||
|
||||
## Cross-framework scenarios
|
||||
|
||||
### JSON hello (overhead)
|
||||
|
||||
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| raw-http | 115,398 | 0.00 | 1.00 | 1.00 | 0.3% | 114,822–115,539 |
|
||||
| green-tea | 98,093 | 0.00 | 1.00 | 2.00 | 0.3% | 98,054–98,669 |
|
||||
| nestjs-fastify | 95,034 | 1.00 | 1.00 | 2.00 | 0.5% | 94,240–95,264 |
|
||||
| fastify | 86,765 | 1.00 | 2.00 | 2.00 | 0.3% | 86,496–87,123 |
|
||||
| express | 24,366 | 3.00 | 5.00 | 8.00 | 0.2% | 24,283–24,418 |
|
||||
| nestjs-express | 21,762 | 4.00 | 6.00 | 10.00 | 0.4% | 21,698–21,896 |
|
||||
|
||||
### Route param
|
||||
|
||||
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| raw-http | 116,333 | 0.00 | 1.00 | 1.00 | 0.2% | 115,974–116,410 |
|
||||
| green-tea | 93,434 | 1.00 | 2.00 | 2.00 | 0.2% | 93,152–93,613 |
|
||||
| nestjs-fastify | 89,312 | 1.00 | 2.00 | 2.00 | 0.1% | 89,235–89,530 |
|
||||
| fastify | 86,278 | 1.00 | 2.00 | 2.00 | 0.3% | 86,138–86,765 |
|
||||
| express | 23,835 | 3.00 | 5.00 | 8.00 | 0.5% | 23,803–24,046 |
|
||||
| nestjs-express | 20,955 | 4.00 | 6.00 | 11.00 | 0.6% | 20,949–21,202 |
|
||||
|
||||
### Pipeline (3 steps) (approximation)
|
||||
|
||||
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| raw-http | 113,491 | 0.00 | 1.00 | 1.00 | 0.8% | 112,531–114,810 |
|
||||
| nestjs-fastify | 87,328 | 1.00 | 2.00 | 2.00 | 0.4% | 86,867–87,661 |
|
||||
| fastify | 85,024 | 1.00 | 2.00 | 2.00 | 0.3% | 84,512–85,178 |
|
||||
| green-tea | 84,896 | 1.00 | 2.00 | 2.00 | 0.5% | 84,243–85,267 |
|
||||
| express | 23,950 | 3.00 | 5.00 | 8.00 | 0.2% | 23,902–24,011 |
|
||||
| nestjs-express | 20,824 | 4.00 | 6.00 | 11.00 | 0.1% | 20,805–20,878 |
|
||||
|
||||
### POST JSON + validation
|
||||
|
||||
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| raw-http | 100,141 | 0.00 | 1.00 | 2.00 | 0.2% | 99,846–100,294 |
|
||||
| green-tea | 77,178 | 1.00 | 2.00 | 2.00 | 0.1% | 77,126–77,254 |
|
||||
| fastify | 63,722 | 1.00 | 2.00 | 3.00 | 0.1% | 63,574–63,760 |
|
||||
| nestjs-fastify | 59,146 | 1.00 | 3.00 | 3.00 | 0.3% | 59,005–59,376 |
|
||||
| express | 20,098 | 4.00 | 6.00 | 12.00 | 0.2% | 20,056–20,174 |
|
||||
| nestjs-express | 18,856 | 5.00 | 7.00 | 30.00 | 0.5% | 18,853–19,067 |
|
||||
|
||||
## Step-scaling (green-tea)
|
||||
|
||||
| Path | Steps | req/s |
|
||||
| --- | --- | --- |
|
||||
| /steps/0 | 0 | 92,282 |
|
||||
| /steps/3 | 3 | 81,530 |
|
||||
| /steps/5 | 5 | 71,994 |
|
||||
|
||||
Each additional pipeline step costs roughly 4,058 req/s (-22.0% over 5 steps), on this box.
|
||||
|
||||
## Cost of secure-by-default (green-tea)
|
||||
|
||||
| Label | req/s |
|
||||
| --- | --- |
|
||||
| security:false (parity) | 98,093 |
|
||||
| security:true (default) | 92,998 |
|
||||
|
||||
The real cost of running secure-by-default (rather than the parity-mode `security:false` used above) is ~5.2% req/s on this box.
|
||||
|
||||
> Scope: this micro-bench currently measures the security-**headers** cost only (`security:false` vs
|
||||
> `security:true` on `/hello`). The incremental cost of `@body` validation and CORS is not separately
|
||||
> measured yet (deferred) — so this table is narrower than the design spec's 4-point plan.
|
||||
|
||||
## Methodology
|
||||
|
||||
- **Parity controls**: every framework is configured for the fairest possible comparison —
|
||||
security-header parity (matching header sets across frameworks, or green-tea running with
|
||||
`security:false` in the cross-framework tables), keep-alive parity, and Express's `etag` and
|
||||
`x-powered-by` disabled. The `/validate` scenario always sends a valid body so every framework
|
||||
takes its success path and performs equivalent validation work.
|
||||
- **Pipeline approximation**: scenarios marked `(approximation)` (e.g. the multi-step pipeline route)
|
||||
do not have an exact one-to-one equivalent in every framework; the closest reasonable approximation
|
||||
is used for each framework and the result should be read as indicative, not as an exact apples-to-apples
|
||||
measurement.
|
||||
- **Serialization parity**: all four frameworks serialize their JSON responses with plain
|
||||
`JSON.stringify` in these benchmarks. Fastify's `fast-json-stringify` response serializer is
|
||||
deliberately **not** engaged — only its input `schema.body` validation is used — so no framework
|
||||
gets a serialization fast path the others lack.
|
||||
- **Content-type charset asymmetry (disclosed, not controlled)**: green-tea and raw-http send
|
||||
`Content-Type: application/json` while Express and Fastify send `application/json; charset=utf-8`.
|
||||
This is a minor header-byte asymmetry that is disclosed here rather than normalized away.
|
||||
- **NestJS runs on an underlying adapter** (Express or Fastify): the `nestjs-express` / `nestjs-fastify`
|
||||
rows measure Nest's DI / decorator / routing overhead **on top of** that adapter, so compare each
|
||||
against its own base (`express` / `fastify`) rather than against the field. Nest's idiomatic
|
||||
`ValidationPipe` / class-validator is **not** used — `/validate` performs the same manual field check
|
||||
as every other server (parity). The same parity controls apply: `etag` and `x-powered-by` are disabled
|
||||
on the underlying Express instance, and `keepAliveTimeout` is 5000 on both adapters.
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to `@green-tea/core` are documented here.
|
||||
|
||||
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
green-tea uses calendar versioning: `YY.M.PATCH` — the month is not zero-padded, since
|
||||
npm treats versions as semver and semver forbids leading zeros.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [26.8.0-beta.0] - 2026-08-02
|
||||
|
||||
### Added
|
||||
- **Safe constrained route parameters:** patterns such as `:id(\d+)` match a complete decoded
|
||||
segment. The parser accepts a deliberately small, bounded regex subset and rejects unsafe or
|
||||
malformed expressions at boot. Specificity is now static ▸ constrained param ▸ plain param ▸
|
||||
catch-all; matching remains a linear scan.
|
||||
- **`@Head` and `@Options` route decorators**, explicit-handler priority, buffered-GET HEAD fallback,
|
||||
and automatic `204` OPTIONS responses with deterministic `Allow` ordering. GET implies HEAD and
|
||||
every existing path implies OPTIONS; streaming GET routes do not become implicit HEAD routes.
|
||||
- **OpenAPI route constraints and methods:** constrained path params emit `schema.pattern`, and
|
||||
explicitly declared HEAD/OPTIONS handlers appear as operations without inventing automatic ones.
|
||||
- **HTML / views:** `@Html` decorator (string, file, and template modes), a zero-dep built-in
|
||||
template engine (`{{ }}` escaped / `{{{ }}}` raw, exported as `render`) with a `viewEngine`
|
||||
bring-your-own hook, and zero-config `static` directory serving (`createApp({ static: true })`).
|
||||
File and static serving require a filesystem (Node/Deno/Bun); string-mode `@Html` runs everywhere.
|
||||
- **`app.fetch(request): Promise<Response>`** — a Web-Standards handler so the
|
||||
same app runs HTTP and SSE on Deno/Bun/edge runtimes via the Fetch API.
|
||||
- **Deno adapter** (`@green-tea/core/deno`): `serveDeno(app)` runs HTTP + SSE + WebSocket on Deno.
|
||||
- **Bun adapter** (`@green-tea/core/bun`): `serveBun(app)` runs HTTP + SSE + WebSocket on Bun, reusing the neutral `app.upgrade` / `WsSocket` capability. WebSocket, rooms, and channels behave identically to Node and Deno.
|
||||
- **Cloudflare Workers / edge adapter** (`@green-tea/core/edge`): `edgeHandler(app)` runs HTTP + SSE + WebSocket on workerd, reusing the neutral `app.upgrade` / `WsSocket` capability. Requires the `nodejs_compat` compatibility flag. Green Tea now runs on Node, Deno, Bun, and the edge — with identical WebSocket, rooms, and channel behaviour on all four.
|
||||
- **`app.upgrade(request, socket)`**: neutral WebSocket entry point for non-Node runtimes, built on a shared `WsSocket` capability. WebSocket logic is now runtime-agnostic (`src/http/ws-core.ts`).
|
||||
- **Mesh (alpha) runs on Node, Deno and Bun** — teapot *and* teacup, in any combination
|
||||
(a Deno teapot can serve a Node teacup). It no longer needs `app.listen()`: the graph boots on
|
||||
first use, so `serveDeno`/`serveBun` work through `app.fetch`/`app.upgrade`. Edge is **not**
|
||||
supported — the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which
|
||||
`nodejs_compat` does not provide.
|
||||
- **`MESH_PROTOCOL_VERSION`**: the mesh wire is versioned. Peers exchange it in the `hello`/`manifest`
|
||||
frames and refuse a mismatch, naming both versions, instead of misreading each other's frames.
|
||||
The teapot checks the version *before* the secret — a skewed peer is not an auth failure.
|
||||
- **`HttpError` accepts `headers`**, so a custom error can carry its own response headers
|
||||
(`retry-after`, `etag`, …) without a special case in the error renderer.
|
||||
- **`app.ready(): Promise<void>`** — resolves the dependency graph and returns. On a mesh app it
|
||||
connects the teapots and splices their scopes in; on every other app it is a no-op, so
|
||||
`await app.ready()` before `inspect()`/`graph()`/`explain()` works against either kind without
|
||||
knowing which you were handed. It 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 boots them too and shares the same memoized step.
|
||||
|
||||
- **Mesh heartbeat** (`mesh.heartbeatMs`, default 15s): each teacup pings its teapots and closes a
|
||||
link after two unanswered rounds, so a half-open connection surfaces as an immediate 503 rather
|
||||
than every request paying `timeoutMs` first. Ping/pong are mesh frames, not WebSocket protocol
|
||||
pings — the platform `WebSocket` on Deno/Bun does not expose `ws.ping()`.
|
||||
|
||||
### Fixed
|
||||
- The Deno WebSocket adapter snapshots request and connection metadata before accepting an upgrade;
|
||||
Deno 2.9 invalidates that metadata once upgraded, which previously broke WebSocket and mesh boots.
|
||||
- Repeated slashes and malformed path encoding now return `400` consistently across Node and Fetch
|
||||
adapters, retaining configured security/CORS headers. `/path` and `/path/` remain equivalent.
|
||||
- Ambiguous same-method route shapes now fail at boot with both declarations named. Effective-shape
|
||||
checks also cover remote mesh conflicts and local routes that shadow a remote export.
|
||||
- HEAD responses always suppress the body while preserving handler status and headers; Fetch
|
||||
responses also avoid constructing forbidden bodies for `204`, `205`, and `304` statuses.
|
||||
- The opt-in dev routes `/__graph__` (graph viewer) and `/__openapi__` are now
|
||||
served over `app.fetch` too, so they work on every runtime (Deno/Bun/edge),
|
||||
not only the Node `app.listen()` path.
|
||||
- **A teapot with a live control channel could never shut down.** Mesh control connections were
|
||||
not registered with the stream registry, so `server.close()` waited on a connected teacup that
|
||||
had no reason to hang up, and `app.close()` never resolved.
|
||||
- **A downed teapot now answers 503 immediately** instead of hanging for the full `timeoutMs`
|
||||
(30s by default) and then answering 500. A closed socket cannot deliver the frame, so the wait
|
||||
bought nothing. An RPC that times out on a live link is now 504, not 500 — a dead upstream and
|
||||
a slow one are different operational stories, and neither is "this service broke".
|
||||
- **`request:step:enter`/`leave` are now emitted for `@Ws` and mesh routes.** Only HTTP routes
|
||||
emitted them, so a logging plugin silently observed nothing on a WebSocket route — a gap in a
|
||||
documented plugin API. All transports now run their steps through one path.
|
||||
- **A mesh route exported by two teapots now fails the boot**, naming both effective patterns and
|
||||
both teapots, instead of silently serving whichever connected first and leaving the other dead.
|
||||
There is no load balancing to fall back on, so green-tea will not pick for you.
|
||||
- **A local route shadowing a remote one now warns.** Local still takes precedence — that is how you
|
||||
override a teapot — but a silently shadowed export used to look like a broken teapot.
|
||||
- **`app.close()` closes mesh links even with no server**, so a mesh app booted through `app.fetch`
|
||||
(every Deno/Bun deployment) no longer leaks its teapot connections.
|
||||
- **WebSocket frames arriving during boot are no longer dropped.** `app.upgrade` awaited the boot
|
||||
before handing the socket to a consumer, and the inbound channel is fan-out, so a peer that spoke
|
||||
first lost those frames — for mesh, that was the handshake itself.
|
||||
- The plugins guide documented a `request:step:exit` event that has never existed; the bus emits
|
||||
`request:step:leave`.
|
||||
|
||||
### Changed
|
||||
- Root, runtime-only, and website dependency audits are clean after supported package updates and
|
||||
narrow pins for vulnerable transitives. CI audits root + website trees and builds the docs; the
|
||||
GitHub OIDC release workflow audits immediately before its publish gate.
|
||||
- App-scope providers now boot exactly once (memoized): a second `app.listen()`
|
||||
call no longer re-runs provider factories or their side effects.
|
||||
- **`WsOpenCtx.req`** (available in `@Ws`/`@Sse` handlers) is now a neutral
|
||||
`WsRequest` (`{ url, headers, protocol, ip }`) instead of the Node
|
||||
`http.IncomingMessage`, so it works the same across Node and Deno. Node-only
|
||||
fields such as `req.socket` / `req.rawHeaders` are no longer available on
|
||||
`ctx.req`; use `ctx.protocol` / `ctx.ip` / `ctx.query` / `ctx.headers`
|
||||
instead — all still provided.
|
||||
- **Breaking (pre-1.0): transport is now enforced by declaration.** A buffered route
|
||||
(`@Get`/`@Head`/`@Post`/`@Put`/`@Patch`/`@Delete`/`@Options`) whose handler returns an
|
||||
`AsyncIterable`, or a streaming route (`@Sse`/`@Ws`) whose handler returns a plain value, now
|
||||
fails with a 500 `TransportMismatchError` instead of silently switching behavior. `@Stream`
|
||||
still negotiates both. Declare `@Sse`/`@Stream`/`@Ws` to stream — a return value no longer
|
||||
changes a route's wire contract.
|
||||
|
||||
## [26.7.0-beta.0] - 2026-07-07
|
||||
|
||||
First public beta, published under the npm `beta` dist-tag. The API may still
|
||||
change before the stable release.
|
||||
|
||||
### Added
|
||||
- **Transport security** — native TLS termination (https/wss), CORS with a
|
||||
guarded preflight and credentials-safe origins, secure-by-default response
|
||||
headers (nosniff, X-Frame-Options, Referrer-Policy, HSTS-when-secure), and
|
||||
proxy-aware `trustProxy` exposing `ctx.protocol` / `ctx.ip`.
|
||||
- **Input validation** — `@body/@query/@param/@headers` accept any
|
||||
[Standard Schema](https://standardschema.dev) (zod / valibot / arktype); the
|
||||
parsed value is passed to the handler, invalid input returns `422` with
|
||||
per-field issues. Core stays dependency-free.
|
||||
- **Body parsing** — JSON and `application/x-www-form-urlencoded` out of the
|
||||
box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via
|
||||
the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency
|
||||
(a multipart request without it returns `501`), with a configurable
|
||||
repeated-field policy (`bodyDuplicates`, per-route overridable) and a
|
||||
`maxParts` DoS bound.
|
||||
- **Routing** — `:name*` catch-all params, specificity-based precedence
|
||||
(static ▸ `:param` ▸ catch-all, independent of registration order), and
|
||||
`405 Method Not Allowed` with an `Allow` header when a path exists under a
|
||||
different method.
|
||||
- **Argument decorators** — `@needs/@ctx/@param/@query/@body/@headers/@inbound/
|
||||
@abort`, plus `@header('name')` as a singular alias of `@headers`.
|
||||
- **Streams** — SSE / ndjson / WebSocket duplex over a multicast
|
||||
`AsyncIterable` channel, with backpressure and cleanup; `rooms` broadcast hubs.
|
||||
- **Graph introspection** — `app.explain(route)`, `app.graph()`,
|
||||
`app.toMermaid()` / `toDOT()`, and an opt-in `GET /__graph__` dev endpoint.
|
||||
- **Operational hardening** — request body/size limits (`413`), request and
|
||||
keep-alive timeouts, and `app.close()` graceful shutdown (drains in-flight
|
||||
requests, closes live streams and mesh links).
|
||||
- **Visible degradation** — optional providers that fail at boot are
|
||||
summarized on `listen()` and queryable via `app.degraded()`, instead of a
|
||||
silent warning.
|
||||
- **Testing ergonomics** — `createApp({ overrides })` swaps any provider/step
|
||||
by token in one line.
|
||||
- **Mesh (alpha, walking skeleton)** — `teapot`/`teacup` distributed dependency
|
||||
injection over a secret-gated WebSocket control channel. Gated behind
|
||||
`experimental: true`; `createApp` throws if `mesh` is configured without it.
|
||||
- **Packaging** — dual **ESM + CommonJS** builds behind an `exports` map, with
|
||||
matching type declarations; one runtime dependency (`reflect-metadata`),
|
||||
`ws` and `busboy` optional peers.
|
||||
- **Benchmarks** — reproducible `npm run bench` harness vs Express 5, Fastify 5,
|
||||
NestJS, and raw `http`; results in [BENCHMARKS.md](./BENCHMARKS.md).
|
||||
|
||||
[Unreleased]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.0...main
|
||||
[26.8.0-beta.0]: https://github.com/Expressive-Tea/green-tea/compare/v26.7.0-beta.0...v26.8.0-beta.0
|
||||
[26.7.0-beta.0]: https://github.com/Expressive-Tea/green-tea/releases/tag/v26.7.0-beta.0
|
||||
@@ -1,28 +1,130 @@
|
||||
# 🍵 green-tea
|
||||
<p align="center">
|
||||
<img src="./assets/logo.png" width="112" alt="Green Tea" />
|
||||
</p>
|
||||
|
||||
> A declarative, type-safe HTTP framework for Node. The request pipeline is an explicit **dependency graph**, not a mutable middleware chain.
|
||||
<h1 align="center">Green Tea.</h1>
|
||||
|
||||
`@green-tea/core` — **alpha**. Zero runtime dependencies beyond `reflect-metadata` (`ws` is an optional peer dep, only for WebSocket/mesh on Node).
|
||||
<p align="center"><b>A zen, opinionated, type-safe framework.</b></p>
|
||||
|
||||
## Documentation
|
||||
<p align="center">
|
||||
Your API is an explicit <b>dependency graph</b> you can see, slice, and trust —<br />
|
||||
not a mutable bag threaded through positional middleware. <i>That's the tea.</i> 🍵
|
||||
</p>
|
||||
|
||||
- **[Quickstart](./docs/quickstart.md)** — install + concrete examples (routes/DI, `flow`, SSE, WebSocket, mesh, plugins).
|
||||
- **[Architecture](./docs/architecture.md)** — the mental map (layers, request lifecycle, mesh) as diagrams.
|
||||
---
|
||||
|
||||
## Why
|
||||
## The problem
|
||||
|
||||
Express/Fastify middleware is positional, untyped, and globally mutable: order depends on the line you wrote `app.use()` on, `req.user` may or may not exist, and a plugin can quietly delete your body parser. green-tea replaces that model:
|
||||
```js
|
||||
const user = req.user;
|
||||
```
|
||||
|
||||
- **Declarative, not positional.** You declare what each step *needs* and *produces*. The graph order is computed at boot via topological sort — there is no "put this before that".
|
||||
- **The type is the contract.** What a handler reads from the context *is* its dependency declaration. The typed `flow` core makes a handler that reads `ctx.user` **fail to compile** if no step produces `user`.
|
||||
- **Structural plugin isolation.** Plugins get only `bus.on(...)` (observe) and `scope.add(...)` (extend their own scope). There is no API to reorder or delete another scope's steps.
|
||||
- **Response = return value.** No `Response.json()`. Return data; a `@Transformer` serializes it in a leave phase. Cut a request by `throw`ing a typed signal.
|
||||
- **Fail-fast boot.** A required provider that can't initialize (e.g. the DB) stops the server from serving — no 500s because a resource wasn't ready.
|
||||
It compiles. TypeScript is happy. And it's a prayer — `req.user` exists only if some middleware ran before this handler, which depends on where the router got mounted, which line `app.use()` sits on, and whether a package you installed last sprint quietly inserted itself into the middle of your chain.
|
||||
|
||||
So you keep the whole request in your head: what ran, what's on `req` by now, what order things fire in, which plugin deleted your body parser. That bookkeeping is where the bugs live, and no test or type catches them, because nothing is *wrong* — the code is correct and the app is still broken.
|
||||
|
||||
## The idea
|
||||
|
||||
green-tea puts the request on the page instead. You declare what each step **needs** and **produces**; the framework computes the order, type-checks the wiring, and can print the whole thing.
|
||||
|
||||
- Order is **derived** from your dependencies, never maintained by hand.
|
||||
- Boot **fails loudly** when nothing provides a key, so you never serve `undefined`.
|
||||
- A route runs **only** the steps its handler actually depends on.
|
||||
- `app.explain('/users/:id')` prints the whole chain. Onboarding is reading, not archaeology.
|
||||
|
||||
Less to hold in your head. That's the tea.
|
||||
|
||||
```bash
|
||||
npm install @green-tea/core@beta reflect-metadata
|
||||
```
|
||||
|
||||
`@green-tea/core` — **beta**, RC-track. One runtime dependency: `reflect-metadata`. Two optional peers you install only if you use them:
|
||||
|
||||
```bash
|
||||
npm install ws # WebSocket routes (@Ws) and mesh
|
||||
npm install busboy # multipart/form-data file uploads
|
||||
```
|
||||
|
||||
## What's different — and why it matters
|
||||
|
||||
- **The pipeline is a graph, not a chain.** You never write "put this before that." You declare `needs`/`provides` and green-tea topologically sorts it. *Why it matters:* no ordering bugs, no positional guesswork, and each route runs only its slice of the graph (an auth step doesn't run on public routes).
|
||||
- **The type is the contract.** What a handler reads from the context *is* its dependency list. In the typed `flow` core, a handler that reads `ctx.user` **fails to compile** if no step produces `user`. *Why it matters:* whole classes of "it was undefined in prod" disappear at compile time.
|
||||
- **You can see the request before it runs.** `app.explain('/users/:id')` prints the ordered chain with origins; `app.graph()` / `GET /__graph__` render it as a live diagram; `app.openapi()` projects the same metadata into an OpenAPI 3.1 spec. *Why it matters:* onboarding, debugging, audits, and API docs are reading, not archaeology. (NestJS puts the graph behind a paid Devtools plan.)
|
||||
- **One primitive for real-time.** Declare the transport — SSE, ndjson, or a WebSocket duplex — and return an `AsyncIterable`; backpressure and cleanup are handled. *Why it matters:* no separate gateway, adapter, or library to bolt on.
|
||||
- **The same app runs on Node, Deno, Bun, and the edge.** One codebase, one import; you swap the entry point (`app.listen` → `serveDeno` / `serveBun` / `edgeHandler`) and nothing else. HTTP, SSE, and WebSocket — including rooms and channels — behave identically on all four. *Why it matters:* the graph model isn't a bet on one runtime's future, and no other opinionated/DI framework runs everywhere.
|
||||
- **A remote dependency looks like a local one.** `@needs('billing')` resolves the same whether `billing` lives in this process or on another node (mesh, experimental). *Why it matters:* no gRPC layer or message-pattern DSL to learn — there's the graph, and some nodes happen to live elsewhere.
|
||||
- **Plugins can't sabotage you.** A plugin gets `bus.on(...)` (observe) and `scope.add(...)` (extend its own scope). There is no API to reorder or delete another scope's steps. *Why it matters:* installing a plugin can't break your body parser.
|
||||
|
||||
## Real-time is a primitive, not a second framework
|
||||
|
||||
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.
|
||||
|
||||
| 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.
|
||||
|
||||
**Your wire contract is what you declared, never what you happened to return.** A buffered route that returns an iterable, or a streaming route that returns a plain value, fails loudly with a `TransportMismatchError` — green-tea will not quietly switch a route's transport because of a return type. Refactoring a handler's internals can't change how it talks to the client.
|
||||
|
||||
Fan-out is a primitive too: `channel()` is a **multicast** `AsyncIterable` (bounded, drop-oldest) so one source feeds many subscribers, and `rooms` are named broadcast hubs — publish once, every connection in the room receives it.
|
||||
|
||||
```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.
|
||||
|
||||
## Batteries included — still one dependency
|
||||
|
||||
Beta shipped the parts a real API needs, without growing the runtime dependency tree past `reflect-metadata`:
|
||||
|
||||
- **TLS → https/wss** natively, plus proxy-aware `trustProxy` (`X-Forwarded-*` → `ctx.protocol`/`ctx.ip`).
|
||||
- **Secure by default.** `nosniff`, `X-Frame-Options`, `Referrer-Policy`, HSTS-when-secure — on every response, opt-out with one flag.
|
||||
- **CORS** with a guarded preflight and the credentials-never-`*` rule enforced for you.
|
||||
- **Validation via [Standard Schema](https://standardschema.dev).** `@body(schema)` accepts zod, valibot, or arktype — you bring the validator, the core stays zero-dep. Invalid input → `422` with per-field issues; the parsed value reaches your handler typed.
|
||||
- **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS.
|
||||
- **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response.
|
||||
- **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency.
|
||||
- **Ceilings that are already on.** `limits` caps body size (`413`), multipart parts, and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. Configurable, and safe before you configure anything.
|
||||
- **Graceful shutdown.** `app.close()` drains in-flight requests, closes live streams and mesh links.
|
||||
- **Testable by construction.** `createApp({ overrides: { db: fakeDb } })` swaps any node in one line.
|
||||
- **Dual ESM + CommonJS.** Ships both builds behind an `exports` map — `import` and `require` both resolve, with matching type declarations.
|
||||
|
||||
## Benchmarks
|
||||
|
||||
We built a reproducible [autocannon harness](./BENCHMARKS.md) comparing green-tea to Express 5, Fastify 5, NestJS (on both Express and Fastify), and raw Node `http` — and we wrote it to be **hard on ourselves**, not flattering.
|
||||
|
||||
On that harness, **green-tea handled more requests per second than every other framework in 3 of 4 scenarios** (JSON response, routing, and body-parsing-plus-validation), behind only raw `http` with no framework at all. In the fourth (a multi-step pipeline) it lands even with Fastify.
|
||||
|
||||
Read the honest caveats in [BENCHMARKS.md](./BENCHMARKS.md): the numbers are single-box + loopback (absolute throughput is overstated and differences compressed — trust the *ratios*), the cross-framework table runs green-tea with `security:false` for header parity, and the real cost of secure-by-default is measured separately. Regenerate any time with `npm run bench`.
|
||||
|
||||
## How it compares
|
||||
|
||||
Every framework here can serve `/users/:id`. The difference is what happens when the app
|
||||
grows: more dependencies, real-time, and more than one machine.
|
||||
Every framework here can serve `/users/:id`. The difference shows up as the app grows: more dependencies, real-time, and more than one machine.
|
||||
|
||||
| | Express | Fastify | NestJS | expressive-tea | **green-tea** |
|
||||
|---|---|---|---|---|---|
|
||||
@@ -30,39 +132,19 @@ grows: more dependencies, real-time, and more than one machine.
|
||||
| **Order is decided by** | the line you wrote it on | hook phase + registration order | module/provider wiring | boot-stage order | **what each step *needs/produces*** |
|
||||
| **`req.user` exists?** | hope so | hope so | if the guard ran | if the middleware ran | **boot fails if nothing provides it** |
|
||||
| **Type safety** | none | schemas (runtime) | decorator types (runtime DI) | runtime | **compile-time in `flow`** + boot-validated decorators |
|
||||
| **Response** | `res.send()` (mutate) | `reply.send()` | return value | return value | **return value → `@Transformer`** |
|
||||
| **Real-time** | bolt on `ws`/`sse` libs | plugins | separate Gateway + adapter | separate engine | **return an `AsyncIterable`** — same primitive |
|
||||
| **See the pipeline** | read the code | read the code | paid Devtools | `inspect` | **`explain` / `graph` / `/__graph__` — free** |
|
||||
| **Real-time** | bolt on `ws`/`sse` libs | plugins | separate Gateway + adapter | separate engine | **return an `AsyncIterable`** — SSE, ndjson & WebSocket, one primitive |
|
||||
| **Cross-service calls** | HTTP client / gRPC by hand | HTTP client / gRPC | Microservices transport + message patterns | — | **`@needs('x')` resolves on another node** |
|
||||
| **Plugin can break your pipeline?** | yes (deletes your body parser) | encapsulated, but hooks are global | interceptor order matters | yes | **no** — plugins only `bus.on` + `scope.add` |
|
||||
| **Runtime deps** | minimal | minimal | heavy (rxjs, reflect-metadata, …) | Express + InversifyJS | **`reflect-metadata` only** (`ws` optional) |
|
||||
| **Runs on** | Node | Node | Node | Node | **Node · Deno · Bun · edge** — same code, swap the entry point |
|
||||
| **Runtime deps** | minimal | minimal | heavy (rxjs, reflect-metadata, …) | Express + InversifyJS | **`reflect-metadata` only** (`ws`, `busboy` optional) |
|
||||
|
||||
### Read it as a story
|
||||
|
||||
- **Express / Fastify** — fast and battle-tested, but the request is a *mutable bag* threaded
|
||||
through positional middleware. Order is implicit, `req.x` is a leap of faith, and a careless
|
||||
plugin can delete another's work. You wire types and DI yourself.
|
||||
- **NestJS** — brings DI, decorators, and structure, but the DI is *runtime token resolution*,
|
||||
it's a large opinionated dependency tree, and every new capability (WebSockets, gRPC,
|
||||
microservices) is a **separate subsystem** with its own abstraction (Gateways, transports,
|
||||
message patterns) to learn and glue.
|
||||
- **expressive-tea** — the sibling this project grew from: decorators + InversifyJS DI + boot
|
||||
stages on top of Express. green-tea keeps the ideas, drops Express and Inversify, and makes
|
||||
the graph — not the middleware chain — the core.
|
||||
- **green-tea** — one model answers three questions other stacks answer with three subsystems:
|
||||
- *"what does this handler depend on?"* → the graph (boot-validated, `flow` checks it at compile time)
|
||||
- *"how do I push data over time?"* → return an `AsyncIterable` (SSE / WebSocket, one primitive)
|
||||
- *"how do I call another service?"* → `@needs` a token that lives on another node (mesh)
|
||||
|
||||
A remote dependency looks **identical** to a local one. There is no gRPC layer, no
|
||||
message-pattern DSL, no separate WebSocket gateway — there is the graph, and some of its
|
||||
nodes happen to live on another machine.
|
||||
|
||||
### Honest scope
|
||||
|
||||
green-tea is **alpha**. Express/Fastify have a decade of ecosystem; NestJS has enterprise
|
||||
tooling and a huge plugin catalog. Mesh discovery, load-balancing, and failover are not built
|
||||
yet (the [walking skeleton](./docs/quickstart.md#5-mesh--distributed-dependency-injection) is).
|
||||
Pick green-tea for the model, not the ecosystem — *yet*.
|
||||
- **Express / Fastify** — fast and battle-tested, but the request is a *mutable bag* threaded through positional middleware. Order is implicit, `req.x` is a leap of faith, and a careless plugin can delete another's work. You wire types and DI yourself.
|
||||
- **NestJS** — brings DI, decorators, and structure, but the DI is *runtime token resolution*, it ships a large opinionated dependency tree, and every new capability (WebSockets, gRPC, microservices) is a **separate subsystem** with its own abstraction to learn and glue.
|
||||
- **expressive-tea** — the sibling this project grew from: decorators + InversifyJS + boot stages on top of Express. green-tea keeps the ideas, drops Express and Inversify, and makes the graph — not the middleware chain — the core.
|
||||
- **green-tea** — one model answers three questions other stacks answer with three subsystems: *what does this handler depend on?* → the graph; *how do I push data over time?* → an `AsyncIterable`; *how do I call another service?* → `@needs` a token that lives on another node.
|
||||
|
||||
## Quick look
|
||||
|
||||
@@ -102,7 +184,7 @@ class UserController {
|
||||
class ApiModule {}
|
||||
|
||||
const app = createApp({ modules: [ApiModule] });
|
||||
console.log(app.inspect('/api/users/:id')); // auditable: ordered chain with origins
|
||||
console.log(app.explain('/api/users/:id')); // auditable: the ordered chain, with origins
|
||||
app.listen(3000);
|
||||
```
|
||||
|
||||
@@ -119,34 +201,85 @@ The handler signature declares exactly what it wants — in any order, nothing m
|
||||
|---|---|---|
|
||||
| `@needs('user')` | a graph-produced value (boot-validated) | `('key')` |
|
||||
| `@ctx()` | the whole accumulated context | `()` |
|
||||
| `@param(...)` | route params | `()` · `('id')` · `(['a','b'])` |
|
||||
| `@query(...)` | parsed query string | `()` · `('q')` · `(['a','b'])` |
|
||||
| `@body(...)` | parsed JSON body | `()` · `('field')` · `(['a','b'])` |
|
||||
| `@headers(...)` | request headers | `()` · `('authorization')` · `(['a','b'])` |
|
||||
| `@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)` |
|
||||
|
||||
`@needs` keys are validated at boot: if nothing provides the key, `createApp` throws with a clear error instead of serving `undefined`.
|
||||
`@needs` keys are validated at boot: nothing provides the key → `createApp` throws with a clear error instead of serving `undefined`. Pass a Standard Schema (`@body(User)`) and the value is validated, coerced, and typed before your handler sees it.
|
||||
|
||||
> **Optional providers degrade, they don't crash.** A provider marked `optional: true` that throws on boot does **not** abort startup — it is left unregistered and logged. The first serving call (`fetch`, `upgrade`, or `listen`) prints a one-line summary of what's running degraded, and the list is queryable via `app.degraded()`. Routes that actually need a degraded provider fail at request time, not at boot. This is deliberate (graceful degradation); wire an alert off `app.degraded()` or the `boot:provider:fail` bus event in production so a degraded start is never silent.
|
||||
|
||||
## Routing
|
||||
|
||||
Patterns match by segment: static, constrained params such as `:id(\d+)`, plain `:param`, and a trailing `:name*` **catch-all**. The most specific wins (static ▸ constrained ▸ plain param ▸ catch-all), and ambiguous same-method shapes fail at boot instead of depending on registration order.
|
||||
|
||||
```typescript
|
||||
@Get('/users/:id(\\d+)') // /users/42
|
||||
@Get('/files/:path*') // /files/img/2026/logo.png → params.path = "img/2026/logo.png"
|
||||
```
|
||||
|
||||
`@Head` and `@Options` provide explicit handlers. Otherwise a buffered GET can serve HEAD without a body, and OPTIONS on an existing path returns `204` with canonical `Allow`; other method mismatches return `405`. `/path` and `/path/` are equivalent, while repeated slashes and malformed encoding return `400` rather than being normalized ambiguously. Constraints use a deliberately safe regex subset. See the full [routing guide](https://green-tea.expressive-tea.io/docs/guides/routing/).
|
||||
|
||||
Matching is still a linear scan — fine for typical route tables. A radix tree for very large tables remains post-beta work.
|
||||
|
||||
## Two layers
|
||||
|
||||
1. **Typed functional core (`flow`)** — `flow().step(...).step(...).handle(...)`; step outputs accumulate into the context type (`Acc & Out`). This is where the compile-time guarantee lives.
|
||||
2. **Declarative decorator layer** — `@Provider/@Step/@Module/@Route/@Get/@Transformer` + argument decorators. Emits runtime metadata, builds and topologically sorts the graph, validates at boot.
|
||||
|
||||
## Development
|
||||
## Why legacy decorators
|
||||
|
||||
green-tea uses **legacy** (experimental) decorators — you set `experimentalDecorators: true` in your `tsconfig`. This is a design decision, not inertia.
|
||||
|
||||
The framework's argument injection (`@param`, `@query`, `@body`, `@header`, `@needs`, `@ctx`, `@inbound`, `@abort`) relies on **parameter decorators** — and the TC39 standard decorators proposal (Stage 3) deliberately does **not** include them. There is no standards-track way to decorate a parameter today, so a handler like `handler(@param('id') id: string)` is only expressible with legacy decorators.
|
||||
|
||||
"Stage 3" also means *not finalized*: the proposal can still change before engines ship it. We track it, and if parameter injection ever gets a viable standard path we'll revisit. Until then, legacy decorators are the right tool for this API — not a shortcut. (We don't rely on `emitDecoratorMetadata`/`design:type` reflection; argument positions are recorded explicitly, so this is the only legacy surface we depend on.)
|
||||
|
||||
## Honest scope
|
||||
|
||||
green-tea is **beta**, on the road to a release candidate. Express and Fastify have a decade of ecosystem; NestJS has enterprise tooling and a huge plugin catalog. Pick green-tea for the model and the ergonomics, not the ecosystem — *yet*.
|
||||
|
||||
**Bring your own auth (and friends).** green-tea ships transport security — TLS/wss, secure-by-default headers, CORS — but **not** authentication, authorization, rate-limiting, CSRF, or sessions. You compose those as steps and plugins (the `Authenticate` step in the quick look is the pattern). Unlike Express/Fastify, there is no off-the-shelf plugin ecosystem for them yet.
|
||||
|
||||
**No observability layer, either.** There is no built-in logger, no metrics export, and no tracing hooks; core does not depend on a logging library and does not intend to. Today you compose those as steps and providers like anything else. A first-class contract — an injectable logger, structured output, and hooks an OpenTelemetry exporter can attach to — is [tracked as one design](https://github.com/Expressive-Tea/green-tea/issues/10), because doing it piecemeal produces three mechanisms that don't fit together. If your team's definition of production-ready includes shipping traces on day one, this is the gap to know about.
|
||||
|
||||
**Runtimes differ in what they can offer.** Node ≥ 18, Deno, and Bun run everything. On the edge (Cloudflare Workers) there is no `app.listen()`, no filesystem — so `@Html` file/template modes and `static` serving are unavailable — and mesh does not run there at all (the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which `nodejs_compat` doesn't provide). Workers also require the `nodejs_compat` flag.
|
||||
|
||||
**mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet.
|
||||
|
||||
## 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.
|
||||
- **[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
|
||||
npm install
|
||||
npm test # vitest
|
||||
npm test # vitest (Node); test:deno / test:bun / test:edge for the other runtimes
|
||||
npm run typecheck # tsc --noEmit (includes the compile-time-guarantee type test)
|
||||
npm run build # emit dist/
|
||||
npm run build # emit dist/ (tsup: dual ESM + CJS)
|
||||
npm run bench # regenerate BENCHMARKS.md
|
||||
npm run docs:dev # the documentation site (website/)
|
||||
```
|
||||
|
||||
## Roadmap
|
||||
|
||||
- ✅ **streams** — SSE / ndjson / WebSocket duplex over a multicast `AsyncIterable` channel. Return an `AsyncIterable` and the transport streams it (backpressure + cleanup). See the [quickstart](./docs/quickstart.md#3-streaming--sse).
|
||||
- ✅ **mesh (walking skeleton)** — `teapot`/`teacup`: a consumer resolves a scope/step or proxies a route living on another node, over a secret-gated WS control channel, via one id-correlated RPC. Remote tokens become synthetic graph nodes. Model: a BEAM/OTP-style cluster, *not* microservices. See the [quickstart](./docs/quickstart.md#5-mesh--distributed-dependency-injection).
|
||||
- **mesh sub-specs (next)** — discovery/auto-registration, 2-way load-balancing, failover/health.
|
||||
- **runtime adapters** — factor the transport behind an adapter so the core stays runtime-agnostic; Node / Deno / Bun / edge become thin adapters over web-standard `Request`/`Response`. Only `src/http.ts` is runtime-specific today.
|
||||
- official plugins (cors, body parsers, auth) — structurally unable to sabotage the global pipeline.
|
||||
- ✅ **transport security** — native TLS/wss, CORS, secure-by-default headers, `trustProxy`.
|
||||
- ✅ **request I/O** — JSON / urlencoded / multipart uploads, size limits, graceful shutdown, Standard Schema validation.
|
||||
- ✅ **streams** — SSE / ndjson / WebSocket duplex over a multicast `AsyncIterable` channel, with backpressure and cleanup.
|
||||
- ✅ **graph introspection** — `explain` / `graph` / `toMermaid` / `GET /__graph__`.
|
||||
- ✅ **mesh (walking skeleton)** — `teapot`/`teacup` distributed DI over a secret-gated WS control channel. A BEAM/OTP-style cluster, *not* microservices.
|
||||
- ✅ **runs everywhere** — Node, Deno, Bun, and Cloudflare Workers over web-standard `Request`/`Response`, with identical WebSocket behaviour on all four.
|
||||
- ✅ **HTML** — `@Html` (string / file / template), a built-in template engine with a bring-your-own `viewEngine` hook, and `static` serving.
|
||||
- ✅ **router completeness for beta** — safe constrained params, deterministic precedence, explicit/automatic HEAD and OPTIONS, strict path validation, and ambiguity checks across local and mesh routes.
|
||||
- **next** — API freeze + first published release, mesh sub-specs (discovery, load-balancing, failover), official plugins, and a radix-tree matcher for very large route tables.
|
||||
|
||||
## Versioning
|
||||
|
||||
green-tea uses **calendar versioning**: `YY.M.PATCH` (e.g. `26.8.0` = the first release cut in August 2026, patch 0). The month is **not** zero-padded — npm treats versions as semver, which forbids leading zeros. A version tells you *when* it shipped, not how many breaking changes preceded it — those are always called out in the [CHANGELOG](./CHANGELOG.md).
|
||||
|
||||
**While in beta**, releases carry a `-beta.N` pre-release suffix on the calendar version (e.g. `26.8.0-beta.0`) and publish under the npm `beta` dist-tag. Until the first stable release there is nothing else to install, so `latest` tracks the newest beta too — `npm install @green-tea/core` and `@green-tea/core@beta` resolve to the same version. Install with the explicit `@beta` tag anyway: the day a stable ships, `latest` moves to it and your installs stay on the channel you meant. The API can still change between betas.
|
||||
|
||||
## License
|
||||
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
<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="currentColor" transform="translate(501,80)"/>
|
||||
|
||||
<g stroke="currentColor" 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="currentColor">
|
||||
<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="currentColor"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.6 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 50 KiB |
@@ -0,0 +1,16 @@
|
||||
<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>
|
||||
|
After Width: | Height: | Size: 4.6 KiB |
+214
@@ -0,0 +1,214 @@
|
||||
export interface EnvInfo {
|
||||
date: string;
|
||||
commit: string;
|
||||
node: string;
|
||||
os: string;
|
||||
cpu: string;
|
||||
ram: string;
|
||||
pinned: boolean;
|
||||
}
|
||||
|
||||
export interface Config {
|
||||
conns: number;
|
||||
duration: number;
|
||||
runs: number;
|
||||
warmup: number;
|
||||
pipelining: number;
|
||||
}
|
||||
|
||||
export interface Row {
|
||||
framework: string;
|
||||
reqSec: { median: number; min: number; max: number; stddev: number; cv: number };
|
||||
p50: number;
|
||||
p99: number;
|
||||
p999: number;
|
||||
}
|
||||
|
||||
export interface ScenarioBlock {
|
||||
title: string;
|
||||
name: string;
|
||||
approximation?: boolean;
|
||||
rows: Row[];
|
||||
}
|
||||
|
||||
export interface RenderData {
|
||||
env: EnvInfo;
|
||||
config: Config;
|
||||
scenarios: ScenarioBlock[];
|
||||
stepScaling: { path: string; steps: number; reqSec: number }[];
|
||||
secureCost: { label: string; reqSec: number }[];
|
||||
}
|
||||
|
||||
const fmtInt = (n: number): string => Math.round(n).toLocaleString('en-US');
|
||||
const fmtLatency = (n: number): string => n.toFixed(2);
|
||||
const fmtCv = (n: number): string => `${(n * 100).toFixed(1)}%`;
|
||||
const fmtRange = (min: number, max: number): string => `${fmtInt(min)}–${fmtInt(max)}`;
|
||||
|
||||
function renderEnvSection(env: EnvInfo, config: Config): string {
|
||||
return [
|
||||
'## Environment',
|
||||
'',
|
||||
`- **Date**: ${env.date}`,
|
||||
`- **Commit**: ${env.commit}`,
|
||||
`- **Node**: ${env.node}`,
|
||||
`- **OS**: ${env.os}`,
|
||||
`- **CPU**: ${env.cpu}`,
|
||||
`- **RAM**: ${env.ram}`,
|
||||
`- **Core-pinned**: ${env.pinned ? 'yes' : 'no'}`,
|
||||
`- **autocannon config**: ${config.conns} connections, ${config.duration}s duration, ` +
|
||||
`${config.runs} runs (${config.warmup} warmup discarded), pipelining ${config.pipelining}`,
|
||||
'',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function renderCaveat(): string {
|
||||
return [
|
||||
'> **A note on honesty: this is a single-box benchmark.** All frameworks were driven with autocannon over',
|
||||
'> loopback on the same machine, sharing the same cores as the server processes they measured. That',
|
||||
"> contention overstates absolute throughput for every framework and compresses the differences *between*",
|
||||
'> frameworks — do not read the raw req/s numbers as what you would see on separate client/server hardware.',
|
||||
'> The honest takeaway is the **ratio** between frameworks in the same table, not any single absolute',
|
||||
'> number. Note also that green-tea runs with `security:false` in the cross-framework tables below, purely',
|
||||
'> for response-header parity with the other frameworks (none of which set the same security headers by',
|
||||
'> default) — the real cost of running green-tea secure-by-default is measured separately in its own',
|
||||
'> section further down.',
|
||||
'',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function renderScenarioTable(rows: Row[]): string {
|
||||
const sorted = [...rows].sort((a, b) => b.reqSec.median - a.reqSec.median);
|
||||
const header = '| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |';
|
||||
const divider = '| --- | --- | --- | --- | --- | --- | --- |';
|
||||
const lines = sorted.map((row) => {
|
||||
const { framework, reqSec, p50, p99, p999 } = row;
|
||||
return (
|
||||
`| ${framework} | ${fmtInt(reqSec.median)} | ${fmtLatency(p50)} | ${fmtLatency(p99)} | ` +
|
||||
`${fmtLatency(p999)} | ${fmtCv(reqSec.cv)} | ${fmtRange(reqSec.min, reqSec.max)} |`
|
||||
);
|
||||
});
|
||||
return [header, divider, ...lines].join('\n');
|
||||
}
|
||||
|
||||
function renderScenarios(scenarios: ScenarioBlock[]): string {
|
||||
return scenarios
|
||||
.map((scenario) => {
|
||||
const heading = `### ${scenario.title}${scenario.approximation ? ' (approximation)' : ''}`;
|
||||
return [heading, '', renderScenarioTable(scenario.rows), ''].join('\n');
|
||||
})
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
function renderStepScaling(stepScaling: RenderData['stepScaling']): string {
|
||||
const sorted = [...stepScaling].sort((a, b) => a.steps - b.steps);
|
||||
const header = '| Path | Steps | req/s |';
|
||||
const divider = '| --- | --- | --- |';
|
||||
const lines = sorted.map((row) => `| ${row.path} | ${row.steps} | ${fmtInt(row.reqSec)} |`);
|
||||
|
||||
let deltaNote = '';
|
||||
if (sorted.length >= 2) {
|
||||
const first = sorted[0];
|
||||
const last = sorted[sorted.length - 1];
|
||||
const stepDiff = last.steps - first.steps;
|
||||
if (stepDiff > 0) {
|
||||
const reqDiff = last.reqSec - first.reqSec;
|
||||
const perStep = reqDiff / stepDiff;
|
||||
const pct = first.reqSec ? (reqDiff / first.reqSec) * 100 : 0;
|
||||
deltaNote =
|
||||
`Each additional pipeline step costs roughly ${fmtInt(Math.abs(perStep))} req/s ` +
|
||||
`(${pct <= 0 ? '-' : ''}${Math.abs(pct).toFixed(1)}% over ${stepDiff} step${stepDiff === 1 ? '' : 's'}), ` +
|
||||
`on this box.`;
|
||||
}
|
||||
}
|
||||
|
||||
return ['## Step-scaling (green-tea)', '', header, divider, ...lines, '', deltaNote, ''].join('\n');
|
||||
}
|
||||
|
||||
function renderSecureCost(secureCost: RenderData['secureCost']): string {
|
||||
const header = '| Label | req/s |';
|
||||
const divider = '| --- | --- |';
|
||||
const lines = secureCost.map((row) => `| ${row.label} | ${fmtInt(row.reqSec)} |`);
|
||||
|
||||
let deltaNote = '';
|
||||
if (secureCost.length >= 2) {
|
||||
const baseline = secureCost[0];
|
||||
const withSecurity = secureCost[secureCost.length - 1];
|
||||
const reqDiff = baseline.reqSec - withSecurity.reqSec;
|
||||
const pct = baseline.reqSec ? (reqDiff / baseline.reqSec) * 100 : 0;
|
||||
deltaNote = `The real cost of running secure-by-default (rather than the parity-mode \`security:false\` used above) is ~${pct.toFixed(1)}% req/s on this box.`;
|
||||
}
|
||||
|
||||
return [
|
||||
'## Cost of secure-by-default (green-tea)',
|
||||
'',
|
||||
header,
|
||||
divider,
|
||||
...lines,
|
||||
'',
|
||||
deltaNote,
|
||||
'',
|
||||
'> Scope: this micro-bench currently measures the security-**headers** cost only (`security:false` vs',
|
||||
'> `security:true` on `/hello`). The incremental cost of `@body` validation and CORS is not separately',
|
||||
'> measured yet (deferred) — so this table is narrower than the design spec\'s 4-point plan.',
|
||||
'',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function renderMethodology(): string {
|
||||
return [
|
||||
'## Methodology',
|
||||
'',
|
||||
'- **Parity controls**: every framework is configured for the fairest possible comparison —',
|
||||
' security-header parity (matching header sets across frameworks, or green-tea running with',
|
||||
' `security:false` in the cross-framework tables), keep-alive parity, and Express\'s `etag` and',
|
||||
" `x-powered-by` disabled. The `/validate` scenario always sends a valid body so every framework",
|
||||
' takes its success path and performs equivalent validation work.',
|
||||
'- **Pipeline approximation**: scenarios marked `(approximation)` (e.g. the multi-step pipeline route)',
|
||||
" do not have an exact one-to-one equivalent in every framework; the closest reasonable approximation",
|
||||
' is used for each framework and the result should be read as indicative, not as an exact apples-to-apples',
|
||||
' measurement.',
|
||||
'- **Serialization parity**: all four frameworks serialize their JSON responses with plain',
|
||||
' `JSON.stringify` in these benchmarks. Fastify\'s `fast-json-stringify` response serializer is',
|
||||
' deliberately **not** engaged — only its input `schema.body` validation is used — so no framework',
|
||||
' gets a serialization fast path the others lack.',
|
||||
'- **Content-type charset asymmetry (disclosed, not controlled)**: green-tea and raw-http send',
|
||||
' `Content-Type: application/json` while Express and Fastify send `application/json; charset=utf-8`.',
|
||||
' This is a minor header-byte asymmetry that is disclosed here rather than normalized away.',
|
||||
'- **NestJS runs on an underlying adapter** (Express or Fastify): the `nestjs-express` / `nestjs-fastify`',
|
||||
" rows measure Nest's DI / decorator / routing overhead **on top of** that adapter, so compare each",
|
||||
' against its own base (`express` / `fastify`) rather than against the field. Nest\'s idiomatic',
|
||||
' `ValidationPipe` / class-validator is **not** used — `/validate` performs the same manual field check',
|
||||
' as every other server (parity). The same parity controls apply: `etag` and `x-powered-by` are disabled',
|
||||
' on the underlying Express instance, and `keepAliveTimeout` is 5000 on both adapters.',
|
||||
'',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function renderLeaderboard(scenarios: ScenarioBlock[]): string {
|
||||
const first = scenarios[0];
|
||||
if (!first || first.rows.length === 0) return '';
|
||||
const leader = [...first.rows].sort((a, b) => b.reqSec.median - a.reqSec.median)[0];
|
||||
return [
|
||||
`> **TL;DR**: \`${leader.framework}\` posted the highest median req/s in the first benchmarked scenario ` +
|
||||
`on this box — see the single-box caveat below before reading anything into the absolute numbers.`,
|
||||
'',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
export function renderMarkdown(data: RenderData): string {
|
||||
const { env, config, scenarios, stepScaling, secureCost } = data;
|
||||
|
||||
return [
|
||||
renderLeaderboard(scenarios),
|
||||
'# green-tea Benchmarks',
|
||||
'',
|
||||
renderEnvSection(env, config),
|
||||
renderCaveat(),
|
||||
'## Cross-framework scenarios',
|
||||
'',
|
||||
renderScenarios(scenarios),
|
||||
renderStepScaling(stepScaling),
|
||||
renderSecureCost(secureCost),
|
||||
renderMethodology(),
|
||||
].join('\n');
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
{
|
||||
"env": {
|
||||
"date": "2026-07-07",
|
||||
"commit": "fe1831a",
|
||||
"node": "v22.22.2",
|
||||
"os": "darwin",
|
||||
"cpu": "Apple M4 Max (16 cores)",
|
||||
"ram": "69 GB",
|
||||
"pinned": false
|
||||
},
|
||||
"config": {
|
||||
"conns": 100,
|
||||
"duration": 5,
|
||||
"runs": 3,
|
||||
"warmup": 1,
|
||||
"pipelining": 1
|
||||
},
|
||||
"scenarios": [
|
||||
{
|
||||
"title": "JSON hello (overhead)",
|
||||
"name": "hello",
|
||||
"rows": [
|
||||
{
|
||||
"framework": "raw-http",
|
||||
"reqSec": {
|
||||
"median": 115398.4,
|
||||
"min": 114822.4,
|
||||
"max": 115539.2,
|
||||
"stddev": 310.09010876768724,
|
||||
"cv": 0.0026905088104554075
|
||||
},
|
||||
"p50": 0,
|
||||
"p99": 1,
|
||||
"p999": 1
|
||||
},
|
||||
{
|
||||
"framework": "fastify",
|
||||
"reqSec": {
|
||||
"median": 86764.8,
|
||||
"min": 86496,
|
||||
"max": 87123.2,
|
||||
"stddev": 256.9227813090051,
|
||||
"cv": 0.002960121758353106
|
||||
},
|
||||
"p50": 1,
|
||||
"p99": 2,
|
||||
"p999": 2
|
||||
},
|
||||
{
|
||||
"framework": "express",
|
||||
"reqSec": {
|
||||
"median": 24366.4,
|
||||
"min": 24283.2,
|
||||
"max": 24417.6,
|
||||
"stddev": 55.38455460585383,
|
||||
"cv": 0.002273984274990166
|
||||
},
|
||||
"p50": 3,
|
||||
"p99": 5,
|
||||
"p999": 8
|
||||
},
|
||||
{
|
||||
"framework": "green-tea",
|
||||
"reqSec": {
|
||||
"median": 98092.8,
|
||||
"min": 98054.4,
|
||||
"max": 98668.8,
|
||||
"stddev": 281.0175795212842,
|
||||
"cv": 0.002859589501804015
|
||||
},
|
||||
"p50": 0,
|
||||
"p99": 1,
|
||||
"p999": 2
|
||||
},
|
||||
{
|
||||
"framework": "nestjs-express",
|
||||
"reqSec": {
|
||||
"median": 21761.6,
|
||||
"min": 21697.6,
|
||||
"max": 21896,
|
||||
"stddev": 82.67870880032535,
|
||||
"cv": 0.0037952010918943873
|
||||
},
|
||||
"p50": 4,
|
||||
"p99": 6,
|
||||
"p999": 10
|
||||
},
|
||||
{
|
||||
"framework": "nestjs-fastify",
|
||||
"reqSec": {
|
||||
"median": 95033.6,
|
||||
"min": 94240,
|
||||
"max": 95264,
|
||||
"stddev": 438.6166536839312,
|
||||
"cv": 0.00462452048886261
|
||||
},
|
||||
"p50": 1,
|
||||
"p99": 1,
|
||||
"p999": 2
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "Route param",
|
||||
"name": "param",
|
||||
"rows": [
|
||||
{
|
||||
"framework": "raw-http",
|
||||
"reqSec": {
|
||||
"median": 116332.8,
|
||||
"min": 115974.4,
|
||||
"max": 116409.6,
|
||||
"stddev": 189.66281191162406,
|
||||
"cv": 0.001631663389130871
|
||||
},
|
||||
"p50": 0,
|
||||
"p99": 1,
|
||||
"p999": 1
|
||||
},
|
||||
{
|
||||
"framework": "fastify",
|
||||
"reqSec": {
|
||||
"median": 86278.4,
|
||||
"min": 86137.6,
|
||||
"max": 86764.8,
|
||||
"stddev": 268.69839349476365,
|
||||
"cv": 0.003110165492522174
|
||||
},
|
||||
"p50": 1,
|
||||
"p99": 2,
|
||||
"p999": 2
|
||||
},
|
||||
{
|
||||
"framework": "express",
|
||||
"reqSec": {
|
||||
"median": 23835.2,
|
||||
"min": 23803.2,
|
||||
"max": 24046.4,
|
||||
"stddev": 107.89690552662897,
|
||||
"cv": 0.004515472130491916
|
||||
},
|
||||
"p50": 3,
|
||||
"p99": 5,
|
||||
"p999": 8
|
||||
},
|
||||
{
|
||||
"framework": "green-tea",
|
||||
"reqSec": {
|
||||
"median": 93433.6,
|
||||
"min": 93152,
|
||||
"max": 93612.8,
|
||||
"stddev": 189.6628119116206,
|
||||
"cv": 0.002030662686635119
|
||||
},
|
||||
"p50": 1,
|
||||
"p99": 2,
|
||||
"p999": 2
|
||||
},
|
||||
{
|
||||
"framework": "nestjs-express",
|
||||
"reqSec": {
|
||||
"median": 20955.2,
|
||||
"min": 20948.8,
|
||||
"max": 21201.6,
|
||||
"stddev": 117.69157432317111,
|
||||
"cv": 0.005594982425799189
|
||||
},
|
||||
"p50": 4,
|
||||
"p99": 6,
|
||||
"p999": 11
|
||||
},
|
||||
{
|
||||
"framework": "nestjs-fastify",
|
||||
"reqSec": {
|
||||
"median": 89312,
|
||||
"min": 89235.2,
|
||||
"max": 89529.6,
|
||||
"stddev": 124.68598780759793,
|
||||
"cv": 0.001395338811201841
|
||||
},
|
||||
"p50": 1,
|
||||
"p99": 2,
|
||||
"p999": 2
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "Pipeline (3 steps)",
|
||||
"name": "pipeline",
|
||||
"approximation": true,
|
||||
"rows": [
|
||||
{
|
||||
"framework": "raw-http",
|
||||
"reqSec": {
|
||||
"median": 113491.2,
|
||||
"min": 112531.2,
|
||||
"max": 114809.6,
|
||||
"stddev": 933.9810324031724,
|
||||
"cv": 0.008220892102882115
|
||||
},
|
||||
"p50": 0,
|
||||
"p99": 1,
|
||||
"p999": 1
|
||||
},
|
||||
{
|
||||
"framework": "fastify",
|
||||
"reqSec": {
|
||||
"median": 85024,
|
||||
"min": 84512,
|
||||
"max": 85177.6,
|
||||
"stddev": 284.55819947576623,
|
||||
"cv": 0.003351507726431956
|
||||
},
|
||||
"p50": 1,
|
||||
"p99": 2,
|
||||
"p999": 2
|
||||
},
|
||||
{
|
||||
"framework": "express",
|
||||
"reqSec": {
|
||||
"median": 23950.4,
|
||||
"min": 23902.4,
|
||||
"max": 24011.2,
|
||||
"stddev": 44.519758410046,
|
||||
"cv": 0.0018585004345727763
|
||||
},
|
||||
"p50": 3,
|
||||
"p99": 5,
|
||||
"p999": 8
|
||||
},
|
||||
{
|
||||
"framework": "green-tea",
|
||||
"reqSec": {
|
||||
"median": 84896,
|
||||
"min": 84243.2,
|
||||
"max": 85267.2,
|
||||
"stddev": 423.2825796347192,
|
||||
"cv": 0.004991414284012342
|
||||
},
|
||||
"p50": 1,
|
||||
"p99": 2,
|
||||
"p999": 2
|
||||
},
|
||||
{
|
||||
"framework": "nestjs-express",
|
||||
"reqSec": {
|
||||
"median": 20824,
|
||||
"min": 20804.8,
|
||||
"max": 20878.41,
|
||||
"stddev": 31.17605954717337,
|
||||
"cv": 0.001496278247605678
|
||||
},
|
||||
"p50": 4,
|
||||
"p99": 6,
|
||||
"p999": 11
|
||||
},
|
||||
{
|
||||
"framework": "nestjs-fastify",
|
||||
"reqSec": {
|
||||
"median": 87328,
|
||||
"min": 86867.2,
|
||||
"max": 87660.8,
|
||||
"stddev": 325.38753646827104,
|
||||
"cv": 0.0037278603866430907
|
||||
},
|
||||
"p50": 1,
|
||||
"p99": 2,
|
||||
"p999": 2
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "POST JSON + validation",
|
||||
"name": "validate",
|
||||
"rows": [
|
||||
{
|
||||
"framework": "raw-http",
|
||||
"reqSec": {
|
||||
"median": 100140.8,
|
||||
"min": 99846.4,
|
||||
"max": 100294.4,
|
||||
"stddev": 185.88177843875883,
|
||||
"cv": 0.0018570746103533369
|
||||
},
|
||||
"p50": 0,
|
||||
"p99": 1,
|
||||
"p999": 2
|
||||
},
|
||||
{
|
||||
"framework": "fastify",
|
||||
"reqSec": {
|
||||
"median": 63721.6,
|
||||
"min": 63574.4,
|
||||
"max": 63760,
|
||||
"stddev": 79.99288857281053,
|
||||
"cv": 0.0012560645345785087
|
||||
},
|
||||
"p50": 1,
|
||||
"p99": 2,
|
||||
"p999": 3
|
||||
},
|
||||
{
|
||||
"framework": "express",
|
||||
"reqSec": {
|
||||
"median": 20097.6,
|
||||
"min": 20056,
|
||||
"max": 20174.41,
|
||||
"stddev": 49.04789518646266,
|
||||
"cv": 0.0024390608203285337
|
||||
},
|
||||
"p50": 4,
|
||||
"p99": 6,
|
||||
"p999": 12
|
||||
},
|
||||
{
|
||||
"framework": "green-tea",
|
||||
"reqSec": {
|
||||
"median": 77177.61,
|
||||
"min": 77126.4,
|
||||
"max": 77254.4,
|
||||
"stddev": 52.602458962379814,
|
||||
"cv": 0.0006815013839797027
|
||||
},
|
||||
"p50": 1,
|
||||
"p99": 2,
|
||||
"p999": 2
|
||||
},
|
||||
{
|
||||
"framework": "nestjs-express",
|
||||
"reqSec": {
|
||||
"median": 18856,
|
||||
"min": 18852.8,
|
||||
"max": 19067.2,
|
||||
"stddev": 100.32338821143516,
|
||||
"cv": 0.005301010367660728
|
||||
},
|
||||
"p50": 5,
|
||||
"p99": 7,
|
||||
"p999": 30
|
||||
},
|
||||
{
|
||||
"framework": "nestjs-fastify",
|
||||
"reqSec": {
|
||||
"median": 59145.6,
|
||||
"min": 59004.8,
|
||||
"max": 59376,
|
||||
"stddev": 153.00625985741647,
|
||||
"cv": 0.002585636725423652
|
||||
},
|
||||
"p50": 1,
|
||||
"p99": 3,
|
||||
"p999": 3
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"stepScaling": [
|
||||
{
|
||||
"path": "/steps/0",
|
||||
"steps": 0,
|
||||
"reqSec": 92281.6
|
||||
},
|
||||
{
|
||||
"path": "/steps/3",
|
||||
"steps": 3,
|
||||
"reqSec": 81529.61
|
||||
},
|
||||
{
|
||||
"path": "/steps/5",
|
||||
"steps": 5,
|
||||
"reqSec": 71993.61
|
||||
}
|
||||
],
|
||||
"secureCost": [
|
||||
{
|
||||
"label": "security:false (parity)",
|
||||
"reqSec": 98092.8
|
||||
},
|
||||
{
|
||||
"label": "security:true (default)",
|
||||
"reqSec": 92998.4
|
||||
}
|
||||
]
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
import autocannon from 'autocannon';
|
||||
import { spawn, execSync } from 'child_process';
|
||||
import os from 'os';
|
||||
import { writeFileSync } from 'fs';
|
||||
import { SCENARIOS, STEP_ROUTES } from './scenarios';
|
||||
import { aggregate } from './stats';
|
||||
import { renderMarkdown, type RenderData, type Row, type ScenarioBlock } from './render';
|
||||
|
||||
const SMOKE = process.env.BENCH_SMOKE === '1';
|
||||
const CONNS = Number(process.env.BENCH_CONNS ?? 100);
|
||||
const DURATION = SMOKE ? 1 : Number(process.env.BENCH_DURATION ?? 10);
|
||||
const RUNS = SMOKE ? 1 : Number(process.env.BENCH_RUNS ?? 5);
|
||||
const WARMUP = SMOKE ? 0 : Number(process.env.BENCH_WARMUP ?? 1);
|
||||
|
||||
function log(msg: string): void {
|
||||
process.stderr.write(`[bench] ${msg}\n`);
|
||||
}
|
||||
|
||||
interface RunResult {
|
||||
reqSec: number;
|
||||
p50: number;
|
||||
p99: number;
|
||||
p999: number;
|
||||
}
|
||||
|
||||
async function spawnServer(
|
||||
name: string,
|
||||
extraEnv: Record<string, string> = {},
|
||||
): Promise<{ port: number; kill: () => Promise<void> }> {
|
||||
const child = spawn(process.execPath, ['--import', 'tsx', `bench/servers/${name}.ts`], {
|
||||
env: { ...process.env, TSX_TSCONFIG_PATH: 'bench/tsconfig.json', ...extraEnv },
|
||||
});
|
||||
let stderr = '';
|
||||
child.stderr.on('data', (d) => (stderr += d));
|
||||
const port = await new Promise<number>((resolve, reject) => {
|
||||
const t = setTimeout(() => {
|
||||
child.kill('SIGKILL');
|
||||
reject(new Error(`${name} failed to boot (no READY in 10s):\n${stderr}`));
|
||||
}, 10000);
|
||||
let buf = '';
|
||||
child.stdout.on('data', (d) => {
|
||||
buf += d;
|
||||
const m = /READY (\d+)/.exec(buf);
|
||||
if (m) {
|
||||
clearTimeout(t);
|
||||
resolve(Number(m[1]));
|
||||
}
|
||||
});
|
||||
child.on('exit', (code) => {
|
||||
clearTimeout(t);
|
||||
reject(new Error(`${name} exited early (code ${code}):\n${stderr}`));
|
||||
});
|
||||
});
|
||||
const kill = (): Promise<void> =>
|
||||
new Promise<void>((resolve) => {
|
||||
child.on('exit', () => resolve());
|
||||
child.kill('SIGTERM');
|
||||
setTimeout(() => {
|
||||
try {
|
||||
child.kill('SIGKILL');
|
||||
} catch {
|
||||
/* already dead */
|
||||
}
|
||||
}, 2000);
|
||||
});
|
||||
return { port, kill };
|
||||
}
|
||||
|
||||
async function bench(port: number, path: string, method: 'GET' | 'POST', body?: unknown): Promise<RunResult> {
|
||||
const r: any = await autocannon({
|
||||
url: `http://127.0.0.1:${port}${path}`,
|
||||
connections: CONNS,
|
||||
duration: DURATION,
|
||||
pipelining: 1,
|
||||
method,
|
||||
headers: body ? { 'content-type': 'application/json' } : undefined,
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
return { reqSec: r.requests.average, p50: r.latency.p50, p99: r.latency.p99, p999: r.latency.p99_9 };
|
||||
}
|
||||
|
||||
async function measure(port: number, path: string, method: 'GET' | 'POST', body?: unknown): Promise<RunResult[]> {
|
||||
for (let i = 0; i < WARMUP; i++) await bench(port, path, method, body); // discarded
|
||||
const runs: RunResult[] = [];
|
||||
for (let i = 0; i < RUNS; i++) runs.push(await bench(port, path, method, body));
|
||||
return runs;
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const frameworks = ['raw-http', 'fastify', 'express', 'green-tea', 'nestjs-express', 'nestjs-fastify'];
|
||||
const scenarioBlocks: ScenarioBlock[] = SCENARIOS.map((s) => ({
|
||||
title: s.title,
|
||||
name: s.name,
|
||||
approximation: s.approximation,
|
||||
rows: [],
|
||||
}));
|
||||
const stepScaling: RenderData['stepScaling'] = [];
|
||||
const secureCost: RenderData['secureCost'] = [];
|
||||
|
||||
for (const fw of frameworks) {
|
||||
log(`booting ${fw}`);
|
||||
const { port, kill } = await spawnServer(fw);
|
||||
try {
|
||||
for (const s of SCENARIOS) {
|
||||
log(`${fw} / ${s.name}`);
|
||||
const runs = await measure(port, s.path, s.method, s.body);
|
||||
const agg = aggregate(runs.map((r) => r.reqSec));
|
||||
const last = runs[runs.length - 1];
|
||||
const row: Row = {
|
||||
framework: fw,
|
||||
reqSec: { median: agg.median, min: agg.min, max: agg.max, stddev: agg.stddev, cv: agg.cv },
|
||||
p50: last.p50,
|
||||
p99: last.p99,
|
||||
p999: last.p999,
|
||||
};
|
||||
scenarioBlocks.find((b) => b.name === s.name)!.rows.push(row);
|
||||
}
|
||||
if (fw === 'green-tea') {
|
||||
for (const sr of STEP_ROUTES) {
|
||||
const runs = await measure(port, sr.path, 'GET');
|
||||
stepScaling.push({ path: sr.path, steps: sr.steps, reqSec: aggregate(runs.map((r) => r.reqSec)).median });
|
||||
}
|
||||
// Reuse the hello scenario's already-computed median so the parity row exactly matches
|
||||
// the green-tea hello-table number (rather than re-measuring the same server/config).
|
||||
const helloMedian = scenarioBlocks
|
||||
.find((b) => b.name === 'hello')!
|
||||
.rows.find((r) => r.framework === 'green-tea')!.reqSec.median;
|
||||
secureCost.push({ label: 'security:false (parity)', reqSec: helloMedian });
|
||||
}
|
||||
} finally {
|
||||
await kill();
|
||||
}
|
||||
}
|
||||
|
||||
log('booting green-tea (GT_SECURE=1)');
|
||||
{
|
||||
const { port, kill } = await spawnServer('green-tea', { GT_SECURE: '1' });
|
||||
try {
|
||||
secureCost.push({
|
||||
label: 'security:true (default)',
|
||||
reqSec: aggregate((await measure(port, '/hello', 'GET')).map((r) => r.reqSec)).median,
|
||||
});
|
||||
} finally {
|
||||
await kill();
|
||||
}
|
||||
}
|
||||
|
||||
const commit = execSync('git rev-parse --short HEAD').toString().trim();
|
||||
const data: RenderData = {
|
||||
env: {
|
||||
date: new Date().toISOString().slice(0, 10),
|
||||
commit,
|
||||
node: process.version,
|
||||
os: os.platform(),
|
||||
cpu: `${os.cpus()[0].model} (${os.cpus().length} cores)`,
|
||||
ram: `${Math.round(os.totalmem() / 1e9)} GB`,
|
||||
pinned: false,
|
||||
},
|
||||
config: { conns: CONNS, duration: DURATION, runs: RUNS, warmup: WARMUP, pipelining: 1 },
|
||||
scenarios: scenarioBlocks,
|
||||
stepScaling,
|
||||
secureCost,
|
||||
};
|
||||
writeFileSync('BENCHMARKS.md', renderMarkdown(data));
|
||||
writeFileSync('bench/results.json', JSON.stringify(data, null, 2));
|
||||
log('wrote BENCHMARKS.md + bench/results.json');
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
export interface Scenario {
|
||||
name: string; // key
|
||||
title: string; // display
|
||||
method: 'GET' | 'POST';
|
||||
path: string; // route path (no host)
|
||||
body?: unknown; // JSON body for POST
|
||||
approximation?: boolean;
|
||||
}
|
||||
|
||||
// The always-valid validation body — every framework takes the success path.
|
||||
export const VALIDATE_BODY = { email: 'bench@example.com' };
|
||||
|
||||
export const SCENARIOS: Scenario[] = [
|
||||
{ name: 'hello', title: 'JSON hello (overhead)', method: 'GET', path: '/hello' },
|
||||
{ name: 'param', title: 'Route param', method: 'GET', path: '/users/42' },
|
||||
{ name: 'pipeline', title: 'Pipeline (3 steps)', method: 'GET', path: '/pipeline', approximation: true },
|
||||
{ name: 'validate', title: 'POST JSON + validation',method: 'POST', path: '/validate', body: VALIDATE_BODY },
|
||||
];
|
||||
|
||||
// green-tea-only step-scaling routes
|
||||
export const STEP_ROUTES = [
|
||||
{ name: 'steps0', steps: 0, path: '/steps/0' },
|
||||
{ name: 'steps3', steps: 3, path: '/steps/3' },
|
||||
{ name: 'steps5', steps: 5, path: '/steps/5' },
|
||||
];
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Module, Controller, Get, Post, Param, Body, HttpException, MiddlewareConsumer, NestModule } from '@nestjs/common';
|
||||
|
||||
@Controller()
|
||||
export class BenchController {
|
||||
@Get('hello') hello() { return { hello: 'world' }; }
|
||||
@Get('users/:id') user(@Param('id') id: string) { return { id }; }
|
||||
@Get('pipeline') pipeline() { return { hello: 'world', s3: 3 }; }
|
||||
@Post('validate') validate(@Body() b: any) {
|
||||
if (!(b && typeof b.email === 'string' && b.email.includes('@'))) throw new HttpException({ error: 'invalid' }, 422);
|
||||
return { email: b.email };
|
||||
}
|
||||
}
|
||||
|
||||
// pipeline parity: 3 middleware hops on /pipeline (approximation of 3 @Steps), adapter-agnostic
|
||||
const mw = (_n: number) => (_req: any, _res: any, next: any) => next();
|
||||
|
||||
@Module({ controllers: [BenchController] })
|
||||
export class BenchModule implements NestModule {
|
||||
configure(c: MiddlewareConsumer) { c.apply(mw(1), mw(2), mw(3)).forRoutes('pipeline'); }
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import express from 'express';
|
||||
|
||||
const app = express();
|
||||
app.disable('x-powered-by');
|
||||
app.set('etag', false);
|
||||
app.use(express.json());
|
||||
app.get('/hello', (_req, res) => { res.json({ hello: 'world' }); });
|
||||
app.get('/users/:id', (req, res) => { res.json({ id: req.params.id }); });
|
||||
const mw = (n: number) => (_req: any, res: any, next: any) => { res.locals[`s${n}`] = n; next(); };
|
||||
app.get('/pipeline', mw(1), mw(2), mw(3), (_req, res) => { res.json({ hello: 'world', s3: res.locals.s3 }); });
|
||||
app.post('/validate', (req: any, res) => {
|
||||
const b = req.body;
|
||||
if (!(b && typeof b.email === 'string' && b.email.includes('@'))) { res.status(422).json({ error: 'invalid' }); return; }
|
||||
res.json({ email: b.email });
|
||||
});
|
||||
const server = app.listen(0, () => {
|
||||
server.keepAliveTimeout = 5000;
|
||||
console.log(`READY ${(server.address() as any).port}`);
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import Fastify from 'fastify';
|
||||
|
||||
const app = Fastify({ logger: false, keepAliveTimeout: 5000 });
|
||||
app.get('/hello', async () => ({ hello: 'world' }));
|
||||
app.get('/users/:id', async (req: any) => ({ id: req.params.id }));
|
||||
const hook = (n: number) => (req: any, _res: any, done: any) => { req[`s${n}`] = n; done(); };
|
||||
app.get('/pipeline', { preHandler: [hook(1), hook(2), hook(3)] }, async (req: any) => ({ hello: 'world', s3: req.s3 }));
|
||||
app.post('/validate', {
|
||||
schema: { body: { type: 'object', required: ['email'], properties: { email: { type: 'string' } } } },
|
||||
}, async (req: any, reply) => {
|
||||
const b = req.body;
|
||||
if (!b.email.includes('@')) { reply.code(422); return { error: 'invalid' }; }
|
||||
return { email: b.email };
|
||||
});
|
||||
app.listen({ port: 0, host: '0.0.0.0' }, (err, addr) => {
|
||||
if (err) { console.error(err); process.exit(1); }
|
||||
console.log(`READY ${Number(new URL(addr).port)}`);
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import 'reflect-metadata';
|
||||
import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../dist/index.mjs';
|
||||
import { serveBun } from '../../dist/bun.mjs';
|
||||
|
||||
// Same BenchModule as green-tea.ts (Node), served via Bun.serve instead of app.listen.
|
||||
const emailSchema = {
|
||||
'~standard': { version: 1 as const, vendor: 'bench', validate: (v: any) =>
|
||||
(v && typeof v.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'invalid email' }] } },
|
||||
};
|
||||
|
||||
function makeStep(n: number) {
|
||||
@Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] })
|
||||
class S { run() { return { [`s${n}`]: n }; } }
|
||||
return S;
|
||||
}
|
||||
const steps = [1, 2, 3, 4, 5].map(makeStep);
|
||||
|
||||
@Route('/')
|
||||
class Bench {
|
||||
@Get('/hello') hello() { return { hello: 'world' }; }
|
||||
@Get('/users/:id') user(@param('id') id: string) { return { id }; }
|
||||
@Get('/pipeline') pipeline(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
|
||||
@Post('/validate') validate(@body(emailSchema) b: any) { return { email: b.email }; }
|
||||
@Get('/steps/0') steps0() { return { hello: 'world' }; }
|
||||
@Get('/steps/3') steps3(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
|
||||
@Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; }
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/', steps, controllers: [Bench] })
|
||||
class BenchModule {}
|
||||
|
||||
const app = createApp({ modules: [BenchModule], security: false });
|
||||
const server = serveBun(app, { port: 0, hostname: '0.0.0.0' });
|
||||
console.log(`READY ${server.port}`);
|
||||
@@ -0,0 +1,33 @@
|
||||
import 'reflect-metadata';
|
||||
import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../dist/index.mjs';
|
||||
import { serveDeno } from '../../dist/deno.mjs';
|
||||
|
||||
// Same BenchModule as green-tea.ts (Node), served via Deno.serve instead of app.listen.
|
||||
const emailSchema = {
|
||||
'~standard': { version: 1 as const, vendor: 'bench', validate: (v: any) =>
|
||||
(v && typeof v.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'invalid email' }] } },
|
||||
};
|
||||
|
||||
function makeStep(n: number) {
|
||||
@Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] })
|
||||
class S { run() { return { [`s${n}`]: n }; } }
|
||||
return S;
|
||||
}
|
||||
const steps = [1, 2, 3, 4, 5].map(makeStep);
|
||||
|
||||
@Route('/')
|
||||
class Bench {
|
||||
@Get('/hello') hello() { return { hello: 'world' }; }
|
||||
@Get('/users/:id') user(@param('id') id: string) { return { id }; }
|
||||
@Get('/pipeline') pipeline(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
|
||||
@Post('/validate') validate(@body(emailSchema) b: any) { return { email: b.email }; }
|
||||
@Get('/steps/0') steps0() { return { hello: 'world' }; }
|
||||
@Get('/steps/3') steps3(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
|
||||
@Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; }
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/', steps, controllers: [Bench] })
|
||||
class BenchModule {}
|
||||
|
||||
const app = createApp({ modules: [BenchModule], security: false });
|
||||
serveDeno(app, { port: 0, hostname: '0.0.0.0', onListen: (a: { port: number }) => console.log(`READY ${a.port}`) });
|
||||
@@ -0,0 +1,44 @@
|
||||
import 'reflect-metadata';
|
||||
import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../src/index';
|
||||
|
||||
// email schema (Standard Schema, hand-rolled — same field check the others do)
|
||||
const emailSchema = {
|
||||
'~standard': { version: 1 as const, vendor: 'bench', validate: (v: any) =>
|
||||
(v && typeof v.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'invalid email' }] } },
|
||||
};
|
||||
|
||||
// 5 chained steps: s1..s5, each needs the previous. Routes @needs the Nth to pull exactly N.
|
||||
function makeStep(n: number) {
|
||||
@Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] })
|
||||
class S { run() { return { [`s${n}`]: n }; } }
|
||||
return S;
|
||||
}
|
||||
const steps = [1, 2, 3, 4, 5].map(makeStep);
|
||||
|
||||
@Route('/')
|
||||
class Bench {
|
||||
@Get('/hello') hello() { return { hello: 'world' }; }
|
||||
@Get('/users/:id') user(@param('id') id: string) { return { id }; }
|
||||
@Get('/pipeline') pipeline(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
|
||||
@Post('/validate') validate(@body(emailSchema) b: any) { return { email: b.email }; }
|
||||
@Get('/steps/0') steps0() { return { hello: 'world' }; }
|
||||
@Get('/steps/3') steps3(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
|
||||
@Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; }
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/', steps, controllers: [Bench] })
|
||||
class BenchModule {}
|
||||
|
||||
// PARITY: security OFF for the cross-framework table. GT_SECURE=1 flips it on for the secure-cost micro-bench.
|
||||
const secure = process.env.GT_SECURE === '1';
|
||||
const app = createApp({ modules: [BenchModule], security: secure });
|
||||
|
||||
async function main() {
|
||||
// fail loudly if decorators didn't apply (inspect throws "no route" on empty plan, so wrap)
|
||||
try { if (app.inspect('/hello').length === 0) throw new Error('empty'); }
|
||||
catch { console.error('DECORATORS_NOT_APPLIED'); process.exit(1); }
|
||||
const server = await app.listen(0);
|
||||
server.keepAliveTimeout = 5000; // parity value (all servers use 5000)
|
||||
console.log(`READY ${(server.address() as any).port}`);
|
||||
}
|
||||
main().catch((e) => { console.error(e); process.exit(1); });
|
||||
@@ -0,0 +1,17 @@
|
||||
import 'reflect-metadata';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { ExpressAdapter } from '@nestjs/platform-express';
|
||||
import express from 'express';
|
||||
import { BenchModule } from './_nest-shared';
|
||||
|
||||
async function main() {
|
||||
const inst = express();
|
||||
inst.disable('x-powered-by');
|
||||
inst.set('etag', false);
|
||||
const app = await NestFactory.create(BenchModule, new ExpressAdapter(inst), { logger: false });
|
||||
await app.listen(0, '0.0.0.0');
|
||||
const server = app.getHttpServer();
|
||||
server.keepAliveTimeout = 5000; // parity (works on Node http.Server after listen)
|
||||
console.log(`READY ${server.address().port}`);
|
||||
}
|
||||
main().catch((e) => { console.error(e); process.exit(1); });
|
||||
@@ -0,0 +1,13 @@
|
||||
import 'reflect-metadata';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
|
||||
import { BenchModule } from './_nest-shared';
|
||||
|
||||
async function main() {
|
||||
const adapter = new FastifyAdapter({ logger: false, keepAliveTimeout: 5000 }); // parity via constructor
|
||||
const app = await NestFactory.create<NestFastifyApplication>(BenchModule, adapter, { logger: false });
|
||||
await app.listen(0, '0.0.0.0');
|
||||
const server = app.getHttpServer();
|
||||
console.log(`READY ${(server.address() as any).port}`);
|
||||
}
|
||||
main().catch((e) => { console.error(e); process.exit(1); });
|
||||
@@ -0,0 +1,18 @@
|
||||
import http from 'http';
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
const url = (req.url ?? '/').split('?')[0];
|
||||
const send = (obj: unknown, code = 200) => { res.writeHead(code, { 'content-type': 'application/json' }); res.end(JSON.stringify(obj)); };
|
||||
if (req.method === 'GET' && url === '/hello') return send({ hello: 'world' });
|
||||
if (req.method === 'GET' && url.startsWith('/users/')) return send({ id: url.slice('/users/'.length) });
|
||||
if (req.method === 'GET' && url === '/pipeline') { const s: any = {}; [1, 2, 3].forEach((n) => (s[`s${n}`] = n)); return send({ hello: 'world', s3: s.s3 }); }
|
||||
if (req.method === 'POST' && url === '/validate') {
|
||||
let raw = ''; req.on('data', (c) => (raw += c)); req.on('end', () => {
|
||||
try { const b = JSON.parse(raw); if (typeof b.email === 'string' && b.email.includes('@')) return send({ email: b.email }); return send({ error: 'invalid' }, 422); }
|
||||
catch { return send({ error: 'bad json' }, 400); }
|
||||
}); return;
|
||||
}
|
||||
send({ error: 'not found' }, 404);
|
||||
});
|
||||
server.keepAliveTimeout = 5000;
|
||||
server.listen(0, () => console.log(`READY ${(server.address() as any).port}`));
|
||||
@@ -0,0 +1,26 @@
|
||||
import express from 'express';
|
||||
|
||||
// Express counterpart: /chain/N runs N trivial middlewares before the handler —
|
||||
// the closest apples-to-apples to green-tea's N chained steps.
|
||||
const app = express();
|
||||
app.disable('x-powered-by');
|
||||
app.set('etag', false);
|
||||
|
||||
const mw = (_req: any, _res: any, next: any) => next();
|
||||
|
||||
function route(path: string, n: number): void {
|
||||
const chain = Array.from({ length: n }, () => mw);
|
||||
app.get(path, ...chain, (_req, res) => { res.json({ ok: 1 }); });
|
||||
}
|
||||
|
||||
route('/chain/0', 0);
|
||||
route('/chain/10', 10);
|
||||
route('/chain/25', 25);
|
||||
route('/chain/50', 50);
|
||||
route('/chain/75', 75);
|
||||
route('/chain/100', 100);
|
||||
|
||||
const server = app.listen(0, () => {
|
||||
server.keepAliveTimeout = 5000;
|
||||
console.log(`READY ${(server.address() as any).port}`);
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import 'reflect-metadata';
|
||||
import { createApp, Step, Route, Get, Module, needs } from '../../src/index';
|
||||
|
||||
// 100 chained steps: s1..s100, each needs the previous. A route that @needs the Nth
|
||||
// pulls exactly N steps transitively — so /chain/100 runs the full 100-deep graph slice.
|
||||
function makeStep(n: number) {
|
||||
@Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] })
|
||||
class S { run() { return { [`s${n}`]: n }; } }
|
||||
return S;
|
||||
}
|
||||
const steps = Array.from({ length: 100 }, (_, i) => makeStep(i + 1));
|
||||
|
||||
@Route('/chain')
|
||||
class Chain {
|
||||
@Get('/0') d0() { return { ok: 1 }; }
|
||||
@Get('/10') d10(@needs('s10') s: number) { return { s }; }
|
||||
@Get('/25') d25(@needs('s25') s: number) { return { s }; }
|
||||
@Get('/50') d50(@needs('s50') s: number) { return { s }; }
|
||||
@Get('/75') d75(@needs('s75') s: number) { return { s }; }
|
||||
@Get('/100') d100(@needs('s100') s: number) { return { s }; }
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/', steps, controllers: [Chain] })
|
||||
class ScaleModule {}
|
||||
|
||||
const app = createApp({ modules: [ScaleModule], security: false });
|
||||
|
||||
async function main() {
|
||||
const server = await app.listen(0);
|
||||
server.keepAliveTimeout = 5000;
|
||||
console.log(`READY ${(server.address() as any).port}`);
|
||||
}
|
||||
main().catch((e) => { console.error(e); process.exit(1); });
|
||||
@@ -0,0 +1,18 @@
|
||||
export interface Agg {
|
||||
median: number;
|
||||
mean: number;
|
||||
stddev: number;
|
||||
cv: number;
|
||||
min: number;
|
||||
max: number;
|
||||
}
|
||||
|
||||
export function aggregate(values: number[]): Agg {
|
||||
const xs = [...values].sort((a, b) => a - b);
|
||||
const n = xs.length;
|
||||
const mean = xs.reduce((s, x) => s + x, 0) / n;
|
||||
const median = n % 2 ? xs[(n - 1) / 2] : (xs[n / 2 - 1] + xs[n / 2]) / 2;
|
||||
const variance = xs.reduce((s, x) => s + (x - mean) ** 2, 0) / n;
|
||||
const stddev = Math.sqrt(variance);
|
||||
return { median, mean, stddev, cv: mean ? stddev / mean : 0, min: xs[0], max: xs[n - 1] };
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"extends": "../tsconfig.json",
|
||||
"compilerOptions": { "experimentalDecorators": true, "emitDecoratorMetadata": true, "noEmit": true },
|
||||
"include": ["."]
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"experimentalDecorators": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"lib": ["deno.window", "deno.ns"]
|
||||
},
|
||||
"unstable": ["sloppy-imports"],
|
||||
"imports": {
|
||||
"http": "node:http",
|
||||
"https": "node:https",
|
||||
"crypto": "node:crypto",
|
||||
"events": "node:events",
|
||||
"stream": "node:stream"
|
||||
},
|
||||
"lint": { "exclude": ["dist", "node_modules"] }
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
{
|
||||
"version": "5",
|
||||
"specifiers": {
|
||||
"jsr:@std/assert@*": "1.0.19",
|
||||
"jsr:@std/internal@^1.0.12": "1.0.14"
|
||||
},
|
||||
"jsr": {
|
||||
"@std/assert@1.0.19": {
|
||||
"integrity": "eaada96ee120cb980bc47e040f82814d786fe8162ecc53c91d8df60b8755991e",
|
||||
"dependencies": [
|
||||
"jsr:@std/internal"
|
||||
]
|
||||
},
|
||||
"@std/internal@1.0.14": {
|
||||
"integrity": "291516b3d4c35024d6ffbc0a9df5bf4c64116e05b50012cf846710152d2ffdf7"
|
||||
}
|
||||
},
|
||||
"workspace": {
|
||||
"packageJson": {
|
||||
"dependencies": [
|
||||
"npm:@eslint/js@^9.39.5",
|
||||
"npm:@nestjs/common@^11.1.28",
|
||||
"npm:@nestjs/core@^11.1.28",
|
||||
"npm:@nestjs/platform-express@^11.1.28",
|
||||
"npm:@nestjs/platform-fastify@^11.1.28",
|
||||
"npm:@stylistic/eslint-plugin@^5.10.0",
|
||||
"npm:@types/autocannon@^7.12.7",
|
||||
"npm:@types/busboy@^1.5.4",
|
||||
"npm:@types/express@^5.0.6",
|
||||
"npm:@types/node@^18.19.0",
|
||||
"npm:@types/ws@^8.18.1",
|
||||
"npm:autocannon@8",
|
||||
"npm:busboy@^1.6.0",
|
||||
"npm:cognitive-complexity-ts@~0.8.2",
|
||||
"npm:esbuild@0.27.2",
|
||||
"npm:eslint@^9.39.5",
|
||||
"npm:express@^5.2.1",
|
||||
"npm:fastify@^5.11.0",
|
||||
"npm:graphql@^16.9.0",
|
||||
"npm:miniflare@^4.20260730.0",
|
||||
"npm:prettier@^3.9.6",
|
||||
"npm:reflect-metadata@0.2.2",
|
||||
"npm:rxjs@^7.8.2",
|
||||
"npm:tsup@^8.5.1",
|
||||
"npm:tsx@^4.23.5",
|
||||
"npm:typescript-eslint@^8.65.0",
|
||||
"npm:typescript@^5.5.0",
|
||||
"npm:vite@^6.4.3",
|
||||
"npm:vitest@^3.2.7",
|
||||
"npm:ws@^8.21.1"
|
||||
],
|
||||
"overrides": {
|
||||
"find-my-way": "9.7.0",
|
||||
"autocannon": {
|
||||
"hyperid": {
|
||||
"uuid": "11.1.1"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
# green-tea — Architecture
|
||||
|
||||
> The request and boot are an explicit **dependency graph**, not a mutable middleware chain.
|
||||
> You declare *what* you need; the framework computes the order. The graph can extend in
|
||||
> **time** (streams) and across **machines** (mesh).
|
||||
|
||||
## The four layers
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
subgraph L3["#3 MESH — the graph crosses machines"]
|
||||
direction LR
|
||||
teacup["teacup (consumer)"] -- "WS RPC" --> teapot["teapot (host)"]
|
||||
end
|
||||
subgraph L2["#2 STREAMS — the graph emits over time"]
|
||||
sse["SSE / ndjson"]:::n
|
||||
ws["WebSocket duplex"]:::n
|
||||
end
|
||||
subgraph L15["#1.5 ARG DECORATORS — the handler declares its deps"]
|
||||
sig["handler signature = dependency declaration"]:::n
|
||||
end
|
||||
subgraph L1["#1 CORE — graph DI + boot + router + pipeline + flow"]
|
||||
core["Providers · Steps · Routes · Transformers · Container · Bus"]:::n
|
||||
end
|
||||
L3 --> L2 --> L15 --> L1
|
||||
classDef n fill:#f6f8fa,stroke:#aaa;
|
||||
```
|
||||
|
||||
## Building blocks
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
Provider["@Provider\n(app scope · singleton)"]:::p
|
||||
Step["@Step\n(request scope · per call)"]:::s
|
||||
Route["@Route + @Get/@Post/@Sse/@Ws/@Stream"]:::r
|
||||
Transformer["@Transformer\nvalue → ResponseShape"]:::t
|
||||
Container["Container.resolve()\nasync · transport-agnostic"]:::c
|
||||
Bus["Bus\nlifecycle events"]:::b
|
||||
|
||||
Provider --> Container
|
||||
Step --> Container
|
||||
Route --> Transformer
|
||||
Container -. "remote binding (mesh)" .-> Provider
|
||||
classDef p fill:#e7f5ff,stroke:#4dabf7;
|
||||
classDef s fill:#fff3bf,stroke:#f59f00;
|
||||
classDef r fill:#ebfbee,stroke:#40c057;
|
||||
classDef t fill:#f3f0ff,stroke:#7950f2;
|
||||
classDef c fill:#fff0f6,stroke:#e64980;
|
||||
classDef b fill:#f1f3f5,stroke:#868e96;
|
||||
```
|
||||
|
||||
## Request lifecycle
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as Client
|
||||
participant H as http.ts (transport)
|
||||
participant P as Pipeline
|
||||
participant G as Graph (providers/steps)
|
||||
participant T as Transformer
|
||||
|
||||
C->>H: HTTP request
|
||||
H->>H: matchRoute(method, path)
|
||||
H->>P: runPipeline(seed = req envelope)
|
||||
P->>G: providers (cached) + steps (topo order)
|
||||
Note over G: each step merges into ctx;<br/>throw = short-circuit, return = continue
|
||||
P->>P: handler(args resolved from ctx)
|
||||
alt returns a value
|
||||
P->>T: transformer → {status, headers, body}
|
||||
T-->>C: buffered response
|
||||
else returns an AsyncIterable
|
||||
P-->>C: stream (SSE / ndjson / WS), backpressure + cleanup
|
||||
else @needs a remote token
|
||||
G-->>C: RPC to teapot, value spliced into ctx
|
||||
end
|
||||
```
|
||||
|
||||
## The unifying rule
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Q{"what does the handler return /\nwhere does a token live?"}
|
||||
Q -->|"a value"| A["buffered (transformer → JSON)"]
|
||||
Q -->|"an AsyncIterable"| B["stream (SSE / WS)"]
|
||||
Q -->|"a token with no local provider"| D["RPC to a teapot (mesh)"]
|
||||
```
|
||||
|
||||
One question — *"what produces this token and where does it live?"* — answers local DI,
|
||||
streaming, and distribution. That single seam is why green-tea isn't "Express with decorators":
|
||||
**the graph is the product.**
|
||||
|
||||
## Mesh walking skeleton (spec #3)
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph A["Node A — teapot"]
|
||||
ea["@Provider({export:true})\n@Step({export:true})\n@Get('/x',{export:true})"]
|
||||
mc["control channel\n/__mesh__/control\n(secret-gated)"]
|
||||
end
|
||||
subgraph B["Node B — teacup"]
|
||||
bn["@needs('auth') with\nno local provider"]
|
||||
lk["link: handshake → manifest\n→ synthetic graph nodes\nwith RPC runners"]
|
||||
end
|
||||
bn --> lk
|
||||
lk -- "hello + secret" --> mc
|
||||
mc -- "manifest {scopes, routes}" --> lk
|
||||
lk -- "rpc-req {id, kind, name, ctx}" --> mc
|
||||
mc -- "rpc-res {id, ok, result}" --> lk
|
||||
```
|
||||
|
||||
- **Provider exported → app scope** (resolved once via RPC, cached).
|
||||
- **Step exported → request scope** (RPC per request, carries the request envelope).
|
||||
- **Route exported → proxy** (teacup forwards the request, teapot runs the full pipeline).
|
||||
|
||||
Deferred to mesh sub-specs: discovery/auto-registration, 2-way load-balancing, failover/health.
|
||||
@@ -0,0 +1,170 @@
|
||||
# Router correctness and security beta design
|
||||
|
||||
**Date:** 2026-08-02
|
||||
**Target:** `26.8.0-beta.0`
|
||||
**Status:** Approved
|
||||
|
||||
## Goal
|
||||
|
||||
Prepare the August beta by completing the router's missing HTTP behavior, adding safe segment constraints, aligning the public documentation with the code, and removing known dependency vulnerabilities from the core repository and documentation site.
|
||||
|
||||
The release keeps the current linear matcher. A radix tree remains a separate performance project that must earn its complexity through benchmarks.
|
||||
|
||||
## Scope
|
||||
|
||||
This change includes:
|
||||
|
||||
- first-class `HEAD` and `OPTIONS` routes;
|
||||
- automatic `HEAD` fallback to `GET`;
|
||||
- automatic bare `OPTIONS` responses;
|
||||
- correct and deterministic `Allow` headers;
|
||||
- a tolerant trailing-slash policy with rejection of repeated internal slashes;
|
||||
- route-pattern validation at boot;
|
||||
- safe parameter constraints such as `:id(\d+)`;
|
||||
- malformed URI handling as a client error;
|
||||
- duplicate and ambiguous route detection;
|
||||
- OpenAPI projection of constrained parameters;
|
||||
- dependency remediation for the root package and `website/`;
|
||||
- public documentation and changelog updates;
|
||||
- the `26.8.0-beta.0` package-version bump.
|
||||
|
||||
This change excludes:
|
||||
|
||||
- a radix-tree matcher;
|
||||
- arbitrary, unrestricted regular expressions;
|
||||
- manual publication, npm tags, or registry mutations;
|
||||
- mesh discovery, load balancing, and failover.
|
||||
|
||||
## Route semantics
|
||||
|
||||
### Path normalization
|
||||
|
||||
`/users` and `/users/` identify the same route. The matcher removes one trailing slash except for `/`.
|
||||
|
||||
The ingress rejects repeated slashes, including `/users//42`, with `400 Bad Request`. It applies this rule before declared-route matching and static-file fallback, so Node and Fetch adapters behave alike.
|
||||
|
||||
Malformed percent encoding also returns `400 Bad Request`. A malformed path never escapes the matcher as `URIError` and never becomes `500`.
|
||||
|
||||
### Methods
|
||||
|
||||
The public `HttpMethod` type and decorator surface gain `HEAD` and `OPTIONS`. `@Head` and `@Options` accept the same route options as the existing buffered method decorators.
|
||||
|
||||
For `HEAD`, an explicit `HEAD` route wins. Without one, the router matches the corresponding `GET` route and executes its pipeline, but every adapter suppresses the response body. The response retains the status and headers that `GET` would produce. Streaming routes do not serve as implicit `HEAD` handlers.
|
||||
|
||||
For a bare `OPTIONS` request, an explicit `OPTIONS` route wins. Without one, any matching path receives `204 No Content` and an `Allow` header. CORS preflight remains the earlier specialized branch and keeps its configured CORS response.
|
||||
|
||||
`Allow` uses a stable method order. It adds `HEAD` when a buffered `GET` route exists and adds `OPTIONS` whenever the path exists. A request with another unsupported method receives `405` plus the same value.
|
||||
|
||||
### Pattern validation
|
||||
|
||||
The application compiles and validates route patterns during graph construction. Invalid declarations fail before the app serves traffic. Validation rejects:
|
||||
|
||||
- a catch-all outside the final segment;
|
||||
- empty parameter or catch-all names;
|
||||
- repeated parameter names in one pattern;
|
||||
- repeated internal slashes in declarations;
|
||||
- malformed constraints;
|
||||
- duplicate routes with the same method and effective pattern;
|
||||
- patterns that differ only by parameter names and therefore match the same requests with equal precedence.
|
||||
|
||||
Errors name the method, pattern, controller origin, and conflict when applicable.
|
||||
|
||||
### Segment constraints
|
||||
|
||||
The matcher accepts a constrained parameter such as `:id(\d+)`. A constraint matches the whole decoded segment. `/users/12` matches `:id(\d+)`; `/users/12x` does not. A failed constraint remains a normal non-match, so another route may win before the router returns `404`.
|
||||
|
||||
The implementation compiles constraints once and caches the compiled pattern. It accepts a deliberately small regular-expression subset for common numeric, UUID, slug, and enumerated segments. It rejects lookarounds, backreferences, nested groups, nested quantifiers, and other constructs that create a practical ReDoS risk. This keeps the advertised syntax without executing unrestricted attacker-facing regular expressions.
|
||||
|
||||
Specificity remains deterministic:
|
||||
|
||||
1. static segment;
|
||||
2. constrained parameter;
|
||||
3. unconstrained parameter;
|
||||
4. catch-all.
|
||||
|
||||
Registration order resolves only genuine, non-ambiguous ties that survive boot validation.
|
||||
|
||||
## Architecture
|
||||
|
||||
`src/http/router.ts` owns pattern parsing, validation, compilation, matching, method fallback, and `Allow` calculation. A compiled representation records normalized segments, parameter names, optional constraints, catch-all state, and specificity.
|
||||
|
||||
`src/metadata.ts` exposes the new method type and decorators. Application graph construction compiles route definitions and reports declaration errors with controller context. The runtime-neutral HTTP core decides `HEAD`, `OPTIONS`, `400`, `404`, and `405`; Node and Fetch adapters only serialize its outcome.
|
||||
|
||||
`src/openapi.ts` converts constrained paths to OpenAPI templates and places the accepted expression in the path parameter's `schema.pattern`. It lists explicit `HEAD` and `OPTIONS` operations but does not invent operations for automatic fallbacks.
|
||||
|
||||
Mesh route manifests carry the expanded method union. Existing wire behavior stays compatible because method values are strings and the change adds values without changing the envelope shape.
|
||||
|
||||
## Error behavior
|
||||
|
||||
Declaration errors fail at boot. Request syntax errors return the standard error envelope with status `400` and pass through the configured `onError` renderer. Pattern non-matches return `404`; method mismatches return `405`; automatic `OPTIONS` returns `204`.
|
||||
|
||||
Error responses keep the existing security and CORS header injection. They do not include decoded attacker input, stack traces, or internal regular-expression details.
|
||||
|
||||
## Dependency remediation
|
||||
|
||||
The published runtime dependency set is already clean: `npm audit --omit=dev` reports zero vulnerabilities. The full development tree and documentation site require remediation.
|
||||
|
||||
The root update will prefer the smallest supported versions that close each advisory:
|
||||
|
||||
- Vitest moves to `3.2.6`, which fixes the critical advisory while preserving Node 18 support;
|
||||
- the Nest benchmark packages move to `11.1.28`, including Multer `2.2.0`;
|
||||
- Miniflare moves to its current compatible patch with fixed Sharp;
|
||||
- Fastify and compatible toolchain packages receive current patch/minor updates;
|
||||
- `find-my-way` receives a narrow `9.7.0` override while Nest pins the vulnerable `9.6.0`, with Nest/Fastify benchmarks as a compatibility gate;
|
||||
- Autocannon's `hyperid`/`uuid` chain receives an isolated remediation only if the benchmark suite proves it compatible; otherwise the benchmark dependency will be replaced or isolated rather than suppressing the advisory.
|
||||
|
||||
The documentation site moves Astro to `7.1.6`, Starlight to `0.41.6`, and resolves the patched PostCSS and SVGO versions. Both lockfiles will be regenerated from their manifests.
|
||||
|
||||
The work will not use `npm audit fix --force`, security-audit suppression, or an incompatible downgrade merely to produce a green report.
|
||||
|
||||
## Documentation
|
||||
|
||||
The change updates:
|
||||
|
||||
- the README routing section and roadmap;
|
||||
- the Routing guide;
|
||||
- the Decorators reference;
|
||||
- the OpenAPI guide where constrained parameters affect output;
|
||||
- the CHANGELOG and package version;
|
||||
- the Starlight 404 configuration that currently emits a build warning.
|
||||
|
||||
Examples will state the trailing-slash policy, double-slash rejection, automatic method behavior, constraint limits, and the deferred radix-tree work.
|
||||
|
||||
## Verification
|
||||
|
||||
The implementation adds unit and integration coverage for:
|
||||
|
||||
- explicit and implicit `HEAD`;
|
||||
- body suppression and header preservation;
|
||||
- explicit and automatic `OPTIONS`;
|
||||
- CORS-preflight precedence;
|
||||
- deterministic `Allow` values;
|
||||
- trailing slash equivalence and double-slash rejection;
|
||||
- invalid percent encoding;
|
||||
- route-declaration failures;
|
||||
- constrained matches, non-matches, precedence, and unsafe-expression rejection;
|
||||
- OpenAPI path and `schema.pattern` output;
|
||||
- Node and Fetch parity;
|
||||
- mesh method serialization where relevant.
|
||||
|
||||
The release gate runs:
|
||||
|
||||
- root and website audits with zero known vulnerabilities;
|
||||
- the runtime-only root audit separately;
|
||||
- Node tests, typecheck, lint, format, complexity, and build;
|
||||
- Deno, Bun, and Edge suites when their runtimes are available;
|
||||
- documentation build without the current 404 warning;
|
||||
- framework benchmarks, including the Nest/Fastify paths affected by overrides;
|
||||
- `npm pack --dry-run` to inspect the published artifact.
|
||||
|
||||
## CI and publication flow
|
||||
|
||||
Gitea remains the source of the release flow:
|
||||
|
||||
1. CI runs on `develop` and `main`.
|
||||
2. A merge to Gitea `main` publishes the package to internal Verdaccio under `stg`.
|
||||
3. Gitea's promotion workflow pushes only `main` and version tags to GitHub.
|
||||
4. A promoted `v*` tag triggers GitHub's `release.yml`.
|
||||
5. GitHub publishes to npm through Trusted Publishing/OIDC and derives `beta` from `26.8.0-beta.0`.
|
||||
|
||||
This implementation prepares the version and validates the workflows. It does not merge to `main`, create a release tag, publish to Verdaccio, or invoke `npm publish` locally.
|
||||
@@ -0,0 +1,679 @@
|
||||
# Router Security Beta Implementation Plan
|
||||
|
||||
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
|
||||
|
||||
**Goal:** Ship `26.8.0-beta.0` with complete HEAD/OPTIONS behavior, safe constrained route parameters, strict path handling, accurate documentation, and clean dependency audits.
|
||||
|
||||
**Architecture:** Keep the linear route table, but compile and validate each pattern once. Centralize path syntax, matching, method fallback, and `Allow` calculation in the runtime-neutral HTTP layer so Node and Fetch adapters stay behaviorally identical. Remediate tooling dependencies without changing the package's Node 18 runtime contract or its one required runtime dependency.
|
||||
|
||||
**Tech Stack:** TypeScript, legacy decorators, Node HTTP, Fetch API, Vitest, OpenAPI 3.1, Astro/Starlight, npm lockfiles, GitHub/Gitea Actions.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Compile and validate route patterns
|
||||
|
||||
**Skills:** `@superpowers:test-driven-development`, `@security-review`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/http/router.ts`
|
||||
- Modify: `src/http/types.ts`
|
||||
- Test: `test/router.test.ts`
|
||||
|
||||
**Step 1: Write failing compiler tests**
|
||||
|
||||
Add tests that establish the supported grammar and precedence:
|
||||
|
||||
```typescript
|
||||
describe('compilePattern', () => {
|
||||
it('compiles constrained params and gives them precedence over plain params', () => {
|
||||
const routes = [route('GET', '/users/:value'), route('GET', '/users/:id(\\d+)')];
|
||||
expect(matchRoute(routes, 'GET', '/users/42')?.def.pattern).toBe('/users/:id(\\d+)');
|
||||
expect(matchRoute(routes, 'GET', '/users/diego')?.def.pattern).toBe('/users/:value');
|
||||
});
|
||||
|
||||
it.each([
|
||||
'/files/:rest*/tail',
|
||||
'/users/:',
|
||||
'/users/:id/:id',
|
||||
'/users//:id',
|
||||
'/users/:id((a+)+)',
|
||||
'/users/:id((?=a)a)',
|
||||
'/users/:id(\\1)',
|
||||
])('rejects invalid or unsafe pattern %s', (pattern) => {
|
||||
expect(() => compilePattern(pattern)).toThrow(/invalid route pattern|unsafe route constraint/);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
Also cover numeric, UUID-like, slug, and bounded-quantifier examples; a constraint must match the complete decoded segment.
|
||||
|
||||
**Step 2: Run the focused test and confirm RED**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
npx vitest run test/router.test.ts
|
||||
```
|
||||
|
||||
Expected: FAIL because `compilePattern` and constrained matching do not exist.
|
||||
|
||||
**Step 3: Implement the compiled representation**
|
||||
|
||||
In `src/http/router.ts`, add:
|
||||
|
||||
```typescript
|
||||
type CompiledSegment =
|
||||
| { kind: 'static'; value: string }
|
||||
| { kind: 'param'; name: string; constraint?: RegExp }
|
||||
| { kind: 'catchAll'; name: string };
|
||||
|
||||
export interface CompiledPattern {
|
||||
source: string;
|
||||
normalized: string;
|
||||
shape: string;
|
||||
segments: CompiledSegment[];
|
||||
kinds: number[]; // static=3, constrained=2, param=1; catch-all stored separately
|
||||
catchAll: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
Implement `compilePattern(pattern)`, `matchCompiled(compiled, pathSegments)`, and a string-keyed cache used by `matchPattern`. Parse `:name(expr)` only when the closing `)` ends the segment. Anchor accepted constraints as `^(?:${expr})$`.
|
||||
|
||||
Implement `assertSafeConstraint` as a small whitelist parser. Permit literals, character classes, `\\d`/`\\w`/`\\s` classes, escaped literals, and simple quantifiers. Reject expression length above 128, groups, alternation, anchors, lookarounds, backreferences, nested quantifiers, and adjacent unbounded quantified atoms without a separating literal. Do not add a runtime dependency.
|
||||
|
||||
Build `shape` from segment kinds and constraint source so `:id` and `:name` have the same effective shape.
|
||||
|
||||
**Step 4: Run tests and confirm GREEN**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
npx vitest run test/router.test.ts
|
||||
npm run typecheck
|
||||
```
|
||||
|
||||
Expected: all router tests pass and TypeScript reports no errors.
|
||||
|
||||
**Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/http/router.ts src/http/types.ts test/router.test.ts
|
||||
git commit -s -m "feat(router): compile safe constrained patterns"
|
||||
```
|
||||
|
||||
### Task 2: Validate request paths and route-table ambiguity
|
||||
|
||||
**Skills:** `@superpowers:test-driven-development`, `@security-review`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/http/router.ts`
|
||||
- Modify: `src/app/index.ts`
|
||||
- Modify: `src/app/types.ts`
|
||||
- Test: `test/router.test.ts`
|
||||
- Test: `test/app.test.ts`
|
||||
|
||||
**Step 1: Write failing path-policy tests**
|
||||
|
||||
Add router tests for the approved normalization:
|
||||
|
||||
```typescript
|
||||
expect(normalizeRequestPath('/users')).toBe('/users');
|
||||
expect(normalizeRequestPath('/users/')).toBe('/users');
|
||||
expect(normalizeRequestPath('/')).toBe('/');
|
||||
expect(() => normalizeRequestPath('/users//42')).toThrow(/repeated slash/);
|
||||
expect(() => normalizeRequestPath('/users/%E0%A4%A')).toThrow(/malformed path encoding/);
|
||||
```
|
||||
|
||||
Add app-construction tests proving that identical routes and routes that differ only by parameter names fail before serving:
|
||||
|
||||
```typescript
|
||||
expect(() => createApp({ modules: [DuplicateRouteModule] })).toThrow(/ambiguous route.*GET/);
|
||||
```
|
||||
|
||||
Cover the same path under different methods as valid.
|
||||
|
||||
**Step 2: Run focused tests and confirm RED**
|
||||
|
||||
```bash
|
||||
npx vitest run test/router.test.ts test/app.test.ts
|
||||
```
|
||||
|
||||
Expected: FAIL because normalization and ambiguity checks are absent.
|
||||
|
||||
**Step 3: Implement request normalization**
|
||||
|
||||
Add `InvalidRequestPathError` and `normalizeRequestPath(path)` to `src/http/router.ts`. Strip exactly one trailing slash except at root, reject `//`, and call `decodeURIComponent` on every raw segment only to validate encoding. Matching still compares static segments according to the existing encoded-path contract and decodes captured values once.
|
||||
|
||||
**Step 4: Implement route-table validation**
|
||||
|
||||
Store a `compiled` pattern on each internal `RoutePlan`/`RouteDef`, or expose a shared cache accessor if that avoids duplicating state. During `collectControllers`, compile each joined pattern and compare the candidate's method plus `shape` with existing route plans. Throw an error that includes method, pattern, controller/handler, and conflicting declaration.
|
||||
|
||||
Apply the same validation after remote mesh routes join. A remote conflict must name both mesh owner URLs rather than silently selecting registration order.
|
||||
|
||||
**Step 5: Run focused and mesh tests**
|
||||
|
||||
```bash
|
||||
npx vitest run test/router.test.ts test/app.test.ts test/mesh/fetch-boot.test.ts test/mesh/integration.test.ts
|
||||
npm run typecheck
|
||||
```
|
||||
|
||||
Expected: all selected tests pass.
|
||||
|
||||
**Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add src/http/router.ts src/app/index.ts src/app/types.ts test/router.test.ts test/app.test.ts
|
||||
git commit -s -m "fix(router): reject invalid and ambiguous paths"
|
||||
```
|
||||
|
||||
### Task 3: Add HEAD and OPTIONS to the public decorator API
|
||||
|
||||
**Skills:** `@superpowers:test-driven-development`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/metadata.ts`
|
||||
- Modify: `src/index.ts`
|
||||
- Modify: `src/signals.ts`
|
||||
- Test: `test/metadata.test.ts`
|
||||
- Test: `test/smoke.test.ts`
|
||||
|
||||
**Step 1: Write failing decorator tests**
|
||||
|
||||
```typescript
|
||||
class Methods {
|
||||
@Head('/resource') head() {}
|
||||
@Options('/resource') options() {}
|
||||
}
|
||||
|
||||
expect(getRoutes(Methods).map(({ method }) => method)).toEqual(['HEAD', 'OPTIONS']);
|
||||
```
|
||||
|
||||
Add a public-barrel smoke test that imports `Head`, `Options`, and `HttpMethod` from `src/index.ts`.
|
||||
|
||||
**Step 2: Run tests and confirm RED**
|
||||
|
||||
```bash
|
||||
npx vitest run test/metadata.test.ts test/smoke.test.ts
|
||||
```
|
||||
|
||||
Expected: FAIL because the exports do not exist.
|
||||
|
||||
**Step 3: Implement decorators and messages**
|
||||
|
||||
Extend `HttpMethod`:
|
||||
|
||||
```typescript
|
||||
export type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS';
|
||||
```
|
||||
|
||||
Create buffered `Head` and `Options` decorators through `routeDecorator`, export them from `src/index.ts`, and update `TransportMismatchError`'s buffered-method message. Keep `@Html` restricted to GET/POST and update its rejection text to include HEAD/OPTIONS.
|
||||
|
||||
**Step 4: Run tests and typecheck**
|
||||
|
||||
```bash
|
||||
npx vitest run test/metadata.test.ts test/smoke.test.ts test/transport-enforcement.test.ts test/views-html.test.ts
|
||||
npm run typecheck
|
||||
```
|
||||
|
||||
Expected: all pass.
|
||||
|
||||
**Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/metadata.ts src/index.ts src/signals.ts test/metadata.test.ts test/smoke.test.ts
|
||||
git commit -s -m "feat(router): expose HEAD and OPTIONS decorators"
|
||||
```
|
||||
|
||||
### Task 4: Implement runtime-neutral HEAD, OPTIONS, and path errors
|
||||
|
||||
**Skills:** `@superpowers:test-driven-development`, `@security-review`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/http/router.ts`
|
||||
- Modify: `src/http/core.ts`
|
||||
- Modify: `src/http/web.ts`
|
||||
- Modify: `src/http/server.ts`
|
||||
- Test: `test/router.test.ts`
|
||||
- Test: `test/http.test.ts`
|
||||
- Test: `test/fetch.test.ts`
|
||||
- Test: `test/parity.test.ts`
|
||||
- Test: `test/transport-security.test.ts`
|
||||
|
||||
**Step 1: Write failing method-semantics tests**
|
||||
|
||||
Cover these cases in both Node and `app.fetch`:
|
||||
|
||||
```typescript
|
||||
// Explicit HEAD wins.
|
||||
// Otherwise buffered GET runs once, retains status/headers, and emits an empty body.
|
||||
// Streaming GET does not become implicit HEAD.
|
||||
// Explicit OPTIONS wins.
|
||||
// Automatic OPTIONS returns 204 and deterministic Allow.
|
||||
// GET implies HEAD; every existing path implies OPTIONS.
|
||||
// CORS preflight still runs before explicit/automatic OPTIONS.
|
||||
// Double slash and malformed encoding return 400 with security headers.
|
||||
```
|
||||
|
||||
Use a canonical expected header such as `GET, HEAD, POST, OPTIONS`.
|
||||
|
||||
**Step 2: Run focused tests and confirm RED**
|
||||
|
||||
```bash
|
||||
npx vitest run test/router.test.ts test/http.test.ts test/fetch.test.ts test/parity.test.ts test/transport-security.test.ts
|
||||
```
|
||||
|
||||
Expected: new assertions fail under the current 405 behavior.
|
||||
|
||||
**Step 3: Implement method resolution**
|
||||
|
||||
In `src/http/router.ts`, add a stable method order and helpers:
|
||||
|
||||
```typescript
|
||||
export interface ResolvedRoute extends MatchedRoute {
|
||||
implicitHead: boolean;
|
||||
}
|
||||
|
||||
export function resolveRoute(routes: RouteDef[], method: string, path: string): ResolvedRoute | undefined;
|
||||
export function allowedMethods(routes: RouteDef[], path: string): HttpMethod[];
|
||||
```
|
||||
|
||||
`resolveRoute` tries explicit method first. For HEAD only, it falls back to a matching buffered GET. `allowedMethods` deduplicates explicit methods, adds HEAD for buffered GET, adds OPTIONS for every existing path, and sorts canonically.
|
||||
|
||||
**Step 4: Implement core outcomes**
|
||||
|
||||
At the start of `handle`, normalize the path and render `InvalidRequestPathError` as `400`. Preserve the existing CORS-preflight branch. Resolve explicit OPTIONS normally; otherwise return buffered `204` with `allow` and empty body. For an implicit or explicit HEAD route, run the normal pipeline but replace a buffered result body with `''`. Reject a stream outcome for HEAD as a transport mismatch rather than opening a stream.
|
||||
|
||||
**Step 5: Align body acquisition in both adapters**
|
||||
|
||||
Replace early `matchRoute` calls in `src/http/web.ts` and `src/http/server.ts` with the same normalization and resolution helper used by `handle`. If path validation fails before body acquisition, render `400` through `onError` with injected security/CORS headers. Never read a request body for automatic OPTIONS or an invalid path.
|
||||
|
||||
**Step 6: Run focused tests and confirm GREEN**
|
||||
|
||||
```bash
|
||||
npx vitest run test/router.test.ts test/http.test.ts test/fetch.test.ts test/parity.test.ts test/transport-security.test.ts
|
||||
npm run typecheck
|
||||
```
|
||||
|
||||
Expected: all selected tests pass with Node/Fetch parity.
|
||||
|
||||
**Step 7: Commit**
|
||||
|
||||
```bash
|
||||
git add src/http/router.ts src/http/core.ts src/http/web.ts src/http/server.ts test/router.test.ts test/http.test.ts test/fetch.test.ts test/parity.test.ts test/transport-security.test.ts
|
||||
git commit -s -m "feat(http): complete HEAD and OPTIONS semantics"
|
||||
```
|
||||
|
||||
### Task 5: Project constraints into OpenAPI and introspection
|
||||
|
||||
**Skills:** `@superpowers:test-driven-development`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/openapi.ts`
|
||||
- Modify: `src/app/introspect.ts`
|
||||
- Test: `test/openapi.test.ts`
|
||||
- Test: `test/graph-viz.test.ts`
|
||||
|
||||
**Step 1: Write failing OpenAPI tests**
|
||||
|
||||
Add `@Get('/:id(\\d+)')`, explicit `@Head`, and explicit `@Options` routes to the fixture. Assert:
|
||||
|
||||
```typescript
|
||||
expect(doc.paths['/api/users/{id}']).toBeDefined();
|
||||
expect((doc.paths['/api/users/{id}'].get as any).parameters).toContainEqual(
|
||||
expect.objectContaining({ name: 'id', schema: { type: 'string', pattern: '\\d+' } }),
|
||||
);
|
||||
expect(doc.paths['/api/users/{id}'].head).toBeDefined();
|
||||
expect(doc.paths['/api/users/{id}'].options).toBeDefined();
|
||||
```
|
||||
|
||||
Assert that automatic HEAD/OPTIONS operations are not invented.
|
||||
|
||||
**Step 2: Run tests and confirm RED**
|
||||
|
||||
```bash
|
||||
npx vitest run test/openapi.test.ts test/graph-viz.test.ts
|
||||
```
|
||||
|
||||
Expected: constrained template parsing or schema assertions fail.
|
||||
|
||||
**Step 3: Implement projection**
|
||||
|
||||
Reuse the route compiler's parsed segment data instead of parsing the syntax a second way. Convert params and catch-alls to `{name}`. Add `schema.pattern` only for constrained params. Ensure `inspect`, `explain`, Mermaid, and DOT retain the human-readable original pattern.
|
||||
|
||||
**Step 4: Run tests and typecheck**
|
||||
|
||||
```bash
|
||||
npx vitest run test/openapi.test.ts test/graph-viz.test.ts test/app.test.ts
|
||||
npm run typecheck
|
||||
```
|
||||
|
||||
Expected: all pass.
|
||||
|
||||
**Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/openapi.ts src/app/introspect.ts test/openapi.test.ts test/graph-viz.test.ts
|
||||
git commit -s -m "feat(openapi): document constrained route params"
|
||||
```
|
||||
|
||||
### Task 6: Remove root and website dependency advisories
|
||||
|
||||
**Skills:** `@security-review`
|
||||
|
||||
**Files:**
|
||||
- Modify: `package.json`
|
||||
- Modify: `package-lock.json`
|
||||
- Modify: `website/package.json`
|
||||
- Modify: `website/package-lock.json`
|
||||
- Test: `bench/servers/nestjs-express.ts`
|
||||
- Test: `bench/servers/nestjs-fastify.ts`
|
||||
|
||||
**Step 1: Record the failing audit baseline**
|
||||
|
||||
```bash
|
||||
npm audit
|
||||
npm --prefix website audit
|
||||
npm audit --omit=dev
|
||||
```
|
||||
|
||||
Expected: root full audit reports 17 advisories, website reports 3, runtime-only root reports 0.
|
||||
|
||||
**Step 2: Apply supported direct updates**
|
||||
|
||||
Update root dependencies with explicit commands so the manifests and lockfile agree:
|
||||
|
||||
```bash
|
||||
npm install --save-dev vitest@^3.2.6 \
|
||||
@nestjs/common@^11.1.28 @nestjs/core@^11.1.28 \
|
||||
@nestjs/platform-express@^11.1.28 @nestjs/platform-fastify@^11.1.28 \
|
||||
fastify@^5.11.0 miniflare@^4.20260730.0 \
|
||||
@eslint/js@^9.39.5 eslint@^9.39.5 prettier@^3.9.6 \
|
||||
tsx@^4.23.5 typescript-eslint@^8.65.0 ws@^8.21.1
|
||||
npm --prefix website install astro@^7.1.6 @astrojs/starlight@^0.41.6
|
||||
```
|
||||
|
||||
Do not bump TypeScript, ESLint, or GraphQL across their next major versions.
|
||||
|
||||
**Step 3: Add narrow overrides only for unresolved vulnerable transitives**
|
||||
|
||||
Run `npm audit --json` and inspect the exact remaining paths. Add the smallest overrides justified by that output, initially:
|
||||
|
||||
```json
|
||||
{
|
||||
"overrides": {
|
||||
"@nestjs/platform-fastify": {
|
||||
"find-my-way": "9.7.0"
|
||||
},
|
||||
"autocannon": {
|
||||
"hyperid": {
|
||||
"uuid": "11.1.1"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If npm rejects nested override syntax, express the same ownership with `$` references or the supported nested-object form for the installed npm version. Never add a global override when a package-scoped one works.
|
||||
|
||||
**Step 4: Prove compatibility before accepting overrides**
|
||||
|
||||
```bash
|
||||
npm run typecheck
|
||||
npm test
|
||||
npm run bench
|
||||
```
|
||||
|
||||
Expected: tests pass; Express, Fastify, Nest Express, and Nest Fastify scenarios start and complete; Autocannon produces all scenario rows. If the UUID override breaks Autocannon, revert only that override and replace/isolate Autocannon in a follow-up commit within this task until the full audit is clean.
|
||||
|
||||
**Step 5: Verify clean audits**
|
||||
|
||||
```bash
|
||||
npm audit
|
||||
npm audit --omit=dev
|
||||
npm --prefix website audit
|
||||
```
|
||||
|
||||
Expected: all three commands exit 0 with zero vulnerabilities.
|
||||
|
||||
**Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add package.json package-lock.json website/package.json website/package-lock.json
|
||||
git commit -s -m "chore(deps): remediate security advisories"
|
||||
```
|
||||
|
||||
### Task 7: Add security and documentation gates to CI
|
||||
|
||||
**Skills:** `@security-review`
|
||||
|
||||
**Files:**
|
||||
- Modify: `.github/workflows/ci.yml`
|
||||
- Modify: `.github/workflows/release.yml`
|
||||
|
||||
**Step 1: Define the expected gates**
|
||||
|
||||
The CI job must install root and website lockfiles, audit both, build docs, and preserve the existing Node 18 package gate. The GitHub-only release job must audit the root tree immediately after `npm ci` and before `npm publish`.
|
||||
|
||||
**Step 2: Update CI**
|
||||
|
||||
Add these steps after the root `npm ci`:
|
||||
|
||||
```yaml
|
||||
- run: npm audit
|
||||
- run: npm ci --prefix website
|
||||
- run: npm audit --prefix website
|
||||
- run: npm run docs:build
|
||||
```
|
||||
|
||||
Keep lint, format, complexity, typecheck, test, and build unchanged.
|
||||
|
||||
**Step 3: Update the GitHub release gate**
|
||||
|
||||
Add `npm audit` after `npm ci` in `.github/workflows/release.yml`. Do not change the tag trigger, Gitea server guard, Node 22 OIDC setup, dist-tag derivation, or `npm publish` command.
|
||||
|
||||
Do not modify `stage.yml` or `promote.yml`; their verified GitFlow responsibilities remain:
|
||||
|
||||
- Gitea `main` → Verdaccio `stg`;
|
||||
- Gitea `main` and `v*` tags → GitHub;
|
||||
- GitHub `v*` → npm OIDC release.
|
||||
|
||||
**Step 4: Validate workflow syntax and diff**
|
||||
|
||||
```bash
|
||||
npx prettier --check .github/workflows/ci.yml .github/workflows/release.yml
|
||||
git diff --check
|
||||
```
|
||||
|
||||
If Prettier does not parse the workflow format in this repo, inspect with `ruby -e "require 'yaml'; YAML.load_file(ARGV[0])" <file>` and record that command instead.
|
||||
|
||||
**Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add .github/workflows/ci.yml .github/workflows/release.yml
|
||||
git commit -s -m "ci: gate releases on clean dependency audits"
|
||||
```
|
||||
|
||||
### Task 8: Audit and align the complete website documentation
|
||||
|
||||
**Skills:** `@writing-clearly-and-concisely`
|
||||
|
||||
**Files:**
|
||||
- Review: every page under `website/src/content/docs/`
|
||||
- Modify: `website/src/content/docs/guides/routing.md`
|
||||
- Modify: `website/src/content/docs/reference/decorators.md`
|
||||
- Modify: `website/src/content/docs/guides/openapi.md`
|
||||
- Modify: any other website page whose API, behavior, example, or cross-link has drifted from the code
|
||||
- Create: `website/src/content/docs/404.md`
|
||||
|
||||
**Step 1: Build a code-backed website documentation inventory**
|
||||
|
||||
Compare every website page with the current public exports in `src/index.ts`, app options and methods in `src/app/types.ts`, decorator metadata in `src/metadata.ts`, routing behavior in `src/http/router.ts`, and the executable tests. Search the whole documentation tree for stale method lists, obsolete limitations, old error semantics, old beta/version examples, broken internal links, and examples that no longer typecheck conceptually.
|
||||
|
||||
Do not change a claim from memory. Each correction must be supported by code or a passing test.
|
||||
|
||||
**Step 2: Update routing documentation from the verified behavior**
|
||||
|
||||
Document:
|
||||
|
||||
- `@Head` and `@Options`;
|
||||
- explicit-route priority and automatic fallbacks;
|
||||
- canonical `Allow` behavior;
|
||||
- `/path` equals `/path/`;
|
||||
- `//` and malformed encoding return `400`;
|
||||
- catch-all must be final;
|
||||
- `:id(\\d+)`, whole-segment matching, precedence, and the safe-subset restriction;
|
||||
- the matcher remains linear and a radix tree remains deferred.
|
||||
|
||||
Remove the current statement that bare OPTIONS returns 405.
|
||||
|
||||
**Step 3: Align cross-cutting website references**
|
||||
|
||||
At minimum, verify and correct:
|
||||
|
||||
- every buffered-method list to include or intentionally exclude `HEAD`/`OPTIONS` according to the actual API;
|
||||
- `405`, automatic `OPTIONS`, implicit `HEAD`, CORS-preflight, malformed-path, and security-header descriptions;
|
||||
- OpenAPI behavior: explicit HEAD/OPTIONS appear as operations, constrained params produce `schema.pattern`, and automatic fallbacks remain absent;
|
||||
- mesh route-conflict wording after effective-pattern normalization;
|
||||
- examples and links between routing, decorators, errors, HTML, streaming, security, OpenAPI, and `createApp` reference pages;
|
||||
- navigation/frontmatter descriptions that still advertise the old router surface.
|
||||
|
||||
Keep intentional historical or roadmap statements only when they remain true.
|
||||
|
||||
**Step 4: Fix the Starlight 404 warning**
|
||||
|
||||
Create the missing `404.md` entry with valid Starlight frontmatter and concise navigation back to the docs index. Run `npm run docs:build` and confirm the line `Entry docs → 404 was not found` disappears.
|
||||
|
||||
**Step 5: Validate the whole website documentation tree**
|
||||
|
||||
```bash
|
||||
npm run docs:build
|
||||
npm --prefix website audit
|
||||
rg -n 'Not built|bare `OPTIONS`|returns `405`|@Get.*@Post.*@Put.*@Patch.*@Delete' website/src/content/docs
|
||||
rg -n '\]\(/docs/' website/src/content/docs
|
||||
git diff --check
|
||||
```
|
||||
|
||||
Expected: all 23+ pages build without the missing-404 warning, the website audit remains clean, obsolete router claims are gone, and every changed claim has a code/test source.
|
||||
|
||||
**Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add website/src/content/docs
|
||||
git commit -s -m "docs(website): align guides with router behavior"
|
||||
```
|
||||
|
||||
### Task 9: Align package documentation and prepare the August beta
|
||||
|
||||
**Skills:** `@writing-clearly-and-concisely`
|
||||
|
||||
**Files:**
|
||||
- Modify: `README.md`
|
||||
- Modify: `CHANGELOG.md`
|
||||
- Modify: `src/index.ts`
|
||||
- Modify: `package.json`
|
||||
- Modify: `package-lock.json`
|
||||
|
||||
**Step 1: Align the package-facing documentation**
|
||||
|
||||
Update README routing, roadmap, method, security, and beta-status claims from the same verified behavior documented in the website. Keep README concise and link to the complete website guides rather than duplicating their full reference material.
|
||||
|
||||
**Step 2: Bump the beta version consistently**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
npm version 26.8.0-beta.0 --no-git-tag-version
|
||||
```
|
||||
|
||||
Update `src/index.ts`'s `VERSION` constant and add a `26.8.0-beta.0` CHANGELOG entry covering routes, security remediation, docs, and compatibility. Confirm README's CalVer examples remain accurate.
|
||||
|
||||
**Step 3: Verify docs and version consistency**
|
||||
|
||||
```bash
|
||||
npm run docs:build
|
||||
node -e "const p=require('./package.json'); const l=require('./package-lock.json'); if (p.version !== l.version || p.version !== l.packages[''].version) process.exit(1)"
|
||||
rg -n '26\.7\.0-beta\.0|Not built|bare `OPTIONS`' README.md CHANGELOG.md src website/src/content/docs
|
||||
git diff --check
|
||||
```
|
||||
|
||||
Expected: package versions agree, website docs still build, and any old beta string is retained only in historical release examples.
|
||||
|
||||
**Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add README.md CHANGELOG.md src/index.ts package.json package-lock.json
|
||||
git commit -s -m "docs: document router completeness for beta"
|
||||
```
|
||||
|
||||
### Task 10: Run the complete release-candidate verification
|
||||
|
||||
**Skills:** `@superpowers:verification-before-completion`, `@security-review`
|
||||
|
||||
**Files:**
|
||||
- Modify only if a verification failure reveals an in-scope defect.
|
||||
|
||||
**Step 1: Run static and Node gates**
|
||||
|
||||
```bash
|
||||
npm run lint
|
||||
npm run format:check
|
||||
npm run complexity:check
|
||||
npm run typecheck
|
||||
npm run typecheck:bench
|
||||
npm test
|
||||
npm run build
|
||||
```
|
||||
|
||||
Expected: every command exits 0. Record the existing lint-warning count separately; introduce no new warnings.
|
||||
|
||||
**Step 2: Run multi-runtime gates**
|
||||
|
||||
```bash
|
||||
npm run test:deno
|
||||
npm run test:bun
|
||||
npm run test:edge
|
||||
```
|
||||
|
||||
Expected: every installed runtime suite exits 0. If a runtime is unavailable, report the exact missing command; do not claim that suite passed.
|
||||
|
||||
**Step 3: Run security, docs, and benchmark gates**
|
||||
|
||||
```bash
|
||||
npm audit
|
||||
npm audit --omit=dev
|
||||
npm --prefix website audit
|
||||
npm run docs:build
|
||||
npm run bench
|
||||
```
|
||||
|
||||
Expected: zero advisories; docs build without warning; all benchmark scenarios complete.
|
||||
|
||||
**Step 4: Inspect the publish artifact without publishing**
|
||||
|
||||
```bash
|
||||
npm pack --dry-run
|
||||
```
|
||||
|
||||
Expected: package contains `dist`, assets, README, CHANGELOG, and LICENSE; version is `26.8.0-beta.0`; no docs worktree, tests, secrets, or local environment files appear.
|
||||
|
||||
**Step 5: Review branch and workflow boundaries**
|
||||
|
||||
```bash
|
||||
git status --short --branch
|
||||
git log --oneline --decorate develop..HEAD
|
||||
git diff --check develop...HEAD
|
||||
git diff --stat develop...HEAD
|
||||
```
|
||||
|
||||
Expected: clean `feat/router-security-beta`; all commits carry `Signed-off-by`; no tag, registry publication, `main` merge, or workflow secret change occurred.
|
||||
|
||||
**Step 6: Commit any verification-only repair**
|
||||
|
||||
Only if Step 1–5 exposed an in-scope defect:
|
||||
|
||||
```bash
|
||||
git add <exact repaired files>
|
||||
git commit -s -m "fix: address beta verification findings"
|
||||
```
|
||||
|
||||
Re-run the failed gate and the complete related suite after any repair.
|
||||
@@ -1,312 +0,0 @@
|
||||
# green-tea — Quickstart
|
||||
|
||||
A type-safe HTTP framework where the request/boot pipeline is an explicit **dependency
|
||||
graph**. You declare what you need; the framework computes the order, validates it at boot,
|
||||
and can extend the graph over time (streams) and across machines (mesh).
|
||||
|
||||
See [architecture.md](./architecture.md) for the mental map.
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
npm install @green-tea/core reflect-metadata
|
||||
# ws is an OPTIONAL peer dependency — only needed for WebSocket / mesh on Node:
|
||||
npm install ws # optional
|
||||
```
|
||||
|
||||
`tsconfig.json` must enable decorator metadata:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"compilerOptions": {
|
||||
"experimentalDecorators": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"target": "es2017",
|
||||
"module": "commonjs"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Import `reflect-metadata` once at your entrypoint.
|
||||
|
||||
## 1. A route with dependency injection
|
||||
|
||||
A **provider** is an app-scope singleton. A **step** runs per request and transforms the
|
||||
context. A handler's **argument decorators are its dependency declaration** — ask for what
|
||||
you want, in any order. If you `@needs` a token nothing produces, you get a **boot error**,
|
||||
not an `undefined` at runtime.
|
||||
|
||||
```typescript
|
||||
import 'reflect-metadata';
|
||||
import { createApp, Provider, Step, Route, Get, Module, Unauthorized, needs, param } from '@green-tea/core';
|
||||
|
||||
@Provider({ provides: 'db' })
|
||||
class Database {
|
||||
provide() { return { db: { find: (id: string) => ({ id, name: 'Diego' }) } }; }
|
||||
}
|
||||
|
||||
@Step({ provides: 'user', needs: ['db', 'req'] })
|
||||
class Authenticate {
|
||||
run(ctx: any) {
|
||||
const user = ctx.db.find(ctx.req.headers['x-token']);
|
||||
if (!user) throw new Unauthorized('bad token'); // throw = short-circuit the pipeline
|
||||
return { user }; // return = continue, merge into ctx
|
||||
}
|
||||
}
|
||||
|
||||
@Route('/users')
|
||||
class UserController {
|
||||
@Get('/:id')
|
||||
getUser(@needs('user') user: any, @param('id') id: string) {
|
||||
return { requested: id, you: user }; // auto-serialized as JSON
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/api', providers: [Database], steps: [Authenticate], controllers: [UserController] })
|
||||
class ApiModule {}
|
||||
|
||||
const app = createApp({ modules: [ApiModule] });
|
||||
await app.listen(3000);
|
||||
// GET /api/users/9 (header x-token) → { "requested": "9", "you": { "id": "...", "name": "Diego" } }
|
||||
|
||||
await app.close(); // graceful shutdown: drains in-flight requests, closes streams + mesh links
|
||||
```
|
||||
|
||||
> **Per-route execution (important).** Each route runs **only the providers/steps in the transitive
|
||||
> closure of its handler's `@needs`** — nothing else. A route that doesn't `@needs('user')` does **not**
|
||||
> run the `Authenticate` step. This means a cross-cutting *enforcement* step (e.g. auth that throws 401)
|
||||
> only protects routes that actually `@needs` its token. To run something on **every** route regardless
|
||||
> of needs (logging, audit, a global guard), add it as a **plugin step** via `scope.add({ ..., provides: [] })` —
|
||||
> steps that produce nothing run unconditionally. Don't rely on a token-providing step to guard routes
|
||||
> that don't declare it.
|
||||
|
||||
### Argument decorators
|
||||
|
||||
| Decorator | Reads from | Adds a graph dependency? |
|
||||
|---|---|---|
|
||||
| `@needs('user')` | a value produced by a provider/step | **yes** (boot-validated) |
|
||||
| `@ctx()` | the whole accumulated context | no |
|
||||
| `@param('id')` | route params | no |
|
||||
| `@query('q')` | parsed query string | no |
|
||||
| `@body()` | parsed JSON body | no |
|
||||
| `@headers('x')` | request headers | no |
|
||||
| `@inbound()` | the incoming WS message channel | no (WS only) |
|
||||
| `@abort()` | an `AbortSignal` that fires on disconnect | no (stream/WS) |
|
||||
|
||||
Each envelope decorator has three forms: `@query()` (whole object), `@query('q')` (one key),
|
||||
`@query(['q','date'])` (subset).
|
||||
|
||||
## 2. Compile-time guarantee with `flow`
|
||||
|
||||
The decorator layer validates the graph at boot. The functional core `flow` validates it in
|
||||
the **type checker**:
|
||||
|
||||
```typescript
|
||||
import { flow } from '@green-tea/core';
|
||||
|
||||
const pipeline = flow()
|
||||
.step('db', () => ({ find: (id: string) => id }))
|
||||
.step('user', (ctx) => ctx.db.find('u1')); // referencing a missing 'db' would not compile
|
||||
```
|
||||
|
||||
## 3. Streaming — SSE
|
||||
|
||||
Return an `AsyncIterable` and the pipeline streams it (the transformer is bypassed; the
|
||||
transport frames it, handles backpressure, and cleans up on disconnect).
|
||||
|
||||
```typescript
|
||||
import { Route, Sse } from '@green-tea/core';
|
||||
|
||||
@Route('/feed')
|
||||
class FeedController {
|
||||
@Sse('/ticks')
|
||||
ticks() {
|
||||
return (async function* () {
|
||||
for (let n = 1; n <= 3; n++) yield { tick: n };
|
||||
})();
|
||||
}
|
||||
}
|
||||
// GET /feed/ticks (Accept: text/event-stream)
|
||||
// data: {"tick":1}
|
||||
// data: {"tick":2}
|
||||
// data: {"tick":3}
|
||||
```
|
||||
|
||||
`@Stream(path)` negotiates the transport by header (`Accept: text/event-stream` → SSE,
|
||||
`Upgrade: websocket` → WS, else ndjson chunked).
|
||||
|
||||
## 4. Streaming — WebSocket duplex
|
||||
|
||||
A WS handler receives the **inbound** channel and returns the **outbound** channel — a step
|
||||
that consumes one channel and produces another.
|
||||
|
||||
```typescript
|
||||
import { Route, Ws, inbound, channel } from '@green-tea/core';
|
||||
|
||||
@Route('/chat')
|
||||
class ChatController {
|
||||
@Ws('/echo')
|
||||
echo(@inbound() incoming: AsyncIterable<string>) {
|
||||
const out = channel<string>();
|
||||
(async () => {
|
||||
for await (const msg of incoming) out.push(`echo: ${msg}`);
|
||||
out.close();
|
||||
})();
|
||||
return out;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`channel<T>()` is a multicast `AsyncIterable` with `push` / `close` / `fail` and an optional
|
||||
bounded buffer (`channel({ buffer: 100 })`, drop-oldest).
|
||||
|
||||
## 5. Mesh — distributed dependency injection
|
||||
|
||||
A **teacup** can depend on a token that physically lives on a **teapot**. Exports are
|
||||
opt-in (`export: true`) and the control channel is gated by a shared secret.
|
||||
|
||||
**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], 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],
|
||||
mesh: { teapots: [{ url: 'ws://A-host:3002/__mesh__/control', secret: 'shh' }] },
|
||||
});
|
||||
await teacup.listen(3003);
|
||||
// GET B:3003/api/local/who (x-token: abc)
|
||||
// → { "config": { "region": "mx", "tier": "pro" }, "auth": { "token": "abc" } }
|
||||
```
|
||||
|
||||
`@needs('config' | 'auth')` validates at boot because the teapot announced them in its
|
||||
manifest on connect. A provider export is app-scope (resolved once, cached); a step export is
|
||||
request-scope (RPC per request, carrying the request envelope).
|
||||
|
||||
> Skeleton limitations (by design): no discovery, load-balancing, or failover yet; app-scope
|
||||
> remote values are not reconciled on reconnect; the request envelope omits `req.url`.
|
||||
|
||||
## 6. Plugins & observability
|
||||
|
||||
```typescript
|
||||
const logger = (api: any) => {
|
||||
api.bus.on('request:step:enter', (p: any) => console.log(`→ ${p.name}`));
|
||||
api.bus.on('stream:open', (p: any) => console.log(`stream open ${p.name}`));
|
||||
api.bus.on('mesh:rpc:error', (p: any) => console.error('mesh rpc failed', p.error));
|
||||
};
|
||||
|
||||
const app = createApp({ modules: [ApiModule], plugins: [logger] });
|
||||
```
|
||||
|
||||
Lifecycle events: `boot:provider:*`, `request:step:*`, `stream:open|close|error`,
|
||||
`mesh:connect|disconnect|rpc:error`, `plugin:mounted`.
|
||||
|
||||
## Inspect & test the graph
|
||||
|
||||
### Visualize with Mermaid
|
||||
|
||||
```typescript
|
||||
console.log(app.toMermaid()); // flowchart diagram of all nodes and routes
|
||||
```
|
||||
|
||||
Enable a live `GET /__graph__` endpoint (renders HTML with Mermaid, or plain-text with `Accept: text/plain`):
|
||||
|
||||
```typescript
|
||||
const app = createApp({ modules: [ApiModule], devGraph: true });
|
||||
// GET /__graph__ → HTML viewer
|
||||
// GET /__graph__ (text/plain) → raw Mermaid source
|
||||
```
|
||||
|
||||
### Explain a route
|
||||
|
||||
```typescript
|
||||
const e = app.explain('/api/users/:id');
|
||||
// { pattern, method, transport, chain: [{ name, kind, origin, needs, provides }, ...] }
|
||||
console.log(e.chain.map((n) => `${n.kind}:${n.name}`));
|
||||
// → ['provider:db', 'step:user', 'handler:getUser']
|
||||
```
|
||||
|
||||
### Override tokens in tests
|
||||
|
||||
Swap any provider or step token with a test double at construction time — no monkey-patching:
|
||||
|
||||
```typescript
|
||||
const app = createApp({
|
||||
modules: [ApiModule],
|
||||
overrides: {
|
||||
db: { find: () => ({ id: 'test-user' }) }, // plain object — wrapped as { db: value }
|
||||
user: () => ({ user: { id: 'stub' } }), // function runner
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Overrides replace only the named token's runner; the rest of the graph is untouched.
|
||||
|
||||
## Runnable examples
|
||||
|
||||
The `example/` directory holds end-to-end apps you can `node`-run and read top to bottom.
|
||||
|
||||
### CRUD — methods, query, JSON & urlencoded body
|
||||
|
||||
`@Get/@Post/@Put/@Patch/@Delete` over a provider-backed store. Filter via `@query('done')`,
|
||||
read the payload via `@body()` — the same handler accepts both `application/json` and
|
||||
`application/x-www-form-urlencoded` (the transport parses each into a plain object). Missing
|
||||
rows throw `NotFound` (→ 404).
|
||||
|
||||
See [`example/crud.ts`](../example/crud.ts).
|
||||
|
||||
### Chat — rooms + handshake auth
|
||||
|
||||
A `@Step` reads `?token=` and `provides: 'user'`, throwing `Unauthorized` on a missing token —
|
||||
which closes the socket with code **4401** (`4000 + status`). The `@Ws` handler pumps the
|
||||
`@inbound()` channel into `rooms.room(name)` and returns that same room as its outbound channel,
|
||||
so every joined socket multicasts to the others. `rooms` is the built-in shared `Rooms`
|
||||
primitive (one instance app-wide).
|
||||
|
||||
See [`example/chat.ts`](../example/chat.ts).
|
||||
|
||||
### GraphQL — query/mutation over POST, subscription over SSE
|
||||
|
||||
A schema built programmatically with `graphql` (a dev/example dependency — the core has no
|
||||
runtime dep on it). `POST /graphql` runs queries and mutations through `graphql()`. The
|
||||
`mutation` pushes each new message into `rooms.room('messages')`; the `@Sse('/stream')` route
|
||||
calls `subscribe()` whose source **is** that room, guards the result with `isAsyncIterable`,
|
||||
and returns it — the framework streams each `ExecutionResult` as an SSE `data:` frame. This is
|
||||
the tie between GraphQL, green-tea streams, and the `rooms` primitive.
|
||||
|
||||
See [`example/graphql.ts`](../example/graphql.ts) — `npm install graphql` first.
|
||||
|
||||
## The one rule to remember
|
||||
|
||||
```
|
||||
return a VALUE → buffered response (transformer → JSON)
|
||||
return an AsyncIterable → stream (SSE / WS)
|
||||
@needs a remote token → RPC to a teapot (mesh)
|
||||
```
|
||||
@@ -0,0 +1,26 @@
|
||||
import js from '@eslint/js';
|
||||
import tseslint from 'typescript-eslint';
|
||||
import stylistic from '@stylistic/eslint-plugin';
|
||||
|
||||
export default tseslint.config(
|
||||
{ ignores: ['dist', 'node_modules', 'bench', 'coverage'] },
|
||||
js.configs.recommended,
|
||||
...tseslint.configs.recommended,
|
||||
{
|
||||
plugins: { '@stylistic': stylistic },
|
||||
rules: {
|
||||
// The request pipeline accumulates a dynamic context object by design;
|
||||
// `any` there is load-bearing, not laziness. Flag it as a warning so new
|
||||
// uses are visible without failing the build.
|
||||
'@typescript-eslint/no-explicit-any': 'warn',
|
||||
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }],
|
||||
// Breathing room around multi-line blocks (for/while/if/function/class) so
|
||||
// consecutive blocks don't read as one wall of code. Auto-fixable.
|
||||
'@stylistic/padding-line-between-statements': [
|
||||
'error',
|
||||
{ blankLine: 'always', prev: 'multiline-block-like', next: '*' },
|
||||
{ blankLine: 'always', prev: '*', next: 'multiline-block-like' },
|
||||
],
|
||||
},
|
||||
},
|
||||
);
|
||||
+1
-1
@@ -101,7 +101,7 @@ class PingController {
|
||||
@Module({ mountpoint: '/mesh', providers: [ConfigProvider], steps: [AuthStep], controllers: [PingController] })
|
||||
class TeapotModule {}
|
||||
|
||||
export const teapotApp = createApp({ modules: [TeapotModule], mesh: { secret: 'demo-secret' } });
|
||||
export const teapotApp = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'demo-secret' } });
|
||||
|
||||
@Route('/remote')
|
||||
class TeacupController {
|
||||
|
||||
Generated
+7678
-241
File diff suppressed because it is too large.
Load diff
+137
-8
@@ -1,34 +1,163 @@
|
||||
{
|
||||
"name": "@green-tea/core",
|
||||
"version": "0.0.0",
|
||||
"description": "Declarative, type-safe HTTP framework. The pipeline is a graph, not a middleware chain.",
|
||||
"version": "26.8.0-beta.0",
|
||||
"description": "You declare what each step needs and provides; green-tea computes the execution order, fails at boot if something is missing, and prints the whole pipeline. HTTP, SSE and WebSocket on Node, Deno, Bun and the edge.",
|
||||
"license": "MIT",
|
||||
"author": "green-tea contributors",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/Expressive-Tea/green-tea.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/Expressive-Tea/green-tea/issues"
|
||||
},
|
||||
"homepage": "https://green-tea.expressive-tea.io/docs/",
|
||||
"keywords": [
|
||||
"http",
|
||||
"framework",
|
||||
"typescript",
|
||||
"dependency-injection",
|
||||
"decorators",
|
||||
"dependency-graph",
|
||||
"sse",
|
||||
"websocket",
|
||||
"streaming",
|
||||
"node"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"type": "commonjs",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"import": {
|
||||
"types": "./dist/index.d.mts",
|
||||
"default": "./dist/index.mjs"
|
||||
},
|
||||
"require": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"./deno": {
|
||||
"import": {
|
||||
"types": "./dist/deno.d.mts",
|
||||
"default": "./dist/deno.mjs"
|
||||
},
|
||||
"require": {
|
||||
"types": "./dist/deno.d.ts",
|
||||
"default": "./dist/deno.js"
|
||||
}
|
||||
},
|
||||
"./bun": {
|
||||
"import": {
|
||||
"types": "./dist/bun.d.mts",
|
||||
"default": "./dist/bun.mjs"
|
||||
},
|
||||
"require": {
|
||||
"types": "./dist/bun.d.ts",
|
||||
"default": "./dist/bun.js"
|
||||
}
|
||||
},
|
||||
"./edge": {
|
||||
"import": {
|
||||
"types": "./dist/edge.d.mts",
|
||||
"default": "./dist/edge.mjs"
|
||||
},
|
||||
"require": {
|
||||
"types": "./dist/edge.d.ts",
|
||||
"default": "./dist/edge.js"
|
||||
}
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"assets",
|
||||
"README.md",
|
||||
"CHANGELOG.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"build": "tsup",
|
||||
"test": "vitest run",
|
||||
"test:dev": "vitest",
|
||||
"typecheck": "tsc --noEmit -p tsconfig.json"
|
||||
"test:deno": "deno test --allow-net --allow-read --allow-run --allow-env --no-check test/deno/",
|
||||
"test:bun": "bun test test/bun/",
|
||||
"test:edge": "tsx test/edge/run.ts",
|
||||
"typecheck": "tsc --noEmit -p tsconfig.json",
|
||||
"typecheck:bench": "tsc --noEmit -p bench/tsconfig.json",
|
||||
"lint": "eslint src",
|
||||
"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",
|
||||
"bench": "tsx bench/run.ts",
|
||||
"prepublishOnly": "npm run lint && npm run complexity:check && npm run typecheck && npm test && npm run build",
|
||||
"prepare": "git config core.hooksPath .githooks || true"
|
||||
},
|
||||
"dependencies": {
|
||||
"reflect-metadata": "0.2.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"busboy": "^1.6.0",
|
||||
"ws": "^8.18.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"busboy": {
|
||||
"optional": true
|
||||
},
|
||||
"ws": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"overrides": {
|
||||
"find-my-way": "9.7.0",
|
||||
"autocannon": {
|
||||
"hyperid": {
|
||||
"uuid": "11.1.1"
|
||||
}
|
||||
},
|
||||
"undici": "7.29.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.5",
|
||||
"@nestjs/common": "^11.1.28",
|
||||
"@nestjs/core": "^11.1.28",
|
||||
"@nestjs/platform-express": "^11.1.28",
|
||||
"@nestjs/platform-fastify": "^11.1.28",
|
||||
"@stylistic/eslint-plugin": "^5.10.0",
|
||||
"@types/autocannon": "^7.12.7",
|
||||
"@types/busboy": "^1.5.4",
|
||||
"@types/express": "^5.0.6",
|
||||
"@types/node": "^18.19.0",
|
||||
"@types/ws": "^8.18.1",
|
||||
"autocannon": "^8.0.0",
|
||||
"busboy": "^1.6.0",
|
||||
"cognitive-complexity-ts": "^0.8.2",
|
||||
"eslint": "^9.39.5",
|
||||
"esbuild": "0.27.2",
|
||||
"express": "^5.2.1",
|
||||
"fastify": "^5.11.0",
|
||||
"graphql": "^16.9.0",
|
||||
"miniflare": "^4.20260730.0",
|
||||
"prettier": "^3.9.6",
|
||||
"rxjs": "^7.8.2",
|
||||
"tsup": "^8.5.1",
|
||||
"tsx": "^4.23.5",
|
||||
"typescript": "^5.5.0",
|
||||
"vitest": "^2.0.0",
|
||||
"ws": "^8.21.0"
|
||||
"typescript-eslint": "^8.65.0",
|
||||
"vite": "^6.4.3",
|
||||
"vitest": "^3.2.7",
|
||||
"ws": "^8.21.1"
|
||||
}
|
||||
}
|
||||
Executable
+42
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env node
|
||||
// Cognitive-complexity gate. Fails (exit 1) if any named function in src/ exceeds
|
||||
// the threshold, per cognitive-complexity-ts. Cyclomatic complexity is intentionally
|
||||
// NOT gated here — its `??`-chain false positives make it advisory only (npm run complexity:cyclomatic).
|
||||
import { execSync } from 'node:child_process';
|
||||
|
||||
const THRESHOLD = Number(process.env.COMPLEXITY_MAX ?? 25);
|
||||
|
||||
let raw = '';
|
||||
try {
|
||||
raw = execSync('npx ccts-json src', { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
|
||||
} catch (error) {
|
||||
raw = error.stdout?.toString() ?? '';
|
||||
}
|
||||
|
||||
if (!raw.trim()) {
|
||||
console.error('check-complexity: no output from ccts-json');
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const offenders = [];
|
||||
function walk(node) {
|
||||
if (!node || typeof node !== 'object') return;
|
||||
if (node.kind === 'function' && node.name && node.score > THRESHOLD) {
|
||||
offenders.push({ score: node.score, name: node.name });
|
||||
}
|
||||
for (const [key, value] of Object.entries(node)) {
|
||||
if (key === 'inner' && Array.isArray(value)) value.forEach(walk);
|
||||
else if (value && typeof value === 'object') walk(value);
|
||||
}
|
||||
}
|
||||
walk(JSON.parse(raw));
|
||||
|
||||
if (offenders.length) {
|
||||
offenders.sort((a, b) => b.score - a.score);
|
||||
console.error(`\n✖ cognitive complexity: ${offenders.length} function(s) over ${THRESHOLD}\n`);
|
||||
for (const o of offenders) console.error(` ${String(o.score).padStart(4)} ${o.name}`);
|
||||
console.error('\nExtract helpers to bring them under the threshold (or raise COMPLEXITY_MAX).\n');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(`✓ cognitive complexity: every function ≤ ${THRESHOLD}`);
|
||||
-381
@@ -1,381 +0,0 @@
|
||||
import http from 'http';
|
||||
import { Bus } from './bus';
|
||||
import { Container } from './container';
|
||||
import { topoSort, subgraphFor, GraphNode, nearest } from './graph';
|
||||
import { toMermaid, toDOT, graphHtml, type GraphView } from './graph-viz';
|
||||
import { runPipeline, PipelineStep } from './pipeline';
|
||||
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from './http';
|
||||
import { isAsyncIterable } from './channel';
|
||||
import { JsonTransformer } from './transformers';
|
||||
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from './plugin';
|
||||
import {
|
||||
Ctor, HttpMethod, Transport, getModuleMeta, getProviderMeta, getStepMeta, getRoutes, getTransformer, joinPath,
|
||||
} from './metadata';
|
||||
import { getArgs, getHandlerNeeds, resolveArgs } from './params';
|
||||
import { connectLink, type Link } from './mesh/link';
|
||||
import { Rooms } from './rooms';
|
||||
import { buildRemote } from './mesh/teacup';
|
||||
import { buildManifest, createMeshControl } from './mesh/teapot';
|
||||
import type { MeshControl } from './http';
|
||||
import type { RequestEnvelope, RouteEntry } from './mesh/protocol';
|
||||
|
||||
export interface InspectLine { name: string; kind: 'provider' | 'step' | 'handler'; origin: string }
|
||||
export interface ExplainNode { name: string; kind: 'provider' | 'step' | 'handler'; origin: string; needs: string[]; provides: string[] }
|
||||
export interface Explain { pattern: string; method: HttpMethod; transport: Transport; chain: ExplainNode[] }
|
||||
export interface App {
|
||||
listen(port: number): Promise<http.Server>;
|
||||
close(): Promise<void>;
|
||||
inspect(routePath: string): InspectLine[];
|
||||
graph(): GraphView;
|
||||
toMermaid(): string;
|
||||
toDOT(): string;
|
||||
explain(routePath: string): Explain;
|
||||
bus: Bus;
|
||||
}
|
||||
|
||||
interface RoutePlan {
|
||||
pattern: string;
|
||||
method: HttpMethod;
|
||||
transport: Transport;
|
||||
origin: string;
|
||||
providers: GraphNode[];
|
||||
steps: GraphNode[];
|
||||
handlerName: string;
|
||||
needs: string[];
|
||||
run: (ctx: any) => unknown;
|
||||
transformer: typeof JsonTransformer;
|
||||
}
|
||||
|
||||
export interface MeshConfig {
|
||||
secret?: string;
|
||||
teapots?: Array<{ url: string; secret: string }>;
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record<string, unknown> }): App {
|
||||
const bus = new Bus();
|
||||
const container = new Container();
|
||||
let server: http.Server | undefined;
|
||||
const streams = new Set<() => void>();
|
||||
const extraSteps: ScopeNode[] = [];
|
||||
const scope: ScopeApi = { add: (n) => extraSteps.push(n) };
|
||||
|
||||
// collect declarations from modules
|
||||
const providerNodes: GraphNode[] = [];
|
||||
const stepNodes: GraphNode[] = [];
|
||||
const runners = new Map<string, (ctx: any) => any>(); // node name -> runtime fn
|
||||
const setRunner = (name: string, fn: (ctx: any) => any) => {
|
||||
if (runners.has(name)) throw new Error(`duplicate provider/step name '${name}' — names must be unique across modules and plugins`);
|
||||
runners.set(name, fn);
|
||||
};
|
||||
const providerMeta = new Map<string, { optional: boolean }>();
|
||||
const routePlans: RoutePlan[] = [];
|
||||
const exportedProviders: string[] = [];
|
||||
const exportedSteps: string[] = [];
|
||||
const exportedRoutes: RouteEntry[] = [];
|
||||
|
||||
for (const mod of opts.modules) {
|
||||
const m = getModuleMeta(mod);
|
||||
if (!m) throw new Error(`${mod.name} is not a @Module`);
|
||||
const origin = `module:${mod.name}`;
|
||||
|
||||
for (const P of m.providers ?? []) {
|
||||
const meta = getProviderMeta(P)!;
|
||||
providerNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin });
|
||||
providerMeta.set(meta.provides, { optional: meta.optional });
|
||||
if (meta.export) exportedProviders.push(meta.provides);
|
||||
const inst: any = new P();
|
||||
setRunner(meta.provides, (ctx) => inst.provide(ctx));
|
||||
}
|
||||
for (const S of m.steps ?? []) {
|
||||
const meta = getStepMeta(S)!;
|
||||
stepNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin });
|
||||
if (meta.export) exportedSteps.push(meta.provides);
|
||||
const inst: any = new S();
|
||||
setRunner(meta.provides, (ctx) => inst.run(ctx));
|
||||
}
|
||||
for (const C of m.controllers ?? []) {
|
||||
for (const route of getRoutes(C)) {
|
||||
const inst: any = new C();
|
||||
const argSpecs = getArgs(C, route.handlerName);
|
||||
const pattern = joinPath(m.mountpoint, route.path);
|
||||
if (route.export) {
|
||||
if (route.transport !== 'buffer') throw new Error(`cannot export streaming route ${pattern}`);
|
||||
exportedRoutes.push({ method: route.method, pattern });
|
||||
}
|
||||
routePlans.push({
|
||||
pattern,
|
||||
method: route.method,
|
||||
transport: route.transport,
|
||||
origin,
|
||||
providers: [],
|
||||
steps: [],
|
||||
handlerName: route.handlerName,
|
||||
needs: getHandlerNeeds(argSpecs),
|
||||
run: (c: any) => inst[route.handlerName](...resolveArgs(argSpecs, c)),
|
||||
transformer: getTransformer(C, route.handlerName) ?? JsonTransformer,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// plugin-added steps join the graph as their own scope
|
||||
for (const plugin of opts.plugins ?? []) mountPlugin(plugin, bus, scope);
|
||||
for (const n of extraSteps) {
|
||||
const node = { name: n.name, needs: n.needs, provides: n.provides, origin: 'plugin' };
|
||||
if (n.kind === 'provider') providerNodes.push(node); else stepNodes.push(node);
|
||||
setRunner(n.name, n.run);
|
||||
}
|
||||
|
||||
// built-in: auto-provide a shared Rooms instance (unless the user declares one)
|
||||
if (!runners.has('rooms')) {
|
||||
const roomsInstance = new Rooms();
|
||||
providerNodes.push({ name: 'rooms', needs: [], provides: ['rooms'], origin: 'builtin' });
|
||||
providerMeta.set('rooms', { optional: false });
|
||||
setRunner('rooms', () => ({ rooms: roomsInstance })); // merge object -> ctx.rooms
|
||||
}
|
||||
|
||||
// For each route, resolve which providers/steps feed it via topo order.
|
||||
// MVP: every route depends on every declared step + provider in the app graph.
|
||||
// For mesh apps, finalize is DEFERRED to listen() so remote scopes can join the graph first.
|
||||
let orderedProviders: GraphNode[] = [];
|
||||
let orderedSteps: GraphNode[] = [];
|
||||
let booted = false;
|
||||
const finalizeGraph = (): void => {
|
||||
const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params']);
|
||||
orderedProviders = ordered.filter((n) => providerNodes.includes(n));
|
||||
orderedSteps = ordered.filter((n) => stepNodes.includes(n));
|
||||
const alwaysSteps = stepNodes.filter((n) => n.provides.length === 0); // side-effect/observer steps (plugins)
|
||||
const alwaysNeeds = alwaysSteps.flatMap((n) => n.needs); // pull observers' deps into every route
|
||||
for (const plan of routePlans) {
|
||||
const closure = subgraphFor([...plan.needs, ...alwaysNeeds], ordered);
|
||||
plan.providers = closure.filter((n) => providerNodes.includes(n));
|
||||
const sliced = new Set<GraphNode>([...closure.filter((n) => stepNodes.includes(n)), ...alwaysSteps]);
|
||||
plan.steps = ordered.filter((n) => stepNodes.includes(n) && sliced.has(n)); // topo order, deduped
|
||||
}
|
||||
|
||||
const producedKeys = new Set<string>([
|
||||
...providerNodes.flatMap((n) => n.provides),
|
||||
...stepNodes.flatMap((n) => n.provides),
|
||||
]);
|
||||
const allowed = new Set<string>([...producedKeys, 'req', 'params', 'query', 'body', 'headers', 'inbound', 'abort']);
|
||||
for (const plan of routePlans) {
|
||||
for (const need of plan.needs) {
|
||||
if (!allowed.has(need)) {
|
||||
const hint = nearest(need, allowed);
|
||||
throw new Error(`handler '${plan.handlerName}' needs '${need}' but nothing (local or mesh) provides it${hint ? ` — did you mean '${hint}'?` : ''}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
booted = true;
|
||||
};
|
||||
if (!opts.mesh) finalizeGraph();
|
||||
|
||||
const inspect = (routePath: string): InspectLine[] => {
|
||||
if (!booted) throw new Error('inspect() unavailable before listen() for mesh apps');
|
||||
const plan = routePlans.find((p) => p.pattern === routePath);
|
||||
if (!plan) throw new Error(`no route: ${routePath}`);
|
||||
return [
|
||||
...plan.providers.map((p) => ({ name: p.name, kind: 'provider' as const, origin: p.origin })),
|
||||
...plan.steps.map((s) => ({ name: s.name, kind: 'step' as const, origin: s.origin })),
|
||||
{ name: plan.handlerName, kind: 'handler' as const, origin: plan.origin },
|
||||
];
|
||||
};
|
||||
|
||||
const graph = (): GraphView => {
|
||||
if (!booted) throw new Error('graph() unavailable before listen() for mesh apps');
|
||||
return {
|
||||
nodes: [
|
||||
...providerNodes.map((n) => ({ name: n.name, kind: 'provider' as const, origin: n.origin, needs: n.needs, provides: n.provides })),
|
||||
...stepNodes.map((n) => ({ name: n.name, kind: 'step' as const, origin: n.origin, needs: n.needs, provides: n.provides })),
|
||||
],
|
||||
routes: routePlans.map((p) => ({
|
||||
pattern: p.pattern, method: p.method, transport: p.transport,
|
||||
chain: [...p.providers.map((n) => n.name), ...p.steps.map((n) => n.name), p.handlerName],
|
||||
})),
|
||||
};
|
||||
};
|
||||
|
||||
const explain = (routePath: string): Explain => {
|
||||
if (!booted) throw new Error('explain() unavailable before listen() for mesh apps');
|
||||
const plan = routePlans.find((p) => p.pattern === routePath);
|
||||
if (!plan) throw new Error(`no route: ${routePath}`);
|
||||
const nv = (n: GraphNode, kind: 'provider' | 'step'): ExplainNode => ({ name: n.name, kind, origin: n.origin, needs: n.needs, provides: n.provides });
|
||||
return {
|
||||
pattern: plan.pattern, method: plan.method, transport: plan.transport,
|
||||
chain: [
|
||||
...plan.providers.map((n) => nv(n, 'provider')),
|
||||
...plan.steps.map((n) => nv(n, 'step')),
|
||||
{ name: plan.handlerName, kind: 'handler', origin: plan.origin, needs: plan.needs, provides: [] },
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
const providedSeed = async (plan: RoutePlan): Promise<Record<string, unknown>> => {
|
||||
const provided: Record<string, unknown> = {};
|
||||
for (const p of plan.providers) {
|
||||
if (container.has(p.name)) Object.assign(provided, (await container.resolve(p.name)) as Record<string, unknown>);
|
||||
}
|
||||
return provided;
|
||||
};
|
||||
const planSteps = (plan: RoutePlan): PipelineStep[] => plan.steps.map((s) => {
|
||||
const fn = runners.get(s.name);
|
||||
if (!fn) throw new Error(`no runner registered for step '${s.name}'`);
|
||||
return { name: s.name, origin: s.origin, run: fn };
|
||||
});
|
||||
|
||||
const listen = async (port: number): Promise<http.Server> => {
|
||||
// mesh teacup: connect remote teapots, splice their scopes/routes into the graph, then finalize
|
||||
const remoteRoutes: RouteDef[] = [];
|
||||
const meshLinks: Link[] = [];
|
||||
let meshControl: MeshControl | undefined;
|
||||
if (opts.mesh && !booted) {
|
||||
try {
|
||||
for (const t of opts.mesh.teapots ?? []) {
|
||||
const link = await connectLink({ url: t.url, secret: t.secret, timeoutMs: opts.mesh.timeoutMs, bus });
|
||||
meshLinks.push(link);
|
||||
const { providers, steps, routes } = buildRemote(link, t.url);
|
||||
for (const p of providers) {
|
||||
providerNodes.push({ name: p.name, needs: [], provides: [p.name], origin: `mesh:${t.url}` });
|
||||
providerMeta.set(p.name, { optional: false });
|
||||
setRunner(p.name, p.run);
|
||||
}
|
||||
for (const s of steps) {
|
||||
stepNodes.push({ name: s.name, needs: [], provides: [s.name], origin: `mesh:${t.url}` });
|
||||
setRunner(s.name, s.run);
|
||||
}
|
||||
for (const r of routes) {
|
||||
remoteRoutes.push({
|
||||
method: r.method, pattern: r.pattern, transport: 'buffer',
|
||||
handler: async (req) => r.handler(req as RequestEnvelope),
|
||||
});
|
||||
}
|
||||
}
|
||||
finalizeGraph();
|
||||
} catch (err) {
|
||||
for (const l of meshLinks) { try { l.close(); } catch { /* */ } }
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// apply overrides: swap any provider/step runner by token in one line
|
||||
if (opts.overrides) {
|
||||
const produced = new Set([...providerNodes, ...stepNodes].flatMap((n) => n.provides));
|
||||
for (const [token, val] of Object.entries(opts.overrides)) {
|
||||
if (!produced.has(token)) throw new Error(`override for unknown token '${token}'`);
|
||||
const fn = typeof val === 'function' ? (val as (ctx: any) => any) : () => ({ [token]: val });
|
||||
runners.set(token, fn); // direct set (setRunner throws on dup); replaces the real runner
|
||||
}
|
||||
}
|
||||
|
||||
// run app-scoped providers in order (fail-fast for required)
|
||||
for (const node of orderedProviders) {
|
||||
bus.emit('boot:provider:start', { name: node.name, scope: node.origin });
|
||||
try {
|
||||
const value = await runners.get(node.name)!(await snapshot(container, node.needs));
|
||||
container.register(node.name, 'app', () => value);
|
||||
await container.resolve(node.name); // warm the cache
|
||||
bus.emit('boot:provider:ok', { name: node.name });
|
||||
} catch (error) {
|
||||
bus.emit('boot:provider:fail', { name: node.name, error });
|
||||
if (!providerMeta.get(node.name)?.optional) {
|
||||
throw new Error(`provider '${node.name}' failed: ${(error as Error).message}`);
|
||||
}
|
||||
// optional: warn, leave it unregistered; routes needing it fail at request time
|
||||
// ponytail: full partial-degradation is out of scope (spec §10); warn is enough here
|
||||
console.warn(`[green-tea] optional provider '${node.name}' failed: ${(error as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// mesh teapot: expose declared exports over the control channel (lazy resolvers read live state)
|
||||
const hasExports = exportedProviders.length || exportedSteps.length || exportedRoutes.length;
|
||||
if (hasExports && !opts.mesh?.secret) {
|
||||
throw new Error('mesh: exports declared (export: true) but no mesh.secret configured to gate the control channel');
|
||||
}
|
||||
if (opts.mesh?.secret && hasExports) {
|
||||
const manifest = buildManifest({ providers: exportedProviders, steps: exportedSteps, routes: exportedRoutes });
|
||||
const resolveScope = async (name: string, env: RequestEnvelope): Promise<unknown> => {
|
||||
let ctx: any = { req: env, params: env.params, query: env.query, body: env.body, headers: env.headers };
|
||||
for (const p of orderedProviders) if (container.has(p.name)) Object.assign(ctx, await container.resolve(p.name));
|
||||
for (const s of orderedSteps) { const fn = runners.get(s.name)!; ctx = { ...ctx, ...(await fn(ctx)) }; }
|
||||
return ctx[name];
|
||||
};
|
||||
const resolveRoute = async (name: string, env: RequestEnvelope) => {
|
||||
const plan = routePlans.find((p) => p.pattern === name && p.method === env.method);
|
||||
if (!plan) { const e: any = new Error(`no route ${name}`); e.status = 404; throw e; }
|
||||
const provided = await providedSeed(plan);
|
||||
const result = await runPipeline({
|
||||
steps: planSteps(plan), handler: plan.run, transformer: plan.transformer, bus,
|
||||
seed: { ...provided, req: env, params: env.params, query: env.query, body: env.body, headers: env.headers },
|
||||
});
|
||||
if ('stream' in result) { const e: any = new Error('cannot proxy a streaming route'); e.status = 500; throw e; }
|
||||
return result;
|
||||
};
|
||||
meshControl = createMeshControl({ secret: opts.mesh.secret, manifest, resolveScope, resolveRoute, bus });
|
||||
}
|
||||
|
||||
const httpRoutes: RouteDef[] = [
|
||||
...routePlans
|
||||
.filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate
|
||||
.map((plan): RouteDef => ({
|
||||
method: plan.method, pattern: plan.pattern, transport: plan.transport,
|
||||
handler: async (req) => {
|
||||
const provided = await providedSeed(plan);
|
||||
return runPipeline({
|
||||
steps: planSteps(plan), handler: plan.run, transformer: plan.transformer, bus,
|
||||
seed: { ...provided, req, params: req.params, query: req.query, body: req.body, headers: req.headers },
|
||||
});
|
||||
},
|
||||
})),
|
||||
...remoteRoutes,
|
||||
];
|
||||
|
||||
if (opts.devGraph) {
|
||||
httpRoutes.push({
|
||||
method: 'GET', pattern: '/__graph__', transport: 'buffer',
|
||||
handler: async (req) => {
|
||||
const mermaid = toMermaid(graph());
|
||||
const accept = String(req.headers['accept'] ?? '');
|
||||
return accept.includes('text/plain')
|
||||
? { status: 200, headers: { 'content-type': 'text/plain' }, body: mermaid }
|
||||
: { status: 200, headers: { 'content-type': 'text/html' }, body: graphHtml(mermaid) };
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const wsRoutes: WsRouteDef[] = routePlans
|
||||
.filter((plan) => plan.transport === 'ws' || plan.transport === 'negotiate')
|
||||
.map((plan) => ({
|
||||
pattern: plan.pattern,
|
||||
open: async ({ params, inbound, abort, req }) => {
|
||||
const provided = await providedSeed(plan);
|
||||
let ctx: any = { ...provided, req, params, query: parseQuery(req.url ?? ''), body: undefined,
|
||||
headers: req.headers, inbound, abort };
|
||||
for (const s of planSteps(plan)) { ctx = { ...ctx, ...(await s.run(ctx)) }; }
|
||||
const out = plan.run(ctx);
|
||||
if (!isAsyncIterable(out)) throw new Error(`@Ws handler '${plan.handlerName}' must return an AsyncIterable`);
|
||||
return out as AsyncIterable<unknown>;
|
||||
},
|
||||
}));
|
||||
|
||||
server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams });
|
||||
server.on('close', () => { for (const l of meshLinks) { try { l.close(); } catch { /* */ } } });
|
||||
await new Promise<void>((resolve) => server!.listen(port, resolve));
|
||||
return server;
|
||||
};
|
||||
|
||||
const close = (): Promise<void> => new Promise<void>((resolve) => {
|
||||
if (!server) return resolve();
|
||||
server.close(() => resolve()); // waits for in-flight buffered to drain
|
||||
for (const closeStream of streams) closeStream(); // force-close long-lived SSE/WS so close() resolves
|
||||
server.closeIdleConnections(); // Node >=18.2: drop idle keep-alive
|
||||
});
|
||||
|
||||
return { listen, close, inspect, graph, toMermaid: () => toMermaid(graph()), toDOT: () => toDOT(graph()), explain, bus };
|
||||
}
|
||||
|
||||
async function snapshot(c: Container, needs: string[]): Promise<Record<string, unknown>> {
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const key of needs) if (c.has(key)) Object.assign(out, (await c.resolve(key)) as Record<string, unknown>);
|
||||
return out;
|
||||
}
|
||||
+1000
@@ -0,0 +1,1000 @@
|
||||
import type http from 'http';
|
||||
import { Bus } from '../bus';
|
||||
import { Container } from '../container';
|
||||
import { topoSort, subgraphFor, GraphNode, nearest } from '../graph';
|
||||
import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz';
|
||||
import { runPipeline, runSteps, PipelineStep } from '../pipeline';
|
||||
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
|
||||
import type { HttpOptions } from '../http';
|
||||
import { buildFetch } from '../http/web';
|
||||
import { matchWsRoute, runWsConnection, trackUntil, type WsRequest, type WsSocket } from '../http/ws-core';
|
||||
import { isAsyncIterable } from '../channel';
|
||||
import { JsonTransformer, type ErrorRenderer } from '../transformers';
|
||||
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin';
|
||||
import {
|
||||
Ctor,
|
||||
getModuleMeta,
|
||||
getProviderMeta,
|
||||
getStepMeta,
|
||||
getRoutes,
|
||||
getTransformer,
|
||||
getHtmlMeta,
|
||||
joinPath,
|
||||
type RouteMeta,
|
||||
type TransformerFn,
|
||||
} from '../metadata';
|
||||
import { buildHtmlTransformer, buildStaticResolver, type ViewsContext } from '../views';
|
||||
import { getArgs, getHandlerNeeds, resolveArgs } from '../params';
|
||||
import { buildOpenApi, type OpenApiInfo } from '../openapi';
|
||||
import { connectLink, type Link } from '../mesh/link';
|
||||
import { Rooms } from '../rooms';
|
||||
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
|
||||
import { buildRemote } from '../mesh/teacup';
|
||||
import { buildManifest, createMeshControl, MESH_CONTROL_PATH } from '../mesh/teapot';
|
||||
import type { MeshControl } from '../http';
|
||||
import type { RequestEnvelope, RouteEntry } from '../mesh/protocol';
|
||||
import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types';
|
||||
import { inspectRoute, buildGraphView, explainRoute } from './introspect';
|
||||
import { compilePattern } from '../http/router';
|
||||
|
||||
export type { App, InspectLine, ExplainNode, Explain, MeshConfig } from './types';
|
||||
|
||||
type Runner = (ctx: any) => any;
|
||||
|
||||
/** Mutable graph state assembled from modules/plugins and later spliced with remote mesh scopes. */
|
||||
interface Registry {
|
||||
providerNodes: GraphNode[];
|
||||
stepNodes: GraphNode[];
|
||||
runners: Map<string, Runner>;
|
||||
providerMeta: Map<string, { optional: boolean }>;
|
||||
routePlans: RoutePlan[];
|
||||
exportedProviders: string[];
|
||||
exportedSteps: string[];
|
||||
exportedRoutes: RouteEntry[];
|
||||
setRunner(name: string, runner: Runner): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Memoizes an async step so repeat and concurrent callers share one run. Both boot stages need
|
||||
* this: `fetch`, `upgrade`, `listen` and `ready` can each be the first to trigger them, and
|
||||
* re-running would re-splice a mesh or re-run provider factories and their side effects.
|
||||
*/
|
||||
function once(run: () => Promise<void>): () => Promise<void> {
|
||||
let promise: Promise<void> | undefined;
|
||||
|
||||
return (): Promise<void> => {
|
||||
if (!promise) promise = run();
|
||||
|
||||
return promise;
|
||||
};
|
||||
}
|
||||
|
||||
/** Request-time helpers shared by the HTTP, WS and mesh route builders. */
|
||||
interface PipelineDeps {
|
||||
providedSeed(plan: RoutePlan): Promise<Record<string, unknown>>;
|
||||
planSteps(plan: RoutePlan): PipelineStep[];
|
||||
bus: Bus;
|
||||
onError?: ErrorRenderer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an {@link App} from the given modules and options.
|
||||
* Wires providers, steps, controllers and plugins into a dependency graph; for non-mesh apps
|
||||
* the graph is finalized eagerly, otherwise finalization is deferred to {@link App.listen}.
|
||||
*/
|
||||
export function createApp(opts: {
|
||||
modules: Ctor[];
|
||||
plugins?: Plugin[];
|
||||
mesh?: MeshConfig;
|
||||
limits?: RequestLimits;
|
||||
devGraph?: boolean;
|
||||
devOpenapi?: boolean;
|
||||
overrides?: Record<string, unknown>;
|
||||
tls?: TlsOptions;
|
||||
trustProxy?: boolean;
|
||||
security?: boolean | SecurityOptions;
|
||||
cors?: CorsOptions;
|
||||
bodyDuplicates?: 'array' | 'last';
|
||||
/** Render errors your own way (HTML, custom JSON, …); return a response or undefined to fall back to JSON. */
|
||||
onError?: ErrorRenderer;
|
||||
/** Base directory `@Html('file.html')` paths resolve against (default: `process.cwd()`). */
|
||||
views?: string;
|
||||
/** Bring-your-own template engine for `@Html(..., { template: true })`; defaults to the built-in `render`. */
|
||||
viewEngine?: (source: string, data: unknown) => string;
|
||||
/** Serve a static directory as a GET/HEAD fallback (after declared routes, before 404). `true` → `./public`. */
|
||||
static?: boolean | string;
|
||||
/** Opt in to alpha features whose API may still change. Currently gates `mesh`. */
|
||||
experimental?: boolean;
|
||||
/**
|
||||
* Warn at boot when a route's dependency chain resolves to more than this many steps (default 20;
|
||||
* `false` silences). A design nudge, not a perf limit — deep graphs run fine (cost is linear), but
|
||||
* 20+ steps on one route usually means a step is doing too much.
|
||||
*/
|
||||
warnGraphDepth?: number | false;
|
||||
}): App {
|
||||
// mesh is alpha: its API and wire protocol may change. Require an explicit opt-in.
|
||||
if (opts.mesh && !opts.experimental) {
|
||||
throw new Error(
|
||||
'mesh is an alpha feature — pass `experimental: true` to createApp to enable it (its API may change between releases)',
|
||||
);
|
||||
}
|
||||
|
||||
const bus = new Bus();
|
||||
const container = new Container();
|
||||
let server: http.Server | undefined;
|
||||
const streams = new Set<() => void>();
|
||||
const degradedProviders: string[] = []; // optional providers that failed to boot (running degraded)
|
||||
|
||||
// Collect declarations from modules, then splice in plugin- and built-in-provided nodes.
|
||||
const viewsCtx: ViewsContext = { views: opts.views, viewEngine: opts.viewEngine };
|
||||
const registry = collectModules(opts.modules, viewsCtx);
|
||||
const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry;
|
||||
mountPlugins(opts.plugins, bus, registry);
|
||||
provideBuiltins(registry);
|
||||
|
||||
// For each route, resolve which providers/steps feed it via topo order.
|
||||
// MVP: every route depends on every declared step + provider in the app graph.
|
||||
// For mesh apps, finalize is DEFERRED to the boot gate so remote scopes can join the graph
|
||||
// first — connecting to teapots is network I/O, so it cannot happen during construction.
|
||||
let orderedProviders: GraphNode[] = [];
|
||||
let orderedSteps: GraphNode[] = [];
|
||||
let booted = false;
|
||||
let remoteRoutes: RouteDef[] = [];
|
||||
const meshLinks: Link[] = [];
|
||||
|
||||
const finalize = (): void => {
|
||||
({ orderedProviders, orderedSteps } = finalizeGraph(registry, opts.warnGraphDepth));
|
||||
booted = true;
|
||||
};
|
||||
|
||||
if (!opts.mesh) finalize();
|
||||
|
||||
const providedSeed = (plan: RoutePlan) => seedProviders(container, plan);
|
||||
const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan);
|
||||
const pipelineDeps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError };
|
||||
let meshControl: MeshControl | undefined;
|
||||
|
||||
// mesh teacup: connect remote teapots and splice their scopes/routes in, then finalize.
|
||||
// mesh teapot: build the control channel — it captures the *finalized* ordered nodes, so it
|
||||
// can only be built here, after finalize(), and never at construction time.
|
||||
const prepareGraph = async (): Promise<void> => {
|
||||
if (opts.mesh && !booted) {
|
||||
const spliced = await spliceRemoteScopes(opts.mesh, bus, registry);
|
||||
remoteRoutes = spliced.remoteRoutes;
|
||||
meshLinks.push(...spliced.meshLinks);
|
||||
finalize();
|
||||
}
|
||||
|
||||
meshControl = buildMeshControl(opts.mesh, registry, {
|
||||
container,
|
||||
orderedProviders,
|
||||
orderedSteps,
|
||||
deps: pipelineDeps,
|
||||
});
|
||||
};
|
||||
|
||||
// Memoized separately from the provider boot on purpose: resolving the graph and being ready
|
||||
// to serve are different things. Introspection needs only the former, and must not run
|
||||
// provider factories (and open their connections) as a side effect of drawing a diagram.
|
||||
const ready = once(prepareGraph);
|
||||
|
||||
const inspect = (routePath: string): InspectLine[] => inspectRoute(routePlans, routePath, booted);
|
||||
const graph = (): GraphView => buildGraphView(providerNodes, stepNodes, routePlans, booted);
|
||||
const explain = (routePath: string): Explain => explainRoute(routePlans, routePath, booted);
|
||||
const openapi = (info?: OpenApiInfo) =>
|
||||
buildOpenApi(
|
||||
routePlans.map((plan) => ({
|
||||
method: plan.method,
|
||||
pattern: plan.pattern,
|
||||
transport: plan.transport,
|
||||
args: plan.args,
|
||||
})),
|
||||
info,
|
||||
);
|
||||
|
||||
// Dev-only introspection routes (opt-in). Shared by BOTH listen() and app.fetch so the
|
||||
// graph viewer + OpenAPI doc are served on every runtime (Node/Deno/Bun/edge), not Node alone.
|
||||
const devRoutes = (): RouteDef[] => {
|
||||
const routes: RouteDef[] = [];
|
||||
if (opts.devGraph) routes.push(devGraphRoute(graph));
|
||||
if (opts.devOpenapi) routes.push(openApiRoute(openapi));
|
||||
return routes;
|
||||
};
|
||||
|
||||
// Boots exactly once, however first triggered (app.fetch, app.upgrade or listen()); calling
|
||||
// several never double-boots (which would re-run provider factories and their side effects).
|
||||
const bootApp = makeAppBooter(
|
||||
registry,
|
||||
opts.overrides,
|
||||
() => orderedProviders,
|
||||
{ runners, container, providerMeta, bus },
|
||||
degradedProviders,
|
||||
ready,
|
||||
);
|
||||
|
||||
const staticResolver = opts.static ? buildStaticResolver(opts.static) : undefined;
|
||||
|
||||
const fetchOpts: HttpOptions = {
|
||||
limits: opts.limits,
|
||||
tls: opts.tls,
|
||||
trustProxy: opts.trustProxy,
|
||||
security: opts.security ?? true,
|
||||
cors: opts.cors,
|
||||
bodyDuplicates: opts.bodyDuplicates,
|
||||
onError: opts.onError,
|
||||
static: staticResolver,
|
||||
};
|
||||
const fetchFn = buildAppFetch(
|
||||
routePlans,
|
||||
{ providedSeed, planSteps, bus, onError: opts.onError },
|
||||
fetchOpts,
|
||||
bootApp,
|
||||
devRoutes,
|
||||
() => remoteRoutes,
|
||||
);
|
||||
const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl);
|
||||
|
||||
const listen = async (port: number): Promise<http.Server> => {
|
||||
const deps = pipelineDeps;
|
||||
|
||||
// the same gate app.fetch uses: splices remote mesh scopes, finalizes, boots providers,
|
||||
// and builds the mesh control channel — so Node and Deno/Bun serve an identical graph
|
||||
await bootApp();
|
||||
|
||||
const httpRoutes = [...buildHttpRoutes(routePlans, remoteRoutes, deps), ...devRoutes()];
|
||||
const wsRoutes = buildWsRoutes(routePlans, deps);
|
||||
|
||||
server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, {
|
||||
limits: opts.limits,
|
||||
streams,
|
||||
tls: opts.tls,
|
||||
trustProxy: opts.trustProxy,
|
||||
security: opts.security ?? true,
|
||||
cors: opts.cors,
|
||||
bodyDuplicates: opts.bodyDuplicates,
|
||||
onError: opts.onError,
|
||||
static: staticResolver,
|
||||
});
|
||||
server.on('close', () => closeLinks(meshLinks));
|
||||
await new Promise<void>((resolve) => server!.listen(port, resolve));
|
||||
return server;
|
||||
};
|
||||
|
||||
const close = (): Promise<void> =>
|
||||
new Promise<void>((resolve) => {
|
||||
// before the server check: a mesh app booted through app.fetch (Deno/Bun, where listen()
|
||||
// never runs) has links but no server, and would otherwise leak every teapot connection.
|
||||
// Closing a link rejects its in-flight RPCs via the socket's abort.
|
||||
closeLinks(meshLinks);
|
||||
|
||||
if (!server) return resolve();
|
||||
|
||||
server.close(() => resolve()); // waits for in-flight buffered to drain
|
||||
for (const closeStream of streams) closeStream(); // force-close long-lived SSE/WS so close() resolves
|
||||
server.closeIdleConnections(); // Node >=18.2: drop idle keep-alive
|
||||
});
|
||||
|
||||
return {
|
||||
listen,
|
||||
close,
|
||||
ready,
|
||||
fetch: fetchFn,
|
||||
upgrade: upgradeFn,
|
||||
inspect,
|
||||
graph,
|
||||
toMermaid: () => toMermaid(graph()),
|
||||
toDOT: () => toDOT(graph()),
|
||||
explain,
|
||||
openapi,
|
||||
degraded: () => [...degradedProviders],
|
||||
bus,
|
||||
};
|
||||
}
|
||||
|
||||
/** Creates an empty {@link Registry} whose `setRunner` enforces globally-unique provider/step names. */
|
||||
function emptyRegistry(): Registry {
|
||||
const runners = new Map<string, Runner>(); // node name -> runtime fn
|
||||
|
||||
const setRunner = (name: string, runner: Runner) => {
|
||||
if (runners.has(name))
|
||||
throw new Error(`duplicate provider/step name '${name}' — names must be unique across modules and plugins`);
|
||||
runners.set(name, runner);
|
||||
};
|
||||
|
||||
return {
|
||||
providerNodes: [],
|
||||
stepNodes: [],
|
||||
runners,
|
||||
providerMeta: new Map(),
|
||||
routePlans: [],
|
||||
exportedProviders: [],
|
||||
exportedSteps: [],
|
||||
exportedRoutes: [],
|
||||
setRunner,
|
||||
};
|
||||
}
|
||||
|
||||
/** Registers a module's `@Provider` classes as app-scope provider nodes. */
|
||||
function collectProviders(providers: Ctor[], origin: string, registry: Registry): void {
|
||||
for (const ProviderClass of providers) {
|
||||
const meta = getProviderMeta(ProviderClass)!;
|
||||
registry.providerNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin });
|
||||
registry.providerMeta.set(meta.provides, { optional: meta.optional });
|
||||
if (meta.export) registry.exportedProviders.push(meta.provides);
|
||||
const instance: any = new ProviderClass();
|
||||
registry.setRunner(meta.provides, (ctx) => instance.provide(ctx));
|
||||
}
|
||||
}
|
||||
|
||||
/** Registers a module's `@Step` classes as request-scope step nodes. */
|
||||
function collectSteps(steps: Ctor[], origin: string, registry: Registry): void {
|
||||
for (const StepClass of steps) {
|
||||
const meta = getStepMeta(StepClass)!;
|
||||
registry.stepNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin });
|
||||
if (meta.export) registry.exportedSteps.push(meta.provides);
|
||||
const instance: any = new StepClass();
|
||||
registry.setRunner(meta.provides, (ctx) => instance.run(ctx));
|
||||
}
|
||||
}
|
||||
|
||||
/** Registers each `@Route` handler on a module's controllers as a {@link RoutePlan}. */
|
||||
function collectControllers(
|
||||
controllers: Ctor[],
|
||||
mountpoint: string,
|
||||
origin: string,
|
||||
registry: Registry,
|
||||
viewsCtx: ViewsContext,
|
||||
): void {
|
||||
for (const ControllerClass of controllers) {
|
||||
for (const route of getRoutes(ControllerClass)) {
|
||||
const instance: any = new ControllerClass();
|
||||
const argSpecs = getArgs(ControllerClass, route.handlerName);
|
||||
const pattern = joinPath(mountpoint, route.path);
|
||||
const declaration = `${ControllerClass.name}.${route.handlerName}`;
|
||||
|
||||
if (route.export) {
|
||||
if (route.transport !== 'buffer') throw new Error(`cannot export streaming route ${pattern}`);
|
||||
registry.exportedRoutes.push({ method: route.method, pattern });
|
||||
}
|
||||
|
||||
const transformer = resolveTransformer(ControllerClass, route, pattern, viewsCtx);
|
||||
|
||||
const plan: RoutePlan = {
|
||||
pattern,
|
||||
method: route.method,
|
||||
transport: route.transport,
|
||||
origin,
|
||||
declaration,
|
||||
providers: [],
|
||||
steps: [],
|
||||
handlerName: route.handlerName,
|
||||
needs: getHandlerNeeds(argSpecs),
|
||||
run: async (context: any) => instance[route.handlerName](...(await resolveArgs(argSpecs, context))),
|
||||
transformer,
|
||||
duplicates: route.duplicates,
|
||||
maxBodyBytes: route.maxBodyBytes,
|
||||
maxParts: route.maxParts,
|
||||
args: argSpecs,
|
||||
};
|
||||
assertRouteAvailable(registry.routePlans, plan);
|
||||
registry.routePlans.push(plan);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Rejects local routes that have the same method and effective match shape. */
|
||||
function assertRouteAvailable(existing: RoutePlan[], candidate: RoutePlan): void {
|
||||
const compiled = compilePattern(candidate.pattern);
|
||||
const conflict = existing.find(
|
||||
(plan) => plan.method === candidate.method && compilePattern(plan.pattern).shape === compiled.shape,
|
||||
);
|
||||
if (!conflict) return;
|
||||
|
||||
throw new Error(
|
||||
`ambiguous route ${candidate.method} ${candidate.pattern} at ${candidate.declaration} conflicts with ` +
|
||||
`${conflict.method} ${conflict.pattern} at ${conflict.declaration}`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the response transformer for a route: `@Html` metadata builds an HTML transformer (after
|
||||
* validating placement — buffered GET/POST only, and not combined with `@Transformer`); otherwise the
|
||||
* user's `@Transformer` wins, falling back to {@link JsonTransformer}.
|
||||
*/
|
||||
function resolveTransformer(
|
||||
ControllerClass: Ctor,
|
||||
route: RouteMeta,
|
||||
pattern: string,
|
||||
viewsCtx: ViewsContext,
|
||||
): TransformerFn {
|
||||
const html = getHtmlMeta(ControllerClass, route.handlerName);
|
||||
const userTransformer = getTransformer(ControllerClass, route.handlerName);
|
||||
if (!html) return userTransformer ?? JsonTransformer;
|
||||
|
||||
if (route.transport !== 'buffer' || (route.method !== 'GET' && route.method !== 'POST')) {
|
||||
throw new Error(
|
||||
`@Html on ${route.method} ${pattern} is not allowed — @Html only supports buffered GET/POST routes (not SSE/WS/HEAD/PUT/PATCH/DELETE/OPTIONS)`,
|
||||
);
|
||||
}
|
||||
|
||||
if (userTransformer) throw new Error(`@Html and @Transformer on ${pattern} conflict — use one`);
|
||||
|
||||
return buildHtmlTransformer(html, viewsCtx);
|
||||
}
|
||||
|
||||
/** Reads every module's metadata into a fresh {@link Registry} of graph nodes, runners and exports. */
|
||||
function collectModules(modules: Ctor[], viewsCtx: ViewsContext): Registry {
|
||||
const registry = emptyRegistry();
|
||||
|
||||
for (const mod of modules) {
|
||||
const moduleMeta = getModuleMeta(mod);
|
||||
if (!moduleMeta) throw new Error(`${mod.name} is not a @Module`);
|
||||
const origin = `module:${mod.name}`;
|
||||
collectProviders(moduleMeta.providers ?? [], origin, registry);
|
||||
collectSteps(moduleMeta.steps ?? [], origin, registry);
|
||||
collectControllers(moduleMeta.controllers ?? [], moduleMeta.mountpoint, origin, registry, viewsCtx);
|
||||
}
|
||||
|
||||
return registry;
|
||||
}
|
||||
|
||||
/** Mounts plugins and splices any steps/providers they add into the registry as their own scope. */
|
||||
function mountPlugins(plugins: Plugin[] | undefined, bus: Bus, registry: Registry): void {
|
||||
const extraSteps: ScopeNode[] = [];
|
||||
const scope: ScopeApi = { add: (node) => extraSteps.push(node) };
|
||||
|
||||
for (const plugin of plugins ?? []) mountPlugin(plugin, bus, scope);
|
||||
|
||||
for (const scopeNode of extraSteps) {
|
||||
const node = { name: scopeNode.name, needs: scopeNode.needs, provides: scopeNode.provides, origin: 'plugin' };
|
||||
if (scopeNode.kind === 'provider') registry.providerNodes.push(node);
|
||||
else registry.stepNodes.push(node);
|
||||
registry.setRunner(scopeNode.name, scopeNode.run);
|
||||
}
|
||||
}
|
||||
|
||||
/** Auto-provides a shared {@link Rooms} instance unless the user already declared a `rooms` provider. */
|
||||
function provideBuiltins(registry: Registry): void {
|
||||
if (registry.runners.has('rooms')) return;
|
||||
const roomsInstance = new Rooms();
|
||||
registry.providerNodes.push({ name: 'rooms', needs: [], provides: ['rooms'], origin: 'builtin' });
|
||||
registry.providerMeta.set('rooms', { optional: false });
|
||||
registry.setRunner('rooms', () => ({ rooms: roomsInstance })); // merge object -> ctx.rooms
|
||||
}
|
||||
|
||||
// Boot-time nudge: a route whose need-closure pulls this many steps is almost always a modeling
|
||||
// smell (a step doing too much, or work that belongs in a provider), not a real dependency depth.
|
||||
// Cost is linear so it isn't a perf problem — it's a design one. Generous on purpose.
|
||||
const DEEP_GRAPH_WARN = 20;
|
||||
|
||||
/**
|
||||
* Topo-sorts the graph, slices each route's provider/step closure into its plan, and validates every need.
|
||||
* @returns The app-scope providers and request-scope steps in execution order.
|
||||
*/
|
||||
function finalizeGraph(
|
||||
registry: Registry,
|
||||
warnDepth: number | false = DEEP_GRAPH_WARN,
|
||||
): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } {
|
||||
const { providerNodes, stepNodes, routePlans } = registry;
|
||||
const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params']);
|
||||
const orderedProviders = ordered.filter((node) => providerNodes.includes(node));
|
||||
const orderedSteps = ordered.filter((node) => stepNodes.includes(node));
|
||||
const alwaysSteps = stepNodes.filter((node) => node.provides.length === 0); // side-effect/observer steps (plugins)
|
||||
const alwaysNeeds = alwaysSteps.flatMap((node) => node.needs); // pull observers' deps into every route
|
||||
|
||||
for (const plan of routePlans) {
|
||||
const closure = subgraphFor([...plan.needs, ...alwaysNeeds], ordered);
|
||||
plan.providers = closure.filter((node) => providerNodes.includes(node));
|
||||
const sliced = new Set<GraphNode>([...closure.filter((node) => stepNodes.includes(node)), ...alwaysSteps]);
|
||||
plan.steps = ordered.filter((node) => stepNodes.includes(node) && sliced.has(node)); // topo order, deduped
|
||||
|
||||
// The route's own dependency depth, excluding always-on observer steps (plugins).
|
||||
const depth = closure.filter((node) => stepNodes.includes(node)).length;
|
||||
|
||||
if (warnDepth !== false && depth > warnDepth) {
|
||||
console.warn(
|
||||
`[green-tea] ${plan.method} ${plan.pattern} resolves to ${depth} steps — an unusually deep dependency chain. ` +
|
||||
`It runs fine (per-request cost is linear), but ${warnDepth}+ steps on one route usually means a step ` +
|
||||
`is doing too much or the graph wants splitting. If it's intentional, ignore this.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
assertNeedsSatisfiable(routePlans, providerNodes, stepNodes);
|
||||
return { orderedProviders, orderedSteps };
|
||||
}
|
||||
|
||||
/** Throws if any route needs a key that nothing (local or mesh) provides, suggesting the nearest match. */
|
||||
function assertNeedsSatisfiable(routePlans: RoutePlan[], providerNodes: GraphNode[], stepNodes: GraphNode[]): void {
|
||||
const producedKeys = new Set<string>([
|
||||
...providerNodes.flatMap((node) => node.provides),
|
||||
...stepNodes.flatMap((node) => node.provides),
|
||||
]);
|
||||
const allowed = new Set<string>([...producedKeys, 'req', 'params', 'query', 'body', 'headers', 'inbound', 'abort']);
|
||||
|
||||
for (const plan of routePlans) {
|
||||
for (const need of plan.needs) {
|
||||
if (allowed.has(need)) continue;
|
||||
const hint = nearest(need, allowed);
|
||||
throw new Error(
|
||||
`handler '${plan.handlerName}' needs '${need}' but nothing (local or mesh) provides it${hint ? ` — did you mean '${hint}'?` : ''}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Connects the configured teapots, splices their remote providers/steps into the registry, and returns their routes. */
|
||||
async function spliceRemoteScopes(
|
||||
mesh: MeshConfig,
|
||||
bus: Bus,
|
||||
registry: Registry,
|
||||
): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[] }> {
|
||||
const remoteRoutes: RouteDef[] = [];
|
||||
const meshLinks: Link[] = [];
|
||||
const routeOwners = new Map<string, { url: string; pattern: string }>(); // "METHOD effective-shape" -> owner
|
||||
|
||||
try {
|
||||
for (const teapot of mesh.teapots ?? []) {
|
||||
const link = await connectLink({
|
||||
url: teapot.url,
|
||||
secret: teapot.secret,
|
||||
timeoutMs: mesh.timeoutMs,
|
||||
heartbeatMs: mesh.heartbeatMs,
|
||||
bus,
|
||||
});
|
||||
meshLinks.push(link);
|
||||
const { providers, steps, routes } = buildRemote(link);
|
||||
const origin = `mesh:${teapot.url}`;
|
||||
|
||||
for (const provider of providers) {
|
||||
registry.providerNodes.push({ name: provider.name, needs: [], provides: [provider.name], origin });
|
||||
registry.providerMeta.set(provider.name, { optional: false });
|
||||
registry.setRunner(provider.name, provider.run);
|
||||
}
|
||||
|
||||
for (const step of steps) {
|
||||
registry.stepNodes.push({ name: step.name, needs: [], provides: [step.name], origin });
|
||||
registry.setRunner(step.name, step.run);
|
||||
}
|
||||
|
||||
for (const route of routes) {
|
||||
const display = `${route.method} ${route.pattern}`;
|
||||
const key = `${route.method} ${compilePattern(route.pattern).shape}`;
|
||||
const owner = routeOwners.get(key);
|
||||
|
||||
// Fail the boot rather than pick one. Route matching keeps the first of two identical
|
||||
// patterns, so the loser would be silently dead — and callers could come to depend on
|
||||
// "first teapot wins", which would make adding balancing later a breaking change.
|
||||
// Scope tokens already fail this way in setRunner; routes now match.
|
||||
if (owner) {
|
||||
throw new Error(
|
||||
`mesh: ambiguous remote route '${display}' from ${teapot.url} conflicts with ` +
|
||||
`'${route.method} ${owner.pattern}' from ${owner.url} — ` +
|
||||
'load balancing across teapots is not implemented yet, so green-tea will not choose one for you. ' +
|
||||
'Export it from a single teapot.',
|
||||
);
|
||||
}
|
||||
|
||||
routeOwners.set(key, { url: teapot.url, pattern: route.pattern });
|
||||
|
||||
// Local routes are merged ahead of remote ones (see buildHttpRoutes), so a local twin
|
||||
// wins. That precedence is deliberate — your own code beats an imported one, and it is
|
||||
// how you override a teapot — but silently shadowing an export looks exactly like a
|
||||
// broken teapot from the outside. Warn and let the developer decide.
|
||||
if (
|
||||
registry.routePlans.some(
|
||||
(plan) =>
|
||||
plan.method === route.method &&
|
||||
compilePattern(plan.pattern).shape === compilePattern(route.pattern).shape,
|
||||
)
|
||||
) {
|
||||
console.warn(
|
||||
`[green-tea] mesh: route '${display}' is exported by teapot ${teapot.url} but also declared locally — ` +
|
||||
'the local route takes precedence and the remote one will not be reached. ' +
|
||||
'Remove one if that is not what you meant.',
|
||||
);
|
||||
}
|
||||
|
||||
remoteRoutes.push({
|
||||
method: route.method,
|
||||
pattern: route.pattern,
|
||||
transport: 'buffer',
|
||||
handler: async (req) => route.handler(req as RequestEnvelope),
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
closeLinks(meshLinks);
|
||||
throw err;
|
||||
}
|
||||
|
||||
return { remoteRoutes, meshLinks };
|
||||
}
|
||||
|
||||
/** Swaps provider/step runners by token — a value replaces the runner, a function becomes it. */
|
||||
function applyOverrides(overrides: Record<string, unknown> | undefined, registry: Registry): void {
|
||||
if (!overrides) return;
|
||||
const produced = new Set([...registry.providerNodes, ...registry.stepNodes].flatMap((node) => node.provides));
|
||||
|
||||
for (const [token, val] of Object.entries(overrides)) {
|
||||
if (!produced.has(token)) throw new Error(`override for unknown token '${token}'`);
|
||||
const runner: Runner = typeof val === 'function' ? (val as Runner) : () => ({ [token]: val });
|
||||
registry.runners.set(token, runner); // direct set (setRunner throws on dup); replaces the real runner
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs app-scoped providers in topo order, caching each result; required failures abort, optional ones warn.
|
||||
* @returns The names of optional providers that failed and are running degraded (unregistered).
|
||||
*/
|
||||
async function bootProviders(
|
||||
orderedProviders: GraphNode[],
|
||||
deps: {
|
||||
runners: Map<string, Runner>;
|
||||
container: Container;
|
||||
providerMeta: Map<string, { optional: boolean }>;
|
||||
bus: Bus;
|
||||
},
|
||||
): Promise<string[]> {
|
||||
const { runners, container, providerMeta, bus } = deps;
|
||||
const degraded: string[] = [];
|
||||
|
||||
for (const node of orderedProviders) {
|
||||
bus.emit('boot:provider:start', { name: node.name, scope: node.origin });
|
||||
|
||||
try {
|
||||
const value = await runners.get(node.name)!(await snapshot(container, node.needs));
|
||||
container.register(node.name, 'app', () => value);
|
||||
await container.resolve(node.name); // warm the cache
|
||||
bus.emit('boot:provider:ok', { name: node.name });
|
||||
} catch (error) {
|
||||
bus.emit('boot:provider:fail', { name: node.name, error });
|
||||
|
||||
if (!providerMeta.get(node.name)?.optional) {
|
||||
throw new Error(`provider '${node.name}' failed: ${(error as Error).message}`);
|
||||
}
|
||||
|
||||
// optional: warn, leave it unregistered; routes needing it fail at request time
|
||||
// ponytail: full partial-degradation is out of scope (spec §10); warn is enough here
|
||||
degraded.push(node.name);
|
||||
console.warn(`[green-tea] optional provider '${node.name}' failed: ${(error as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
return degraded;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a memoized boot function: prepares the graph, applies overrides and boots app-scope
|
||||
* providers exactly once, however first triggered — `app.fetch`, `app.upgrade` and `listen()` may
|
||||
* all call it, and the memoization guarantees only the first runs the sequence. This is the single
|
||||
* place an app becomes ready, which is what lets a mesh app boot on any runtime rather than only
|
||||
* where `listen()` (a Node http.Server) can be built.
|
||||
*/
|
||||
function makeAppBooter(
|
||||
registry: Registry,
|
||||
overrides: Record<string, unknown> | undefined,
|
||||
getOrderedProviders: () => GraphNode[],
|
||||
deps: {
|
||||
runners: Map<string, Runner>;
|
||||
container: Container;
|
||||
providerMeta: Map<string, { optional: boolean }>;
|
||||
bus: Bus;
|
||||
},
|
||||
degradedProviders: string[],
|
||||
/** Resolves the graph (splices remote mesh scopes, finalizes). Must precede providers: remote nodes join the topo sort. */
|
||||
prepareGraph: () => Promise<void>,
|
||||
): () => Promise<void> {
|
||||
const runBoot = async (): Promise<void> => {
|
||||
await prepareGraph();
|
||||
applyOverrides(overrides, registry);
|
||||
degradedProviders.length = 0;
|
||||
degradedProviders.push(...(await bootProviders(getOrderedProviders(), deps)));
|
||||
|
||||
if (degradedProviders.length) {
|
||||
console.warn(
|
||||
`[green-tea] started with ${degradedProviders.length} degraded optional provider(s): ${degradedProviders.join(', ')} — routes that need them will fail at request time.`,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return once(runBoot);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the mesh control gateway that exposes this node's declared exports over the control channel.
|
||||
* Returns undefined when there is nothing to export; throws if exports are declared without a gating secret.
|
||||
*/
|
||||
function buildMeshControl(
|
||||
mesh: MeshConfig | undefined,
|
||||
registry: Registry,
|
||||
deps: { container: Container; orderedProviders: GraphNode[]; orderedSteps: GraphNode[]; deps: PipelineDeps },
|
||||
): MeshControl | undefined {
|
||||
const { exportedProviders, exportedSteps, exportedRoutes, routePlans, runners } = registry;
|
||||
const hasExports = exportedProviders.length || exportedSteps.length || exportedRoutes.length;
|
||||
|
||||
if (hasExports && !mesh?.secret) {
|
||||
throw new Error('mesh: exports declared (export: true) but no mesh.secret configured to gate the control channel');
|
||||
}
|
||||
|
||||
if (!mesh?.secret || !hasExports) return undefined;
|
||||
const { container, orderedProviders, orderedSteps } = deps;
|
||||
const { bus, providedSeed, planSteps, onError } = deps.deps;
|
||||
const manifest = buildManifest({ providers: exportedProviders, steps: exportedSteps, routes: exportedRoutes });
|
||||
|
||||
const resolveScope = async (name: string, env: RequestEnvelope): Promise<unknown> => {
|
||||
// context is intentionally `any`: providers and steps merge arbitrary keys into it
|
||||
const seed: any = { req: env, params: env.params, query: env.query, body: env.body, headers: env.headers };
|
||||
|
||||
for (const provider of orderedProviders)
|
||||
if (container.has(provider.name)) Object.assign(seed, await container.resolve(provider.name));
|
||||
|
||||
const steps = orderedSteps.map((step) => ({ name: step.name, origin: step.origin, run: runners.get(step.name)! }));
|
||||
const context = await runSteps(steps, seed, bus);
|
||||
|
||||
return context[name];
|
||||
};
|
||||
|
||||
const resolveRoute = async (name: string, env: RequestEnvelope) => {
|
||||
const plan = routePlans.find((candidate) => candidate.pattern === name && candidate.method === env.method);
|
||||
|
||||
if (!plan) {
|
||||
const error: any = new Error(`no route ${name}`);
|
||||
error.status = 404;
|
||||
throw error;
|
||||
}
|
||||
|
||||
const provided = await providedSeed(plan);
|
||||
const result = await runPipeline({
|
||||
steps: planSteps(plan),
|
||||
handler: plan.run,
|
||||
transformer: plan.transformer,
|
||||
bus,
|
||||
onError,
|
||||
transport: plan.transport,
|
||||
seed: { ...provided, req: env, params: env.params, query: env.query, body: env.body, headers: env.headers },
|
||||
});
|
||||
|
||||
if ('stream' in result) {
|
||||
const error: any = new Error('cannot proxy a streaming route');
|
||||
error.status = 500;
|
||||
throw error;
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
return createMeshControl({ secret: mesh.secret, manifest, resolveScope, resolveRoute, bus });
|
||||
}
|
||||
|
||||
/** Compiles every non-ws route plan into an HTTP route that seeds and runs the pipeline, plus any remote routes. */
|
||||
function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps: PipelineDeps): RouteDef[] {
|
||||
const { providedSeed, planSteps, bus, onError } = deps;
|
||||
|
||||
const local = routePlans
|
||||
.filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate
|
||||
.map((plan): RouteDef => ({
|
||||
method: plan.method,
|
||||
pattern: plan.pattern,
|
||||
transport: plan.transport,
|
||||
bodyDuplicates: plan.duplicates,
|
||||
maxBodyBytes: plan.maxBodyBytes,
|
||||
maxParts: plan.maxParts,
|
||||
handler: async (req) => {
|
||||
const provided = await providedSeed(plan);
|
||||
return runPipeline({
|
||||
steps: planSteps(plan),
|
||||
handler: plan.run,
|
||||
transformer: plan.transformer,
|
||||
bus,
|
||||
onError,
|
||||
transport: plan.transport,
|
||||
seed: {
|
||||
...provided,
|
||||
req,
|
||||
params: req.params,
|
||||
query: req.query,
|
||||
body: req.body,
|
||||
headers: req.headers,
|
||||
protocol: req.protocol,
|
||||
ip: req.ip,
|
||||
},
|
||||
});
|
||||
},
|
||||
}));
|
||||
|
||||
return [...local, ...remoteRoutes];
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds `app.fetch`: a Web-Standards handler over the same route table `listen()` uses, so
|
||||
* `Deno.serve(app.fetch)` / `Bun.serve({ fetch: app.fetch })` work without ever calling `listen()`.
|
||||
* The boot is awaited *before* the route table is built: for a mesh app the table is not knowable
|
||||
* until remote scopes have spliced in, and the boot is what does that. Both are memoized, so this
|
||||
* costs one flag check per request after the first.
|
||||
*/
|
||||
function buildAppFetch(
|
||||
routePlans: RoutePlan[],
|
||||
deps: PipelineDeps,
|
||||
fetchOpts: HttpOptions,
|
||||
ensureBooted: () => Promise<void>,
|
||||
devRoutes: () => RouteDef[],
|
||||
getRemoteRoutes: () => RouteDef[],
|
||||
): (request: Request) => Promise<Response> {
|
||||
let handler: ((request: Request) => Promise<Response>) | undefined;
|
||||
|
||||
return async (request: Request): Promise<Response> => {
|
||||
await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted
|
||||
|
||||
if (!handler) {
|
||||
handler = buildFetch([...buildHttpRoutes(routePlans, getRemoteRoutes(), deps), ...devRoutes()], fetchOpts);
|
||||
}
|
||||
|
||||
return handler(request);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds `app.upgrade`: the neutral WebSocket entry over the same route table `listen()` uses, so
|
||||
* Deno/Bun/edge adapters can drive ws connections without ever calling `listen()`. Node keeps its own
|
||||
* `server.on('upgrade')` path (see `attachWs`) and never calls this.
|
||||
* Mirrors {@link buildAppFetch}: the boot is awaited before the ws route table is built.
|
||||
*/
|
||||
function buildAppUpgrade(
|
||||
routePlans: RoutePlan[],
|
||||
deps: PipelineDeps,
|
||||
streams: Set<() => void>,
|
||||
ensureBooted: () => Promise<void>,
|
||||
getMeshControl: () => MeshControl | undefined,
|
||||
): (request: WsRequest, socket: WsSocket) => Promise<void> {
|
||||
let wsRoutes: WsRouteDef[] | undefined;
|
||||
|
||||
return async (request: WsRequest, socket: WsSocket): Promise<void> => {
|
||||
// Subscribe to inbound BEFORE awaiting the boot. `channel` is fan-out: a frame pushed with no
|
||||
// subscriber is dropped, so anything the peer sends while providers are still booting would be
|
||||
// lost. For the mesh control channel that is the `hello` itself — the handshake would hang
|
||||
// until timeout against a teapot whose providers happened to boot slowly.
|
||||
const frames = socket.inbound[Symbol.asyncIterator]();
|
||||
const ready: WsSocket = Object.create(socket, {
|
||||
inbound: { value: { [Symbol.asyncIterator]: () => frames } },
|
||||
}) as WsSocket;
|
||||
|
||||
await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted
|
||||
|
||||
const path = request.url.split('?')[0];
|
||||
const meshControl = getMeshControl();
|
||||
|
||||
// The reserved mesh path, checked before route matching: this is what lets a teapot export
|
||||
// its scopes from Deno/Bun, where the Node `server.on('upgrade')` path does not exist.
|
||||
if (path === MESH_CONTROL_PATH) {
|
||||
// an explicit refusal, not "no matching ws route": the path is reserved either way, and a
|
||||
// peer that reached a teapot with nothing exported deserves to be told which it was
|
||||
if (!meshControl) {
|
||||
ready.close(1008, 'mesh control channel not enabled: this app exports nothing, or has no mesh.secret');
|
||||
return;
|
||||
}
|
||||
|
||||
await trackUntil(ready, meshControl.handle(ready), streams);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!wsRoutes) wsRoutes = buildWsRoutes(routePlans, deps);
|
||||
|
||||
const route = matchWsRoute(wsRoutes, path);
|
||||
|
||||
if (!route) {
|
||||
ready.close(1008, 'no matching ws route');
|
||||
return;
|
||||
}
|
||||
|
||||
await runWsConnection(ready, request, route, deps.bus, streams);
|
||||
};
|
||||
}
|
||||
|
||||
/** The dev-only `/__graph__` route: serves the dependency graph as Mermaid text or an HTML viewer. */
|
||||
function devGraphRoute(graph: () => GraphView): RouteDef {
|
||||
return {
|
||||
method: 'GET',
|
||||
pattern: '/__graph__',
|
||||
transport: 'buffer',
|
||||
handler: async (req) => {
|
||||
const view = graph();
|
||||
const accept = String(req.headers['accept'] ?? '');
|
||||
return accept.includes('text/plain')
|
||||
? { status: 200, headers: { 'content-type': 'text/plain' }, body: toMermaid(view) }
|
||||
: { status: 200, headers: { 'content-type': 'text/html' }, body: graphHtml(view) };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The dev-only `/__openapi__` route: serves the structural OpenAPI 3.1 document as JSON. */
|
||||
function openApiRoute(openapi: () => unknown): RouteDef {
|
||||
return {
|
||||
method: 'GET',
|
||||
pattern: '/__openapi__',
|
||||
transport: 'buffer',
|
||||
handler: async () => ({
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(openapi()),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Compiles every ws/negotiate route plan into a WebSocket route that seeds context and runs its steps + handler. */
|
||||
function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[] {
|
||||
const { providedSeed, planSteps, bus } = deps;
|
||||
|
||||
return routePlans
|
||||
.filter((plan) => plan.transport === 'ws' || plan.transport === 'negotiate')
|
||||
.map((plan) => ({
|
||||
pattern: plan.pattern,
|
||||
open: async ({ params, inbound, abort, req }) => {
|
||||
const provided = await providedSeed(plan);
|
||||
// ws upgrades carry the neutral WsRequest (protocol/ip pre-derived by the runtime adapter);
|
||||
// trustProxy derivation for ws is out of scope here
|
||||
const context = await runSteps(
|
||||
planSteps(plan),
|
||||
{
|
||||
...provided,
|
||||
req,
|
||||
params,
|
||||
query: parseQuery(req.url ?? ''),
|
||||
body: undefined,
|
||||
headers: req.headers,
|
||||
inbound,
|
||||
abort,
|
||||
protocol: req.protocol,
|
||||
ip: req.ip,
|
||||
},
|
||||
bus,
|
||||
);
|
||||
|
||||
const result = await plan.run(context);
|
||||
if (!isAsyncIterable(result)) throw new Error(`@Ws handler '${plan.handlerName}' must return an AsyncIterable`);
|
||||
return result as AsyncIterable<unknown>;
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
/** Best-effort close of every mesh link, ignoring individual failures. */
|
||||
function closeLinks(links: Link[]): void {
|
||||
for (const link of links) {
|
||||
try {
|
||||
link.close();
|
||||
} catch {
|
||||
/* */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Merges every app-scope provider bound to a route into a request seed (skips unresolved providers). */
|
||||
async function seedProviders(container: Container, plan: RoutePlan): Promise<Record<string, unknown>> {
|
||||
const provided: Record<string, unknown> = {};
|
||||
|
||||
for (const provider of plan.providers) {
|
||||
if (container.has(provider.name))
|
||||
Object.assign(provided, (await container.resolve(provider.name)) as Record<string, unknown>);
|
||||
}
|
||||
|
||||
return provided;
|
||||
}
|
||||
|
||||
/** Resolves a route's step nodes into runnable pipeline steps, failing if any runner is missing. */
|
||||
function compilePlanSteps(runners: Map<string, Runner>, plan: RoutePlan): PipelineStep[] {
|
||||
return plan.steps.map((step) => {
|
||||
const runner = runners.get(step.name);
|
||||
if (!runner) throw new Error(`no runner registered for step '${step.name}'`);
|
||||
return { name: step.name, origin: step.origin, run: runner };
|
||||
});
|
||||
}
|
||||
|
||||
/** Resolves the given need-keys from the container into a merged snapshot (skips unregistered keys). */
|
||||
async function snapshot(container: Container, needs: string[]): Promise<Record<string, unknown>> {
|
||||
const resolved: Record<string, unknown> = {};
|
||||
|
||||
for (const key of needs)
|
||||
if (container.has(key)) Object.assign(resolved, (await container.resolve(key)) as Record<string, unknown>);
|
||||
|
||||
return resolved;
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import type { GraphNode } from '../graph';
|
||||
import type { GraphView } from '../graph-viz';
|
||||
import type { InspectLine, Explain, ExplainNode, RoutePlan } from './types';
|
||||
|
||||
/** Lists the provider/step/handler chain for a route, in execution order. */
|
||||
export function inspectRoute(routePlans: RoutePlan[], routePath: string, booted: boolean): InspectLine[] {
|
||||
if (!booted)
|
||||
throw new Error(
|
||||
'inspect() unavailable until a mesh app has booted: a mesh graph is not knowable until its teapots are asked. Call `await app.ready()` first — it is a no-op on a non-mesh app',
|
||||
);
|
||||
const plan = routePlans.find((candidate) => candidate.pattern === routePath);
|
||||
if (!plan) throw new Error(`no route: ${routePath}`);
|
||||
return [
|
||||
...plan.providers.map((provider) => ({
|
||||
name: provider.name,
|
||||
kind: 'provider' as const,
|
||||
origin: provider.origin,
|
||||
})),
|
||||
...plan.steps.map((step) => ({ name: step.name, kind: 'step' as const, origin: step.origin })),
|
||||
{ name: plan.handlerName, kind: 'handler' as const, origin: plan.origin },
|
||||
];
|
||||
}
|
||||
|
||||
/** Builds the full dependency-graph view: every provider/step node plus each route's chain. */
|
||||
export function buildGraphView(
|
||||
providerNodes: GraphNode[],
|
||||
stepNodes: GraphNode[],
|
||||
routePlans: RoutePlan[],
|
||||
booted: boolean,
|
||||
): GraphView {
|
||||
if (!booted)
|
||||
throw new Error(
|
||||
'graph() unavailable until a mesh app has booted: a mesh graph is not knowable until its teapots are asked. Call `await app.ready()` first — it is a no-op on a non-mesh app',
|
||||
);
|
||||
return {
|
||||
nodes: [
|
||||
...providerNodes.map((node) => ({
|
||||
name: node.name,
|
||||
kind: 'provider' as const,
|
||||
origin: node.origin,
|
||||
needs: node.needs,
|
||||
provides: node.provides,
|
||||
})),
|
||||
...stepNodes.map((node) => ({
|
||||
name: node.name,
|
||||
kind: 'step' as const,
|
||||
origin: node.origin,
|
||||
needs: node.needs,
|
||||
provides: node.provides,
|
||||
})),
|
||||
],
|
||||
routes: routePlans.map((plan) => ({
|
||||
pattern: plan.pattern,
|
||||
method: plan.method,
|
||||
transport: plan.transport,
|
||||
chain: [...plan.providers.map((node) => node.name), ...plan.steps.map((node) => node.name), plan.handlerName],
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/** Explains a single route: its match criteria and the ordered chain with each node's needs/provides. */
|
||||
export function explainRoute(routePlans: RoutePlan[], routePath: string, booted: boolean): Explain {
|
||||
if (!booted)
|
||||
throw new Error(
|
||||
'explain() unavailable until a mesh app has booted: a mesh graph is not knowable until its teapots are asked. Call `await app.ready()` first — it is a no-op on a non-mesh app',
|
||||
);
|
||||
const plan = routePlans.find((candidate) => candidate.pattern === routePath);
|
||||
if (!plan) throw new Error(`no route: ${routePath}`);
|
||||
const toExplainNode = (node: GraphNode, kind: 'provider' | 'step'): ExplainNode => ({
|
||||
name: node.name,
|
||||
kind,
|
||||
origin: node.origin,
|
||||
needs: node.needs,
|
||||
provides: node.provides,
|
||||
});
|
||||
return {
|
||||
pattern: plan.pattern,
|
||||
method: plan.method,
|
||||
transport: plan.transport,
|
||||
chain: [
|
||||
...plan.providers.map((node) => toExplainNode(node, 'provider')),
|
||||
...plan.steps.map((node) => toExplainNode(node, 'step')),
|
||||
{ name: plan.handlerName, kind: 'handler', origin: plan.origin, needs: plan.needs, provides: [] },
|
||||
],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import type http from 'http';
|
||||
import type { Bus } from '../bus';
|
||||
import type { GraphNode } from '../graph';
|
||||
import type { GraphView } from '../graph-viz';
|
||||
import type { HttpMethod, Transport } from '../metadata';
|
||||
import type { ArgSpec } from '../params';
|
||||
import type { OpenApiDoc, OpenApiInfo } from '../openapi';
|
||||
import type { WsRequest, WsSocket } from '../http/ws-core';
|
||||
import { JsonTransformer } from '../transformers';
|
||||
|
||||
/** One entry in an {@link App.inspect} listing: a provider, step or handler and where it came from. */
|
||||
export interface InspectLine {
|
||||
name: string;
|
||||
kind: 'provider' | 'step' | 'handler';
|
||||
origin: string;
|
||||
}
|
||||
|
||||
/** A node in an {@link Explain} chain, annotated with the keys it needs and provides. */
|
||||
export interface ExplainNode {
|
||||
name: string;
|
||||
kind: 'provider' | 'step' | 'handler';
|
||||
origin: string;
|
||||
needs: string[];
|
||||
provides: string[];
|
||||
}
|
||||
|
||||
/** A full route explanation: its match criteria and the ordered provider/step/handler chain. */
|
||||
export interface Explain {
|
||||
pattern: string;
|
||||
method: HttpMethod;
|
||||
transport: Transport;
|
||||
chain: ExplainNode[];
|
||||
}
|
||||
|
||||
/** A running application instance with lifecycle, introspection and graph-export methods. */
|
||||
export interface App {
|
||||
listen(port: number): Promise<http.Server>;
|
||||
close(): Promise<void>;
|
||||
/**
|
||||
* Resolves the dependency graph, then returns. For a mesh app that means connecting to its
|
||||
* teapots and splicing their scopes in — a mesh graph is not knowable without asking. For every
|
||||
* other app it is a no-op, so code holding an `App` can `await app.ready()` before
|
||||
* `inspect()`/`graph()`/`explain()` without caring which kind it was handed.
|
||||
*
|
||||
* Deliberately *not* a full boot: it does not run provider factories. 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 the providers as well, and
|
||||
* shares this same memoized step — calling both never resolves the graph twice.
|
||||
*/
|
||||
ready(): Promise<void>;
|
||||
/** Web-Standards handler: run a Fetch API Request through the graph and return a Response (Node/Deno/Bun/edge). WS not included. */
|
||||
fetch(request: Request): Promise<Response>;
|
||||
/** Run a WebSocket upgrade through the graph using an adapter-provided socket (Deno/Bun/edge). Node uses its own listener path. */
|
||||
upgrade(request: WsRequest, socket: WsSocket): Promise<void>;
|
||||
inspect(routePath: string): InspectLine[];
|
||||
graph(): GraphView;
|
||||
toMermaid(): string;
|
||||
toDOT(): string;
|
||||
explain(routePath: string): Explain;
|
||||
/** Generate a structural OpenAPI 3.1 document from the registered routes. */
|
||||
openapi(info?: OpenApiInfo): OpenApiDoc;
|
||||
/** Names of optional providers that failed to boot and are running degraded (empty until {@link App.listen}). */
|
||||
degraded(): string[];
|
||||
bus: Bus;
|
||||
}
|
||||
|
||||
/** Internal per-route plan: match criteria, its resolved provider/step closure, and the compiled handler. */
|
||||
export interface RoutePlan {
|
||||
pattern: string;
|
||||
method: HttpMethod;
|
||||
transport: Transport;
|
||||
origin: string;
|
||||
declaration: string;
|
||||
providers: GraphNode[];
|
||||
steps: GraphNode[];
|
||||
handlerName: string;
|
||||
needs: string[];
|
||||
run: (ctx: any) => Promise<unknown>;
|
||||
transformer: typeof JsonTransformer;
|
||||
duplicates?: 'array' | 'last';
|
||||
maxBodyBytes?: number;
|
||||
maxParts?: number;
|
||||
args: ArgSpec[];
|
||||
}
|
||||
|
||||
/** Mesh networking options: a secret to gate this node's exports and/or remote teapots to connect to. */
|
||||
export interface MeshConfig {
|
||||
secret?: string;
|
||||
teapots?: Array<{ url: string; secret: string }>;
|
||||
/** How long an RPC may wait for its teapot before failing with 504 (default: 30s). */
|
||||
timeoutMs?: number;
|
||||
/**
|
||||
* Gap between heartbeat pings to each teapot (default: 15s). Two unanswered rounds close the
|
||||
* link, so a half-open connection surfaces as an immediate 503 instead of every request paying
|
||||
* `timeoutMs` first. Lower it to notice a dead teapot sooner, at the cost of more chatter.
|
||||
*/
|
||||
heartbeatMs?: number;
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
import { channel } from './channel';
|
||||
import type { Channel } from './channel';
|
||||
import type { App } from './app/types';
|
||||
import type { WsSocket, WsRequest } from './http/ws-core';
|
||||
import { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter';
|
||||
|
||||
// Minimal ambient for the Bun globals we use — avoids a @types/bun devDep.
|
||||
// Mirrors the real Bun.serve / server.upgrade / ServerWebSocket signatures we call.
|
||||
interface BunServerWebSocket {
|
||||
data: unknown;
|
||||
readyState: number;
|
||||
send(data: string): number;
|
||||
close(code?: number, reason?: string): void;
|
||||
terminate?(): void;
|
||||
}
|
||||
interface BunWebSocketHandler {
|
||||
open?(ws: BunServerWebSocket): void;
|
||||
message(ws: BunServerWebSocket, message: string | Uint8Array): void;
|
||||
close?(ws: BunServerWebSocket, code: number, reason: string): void;
|
||||
error?(ws: BunServerWebSocket, error?: unknown): void;
|
||||
}
|
||||
interface BunServer {
|
||||
port: number;
|
||||
stop(closeActiveConnections?: boolean): void;
|
||||
upgrade(request: Request, options?: { data?: unknown; headers?: Record<string, string> }): boolean;
|
||||
requestIP(request: Request): { address: string; family: string; port: number } | null;
|
||||
}
|
||||
interface BunServeOptions {
|
||||
port?: number;
|
||||
hostname?: string;
|
||||
fetch(request: Request, server: BunServer): Response | Promise<Response> | undefined;
|
||||
websocket?: BunWebSocketHandler;
|
||||
}
|
||||
type BunServeShortOptions = { port?: number; hostname?: string };
|
||||
declare const Bun: { serve(options: BunServeOptions): BunServer };
|
||||
|
||||
/** Per-connection state stashed on ws.data between fetch (upgrade) and the open/message/close callbacks. */
|
||||
interface BunConnData {
|
||||
wsReq: WsRequest;
|
||||
inbound: Channel<unknown>;
|
||||
ac: AbortController;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps a Bun ServerWebSocket as a neutral WsSocket. Unlike Deno/edge, Bun delivers socket
|
||||
* events to a server-level handler rather than the socket, so the channel and abort are
|
||||
* created during the upgrade and stashed on ws.data — there is nothing here to wire up.
|
||||
*/
|
||||
function bunSocket(ws: BunServerWebSocket): WsSocket {
|
||||
const { inbound, ac } = ws.data as BunConnData;
|
||||
|
||||
return neutralSocket(ws, inbound, ac);
|
||||
}
|
||||
|
||||
/**
|
||||
* Serve a Green Tea app on Bun: HTTP + SSE via app.fetch, WebSocket via Bun's server-level
|
||||
* websocket handler. The ServerWebSocket only exists in open(), so per-connection state
|
||||
* (inbound channel, abort, WsRequest) is stashed on ws.data during the upgrade.
|
||||
*/
|
||||
export function serveBun(app: App, options?: BunServeShortOptions): BunServer {
|
||||
return Bun.serve({
|
||||
...options,
|
||||
fetch(request, server) {
|
||||
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
||||
const inbound = channel();
|
||||
const ac = new AbortController();
|
||||
const wsReq = toWsRequest(request, server.requestIP(request)?.address ?? '');
|
||||
const data: BunConnData = { wsReq, inbound, ac };
|
||||
if (server.upgrade(request, { data })) return undefined;
|
||||
return new Response('WebSocket upgrade failed', { status: 400 });
|
||||
}
|
||||
|
||||
return app.fetch(request);
|
||||
},
|
||||
websocket: {
|
||||
open(ws) {
|
||||
const { wsReq } = ws.data as BunConnData;
|
||||
|
||||
void upgradeSafely(app, wsReq, bunSocket(ws));
|
||||
},
|
||||
message(ws, message) {
|
||||
const { inbound } = ws.data as BunConnData;
|
||||
|
||||
inbound.push(decodeMessage(message));
|
||||
},
|
||||
close(ws) {
|
||||
const { inbound, ac } = ws.data as BunConnData;
|
||||
inbound.close();
|
||||
ac.abort();
|
||||
},
|
||||
error(ws) {
|
||||
const { inbound, ac } = ws.data as BunConnData;
|
||||
inbound.fail(new Error('websocket error'));
|
||||
ac.abort();
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
+29
-12
@@ -1,10 +1,20 @@
|
||||
/** Names of every lifecycle event the framework emits over the {@link Bus}. */
|
||||
export type LifecycleEvent =
|
||||
| 'boot:provider:start' | 'boot:provider:ok' | 'boot:provider:fail'
|
||||
| 'request:step:enter' | 'request:step:leave' | 'request:step:error'
|
||||
| 'stream:open' | 'stream:close' | 'stream:error'
|
||||
| 'mesh:connect' | 'mesh:disconnect' | 'mesh:rpc:error'
|
||||
| 'boot:provider:start'
|
||||
| 'boot:provider:ok'
|
||||
| 'boot:provider:fail'
|
||||
| 'request:step:enter'
|
||||
| 'request:step:leave'
|
||||
| 'request:step:error'
|
||||
| 'stream:open'
|
||||
| 'stream:close'
|
||||
| 'stream:error'
|
||||
| 'mesh:connect'
|
||||
| 'mesh:disconnect'
|
||||
| 'mesh:rpc:error'
|
||||
| 'plugin:mounted';
|
||||
|
||||
/** Data carried by a lifecycle event: the subject's name plus optional scope, error and timing. */
|
||||
export interface EventPayload {
|
||||
name: string;
|
||||
scope?: string;
|
||||
@@ -12,19 +22,26 @@ export interface EventPayload {
|
||||
durationMs?: number;
|
||||
}
|
||||
|
||||
/** In-process pub/sub for framework lifecycle events; observer failures are swallowed so they never break the pipeline. */
|
||||
export class Bus {
|
||||
private readonly listeners = new Map<LifecycleEvent, Set<(p: EventPayload) => void>>();
|
||||
|
||||
on(event: LifecycleEvent, fn: (p: EventPayload) => void): () => void {
|
||||
const set = this.listeners.get(event) ?? new Set();
|
||||
set.add(fn);
|
||||
this.listeners.set(event, set);
|
||||
return () => set.delete(fn);
|
||||
/** Subscribe `listener` to `event`; returns an unsubscribe function. */
|
||||
on(event: LifecycleEvent, listener: (p: EventPayload) => void): () => void {
|
||||
const listenerSet = this.listeners.get(event) ?? new Set();
|
||||
listenerSet.add(listener);
|
||||
this.listeners.set(event, listenerSet);
|
||||
return () => listenerSet.delete(listener);
|
||||
}
|
||||
|
||||
emit(event: LifecycleEvent, p: EventPayload): void {
|
||||
for (const fn of this.listeners.get(event) ?? []) {
|
||||
try { fn(p); } catch { /* observers must never break the pipeline */ }
|
||||
/** Dispatch `payload` to every listener of `event`; a throwing listener is isolated and does not affect the others. */
|
||||
emit(event: LifecycleEvent, payload: EventPayload): void {
|
||||
for (const listener of this.listeners.get(event) ?? []) {
|
||||
try {
|
||||
listener(payload);
|
||||
} catch {
|
||||
/* observers must never break the pipeline */
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+51
-19
@@ -1,3 +1,7 @@
|
||||
/**
|
||||
* A push-driven async stream: producers call `push`/`close`/`fail`, consumers use `for await`.
|
||||
* Each `for await` gets its own independent subscription (fan-out).
|
||||
*/
|
||||
export interface Channel<T> extends AsyncIterable<T> {
|
||||
push(value: T): void;
|
||||
close(): void;
|
||||
@@ -5,15 +9,16 @@ export interface Channel<T> extends AsyncIterable<T> {
|
||||
readonly closed: boolean;
|
||||
}
|
||||
|
||||
/** Type guard: true when `x` implements the async-iterable protocol. */
|
||||
export function isAsyncIterable(x: unknown): x is AsyncIterable<unknown> {
|
||||
return x != null && typeof (x as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function';
|
||||
}
|
||||
|
||||
interface Sub<T> {
|
||||
iterator: AsyncIterator<T>;
|
||||
push(v: T, cap: number): void;
|
||||
push(value: T, cap: number): void;
|
||||
end(): void;
|
||||
fail(e: unknown): void;
|
||||
fail(err: unknown): void;
|
||||
}
|
||||
|
||||
function newSub<T>(onReturn: () => void): Sub<T> {
|
||||
@@ -23,29 +28,48 @@ function newSub<T>(onReturn: () => void): Sub<T> {
|
||||
let failure: { err: unknown } | null = null;
|
||||
|
||||
return {
|
||||
push(v, cap) {
|
||||
push(value, cap) {
|
||||
if (ended) return;
|
||||
if (pending) { const p = pending; pending = null; p.resolve({ value: v, done: false }); return; }
|
||||
queue.push(v);
|
||||
|
||||
if (pending) {
|
||||
const waiter = pending;
|
||||
pending = null;
|
||||
waiter.resolve({ value, done: false });
|
||||
return;
|
||||
}
|
||||
|
||||
queue.push(value);
|
||||
if (queue.length > cap) queue.shift(); // drop-oldest when buffer is full
|
||||
},
|
||||
end() {
|
||||
if (ended) return;
|
||||
ended = true;
|
||||
if (pending) { const p = pending; pending = null; p.resolve({ value: undefined as never, done: true }); }
|
||||
|
||||
if (pending) {
|
||||
const waiter = pending;
|
||||
pending = null;
|
||||
waiter.resolve({ value: undefined as never, done: true });
|
||||
}
|
||||
},
|
||||
fail(e) {
|
||||
fail(err) {
|
||||
if (ended) return;
|
||||
ended = true;
|
||||
failure = { err: e };
|
||||
if (pending) { const p = pending; pending = null; p.reject(e); }
|
||||
failure = { err };
|
||||
|
||||
if (pending) {
|
||||
const waiter = pending;
|
||||
pending = null;
|
||||
waiter.reject(err);
|
||||
}
|
||||
},
|
||||
iterator: {
|
||||
next(): Promise<IteratorResult<T>> {
|
||||
if (queue.length) return Promise.resolve({ value: queue.shift() as T, done: false });
|
||||
if (failure) return Promise.reject(failure.err);
|
||||
if (ended) return Promise.resolve({ value: undefined as never, done: true });
|
||||
return new Promise<IteratorResult<T>>((resolve, reject) => { pending = { resolve, reject }; });
|
||||
return new Promise<IteratorResult<T>>((resolve, reject) => {
|
||||
pending = { resolve, reject };
|
||||
});
|
||||
},
|
||||
return(): Promise<IteratorResult<T>> {
|
||||
ended = true;
|
||||
@@ -56,6 +80,10 @@ function newSub<T>(onReturn: () => void): Sub<T> {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a fan-out {@link Channel}. Values pushed are delivered to every active subscriber.
|
||||
* @param opts.buffer Per-subscriber queue cap; drops oldest when exceeded (default: unbounded).
|
||||
*/
|
||||
export function channel<T>(opts: { buffer?: number } = {}): Channel<T> {
|
||||
const cap = opts.buffer ?? Infinity;
|
||||
const subs = new Set<Sub<T>>();
|
||||
@@ -63,27 +91,31 @@ export function channel<T>(opts: { buffer?: number } = {}): Channel<T> {
|
||||
let closedFlag = false;
|
||||
|
||||
return {
|
||||
get closed() { return closedFlag; },
|
||||
get closed() {
|
||||
return closedFlag;
|
||||
},
|
||||
push(value) {
|
||||
if (done) return;
|
||||
for (const s of subs) s.push(value, cap);
|
||||
for (const sub of subs) sub.push(value, cap);
|
||||
},
|
||||
close() {
|
||||
if (done) return;
|
||||
done = true; closedFlag = true;
|
||||
for (const s of subs) s.end();
|
||||
done = true;
|
||||
closedFlag = true;
|
||||
for (const sub of subs) sub.end();
|
||||
subs.clear();
|
||||
},
|
||||
fail(err) {
|
||||
if (done) return;
|
||||
done = true; closedFlag = true;
|
||||
for (const s of subs) s.fail(err);
|
||||
done = true;
|
||||
closedFlag = true;
|
||||
for (const sub of subs) sub.fail(err);
|
||||
subs.clear();
|
||||
},
|
||||
[Symbol.asyncIterator](): AsyncIterator<T> {
|
||||
const s = newSub<T>(() => subs.delete(s));
|
||||
subs.add(s);
|
||||
return s.iterator;
|
||||
const sub = newSub<T>(() => subs.delete(sub));
|
||||
subs.add(sub);
|
||||
return sub.iterator;
|
||||
},
|
||||
};
|
||||
}
|
||||
+22
-6
@@ -1,27 +1,43 @@
|
||||
/** Lifetime of a binding: `app` values are memoized for the process, `request` values are recomputed per resolve. */
|
||||
export type Scope = 'app' | 'request';
|
||||
/** Produces a bound value from the current context; may be async. */
|
||||
export type Factory = (ctx: Record<string, unknown>) => unknown | Promise<unknown>;
|
||||
|
||||
interface Binding { scope: Scope; factory: Factory; cached?: unknown; resolved?: boolean }
|
||||
interface Binding {
|
||||
scope: Scope;
|
||||
factory: Factory;
|
||||
cached?: unknown;
|
||||
resolved?: boolean;
|
||||
}
|
||||
|
||||
/** Minimal token-keyed dependency container with app-scoped memoization and async, mesh-ready resolution. */
|
||||
export class Container {
|
||||
private readonly bindings = new Map<string, Binding>();
|
||||
|
||||
/** Bind `token` to `factory` under `scope`, replacing any existing binding. */
|
||||
register(token: string, scope: Scope, factory: Factory): void {
|
||||
this.bindings.set(token, { scope, factory });
|
||||
}
|
||||
|
||||
/** Whether `token` currently has a binding. */
|
||||
has(token: string): boolean {
|
||||
return this.bindings.has(token);
|
||||
}
|
||||
|
||||
/** Resolve `token`'s value; app-scoped results are cached, request-scoped ones re-run the factory. Throws on unknown tokens. */
|
||||
// ponytail: app-scope memoizes; request-scope always re-runs. resolve is async
|
||||
// so a future remote transport (mesh) slots in without changing callers.
|
||||
async resolve(token: string, ctx: Record<string, unknown> = {}): Promise<unknown> {
|
||||
const b = this.bindings.get(token);
|
||||
if (!b) throw new Error(`unknown token: ${token}`);
|
||||
if (b.scope === 'app' && b.resolved) return b.cached;
|
||||
const value = await b.factory(ctx);
|
||||
if (b.scope === 'app') { b.cached = value; b.resolved = true; }
|
||||
const binding = this.bindings.get(token);
|
||||
if (!binding) throw new Error(`unknown token: ${token}`);
|
||||
if (binding.scope === 'app' && binding.resolved) return binding.cached;
|
||||
const value = await binding.factory(ctx);
|
||||
|
||||
if (binding.scope === 'app') {
|
||||
binding.cached = value;
|
||||
binding.resolved = true;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
import type { App } from './app/types';
|
||||
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
|
||||
|
||||
// The project tsconfig's `lib` doesn't include `DOM`, and the installed `@types/node` (18.x)
|
||||
// doesn't declare a global `WebSocket` either — so we ambient-declare just the shape we use.
|
||||
interface WebSocket extends EventfulSocket {
|
||||
binaryType: string;
|
||||
}
|
||||
|
||||
// Minimal ambient for the Deno globals we use — avoids a @types/deno devDep.
|
||||
// Mirrors the real Deno.serve / Deno.upgradeWebSocket signatures we call.
|
||||
interface DenoServeOptions {
|
||||
port?: number;
|
||||
hostname?: string;
|
||||
signal?: AbortSignal;
|
||||
onListen?: (addr: { hostname: string; port: number }) => void;
|
||||
}
|
||||
interface DenoServeHandlerInfo {
|
||||
remoteAddr: { hostname: string; port: number; transport: string };
|
||||
}
|
||||
interface DenoHttpServer {
|
||||
finished: Promise<void>;
|
||||
shutdown(): Promise<void>;
|
||||
}
|
||||
type DenoServeHandler = (request: Request, info: DenoServeHandlerInfo) => Response | Promise<Response>;
|
||||
declare const Deno: {
|
||||
serve(options: DenoServeOptions, handler: DenoServeHandler): DenoHttpServer;
|
||||
upgradeWebSocket(request: Request): { socket: WebSocket; response: Response };
|
||||
};
|
||||
|
||||
/**
|
||||
* Serve a Green Tea app on Deno: HTTP + SSE via app.fetch, WebSocket via Deno.upgradeWebSocket.
|
||||
* WebSocket messages flow through app.upgrade over the shared neutral core.
|
||||
*/
|
||||
export function serveDeno(app: App, options?: DenoServeOptions): DenoHttpServer {
|
||||
return Deno.serve(options ?? {}, (request, info) => {
|
||||
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
||||
// Deno invalidates request connection metadata as soon as the upgrade is accepted.
|
||||
const wsRequest = toWsRequest(request, info.remoteAddr.hostname);
|
||||
const { socket, response } = Deno.upgradeWebSocket(request);
|
||||
socket.binaryType = 'arraybuffer'; // deliver binary frames as ArrayBuffer, which decodeMessage expects
|
||||
// fire-and-forget: the 101 response must be returned synchronously while the graph runs
|
||||
void upgradeSafely(app, wsRequest, eventSocket(socket));
|
||||
return response;
|
||||
}
|
||||
|
||||
return app.fetch(request);
|
||||
});
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
import type { App } from './app/types';
|
||||
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
|
||||
|
||||
// Minimal ambient for the Cloudflare Workers globals we use — avoids @cloudflare/workers-types.
|
||||
// Declares only what we call; mirrors the real workerd signatures.
|
||||
interface EdgeWebSocket extends EventfulSocket {
|
||||
accept(): void;
|
||||
}
|
||||
interface EdgeCtx {
|
||||
waitUntil(promise: Promise<unknown>): void;
|
||||
}
|
||||
declare const WebSocketPair: { new (): { 0: EdgeWebSocket; 1: EdgeWebSocket } };
|
||||
|
||||
/**
|
||||
* Cloudflare Workers / edge handler: HTTP + SSE via app.fetch, WebSocket via WebSocketPair.
|
||||
* Use as `export default { fetch: edgeHandler(app) }`. Requires the `nodejs_compat`
|
||||
* compatibility flag. The WS lifecycle runs on ctx.waitUntil so it survives past the 101 response.
|
||||
*/
|
||||
export function edgeHandler(
|
||||
app: App,
|
||||
): (request: Request, env?: unknown, ctx?: EdgeCtx) => Response | Promise<Response> {
|
||||
return (request, _env, ctx) => {
|
||||
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
||||
const [client, server] = Object.values(new WebSocketPair()) as [EdgeWebSocket, EdgeWebSocket];
|
||||
server.accept();
|
||||
const wsReq = toWsRequest(request, request.headers.get('cf-connecting-ip') ?? '');
|
||||
const lifecycle = upgradeSafely(app, wsReq, eventSocket(server));
|
||||
if (ctx?.waitUntil) ctx.waitUntil(lifecycle);
|
||||
else void lifecycle;
|
||||
|
||||
return new Response(null, { status: 101, webSocket: client } as ResponseInit & { webSocket: EdgeWebSocket });
|
||||
}
|
||||
|
||||
return app.fetch(request);
|
||||
};
|
||||
}
|
||||
+9
-3
@@ -1,3 +1,7 @@
|
||||
/**
|
||||
* Serializes stream items into wire frames for a streaming transport (SSE, NDJSON).
|
||||
* `headers` is written once before the first frame; `ping` (if present) is sent periodically to keep the connection alive.
|
||||
*/
|
||||
export interface StreamEncoder {
|
||||
headers: Record<string, string>;
|
||||
encode(item: unknown): string | Buffer;
|
||||
@@ -5,17 +9,19 @@ export interface StreamEncoder {
|
||||
ping?(): string;
|
||||
}
|
||||
|
||||
const msgOf = (e: unknown): string => (e instanceof Error ? e.message : String(e));
|
||||
const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));
|
||||
|
||||
/** Server-Sent Events encoder: one JSON payload per `data:` event, with comment-line pings. */
|
||||
export const sseEncoder: StreamEncoder = {
|
||||
headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' },
|
||||
encode: (item) => `data: ${JSON.stringify(item)}\n\n`,
|
||||
encodeError: (err) => `event: error\ndata: ${JSON.stringify({ error: msgOf(err) })}\n\n`,
|
||||
encodeError: (err) => `event: error\ndata: ${JSON.stringify({ error: messageOf(err) })}\n\n`,
|
||||
ping: () => ': ping\n\n',
|
||||
};
|
||||
|
||||
/** Newline-delimited JSON encoder: one JSON object per line. */
|
||||
export const ndjsonEncoder: StreamEncoder = {
|
||||
headers: { 'content-type': 'application/x-ndjson' },
|
||||
encode: (item) => `${JSON.stringify(item)}\n`,
|
||||
encodeError: (err) => `${JSON.stringify({ error: msgOf(err) })}\n`,
|
||||
encodeError: (err) => `${JSON.stringify({ error: messageOf(err) })}\n`,
|
||||
};
|
||||
+11
-3
@@ -1,18 +1,23 @@
|
||||
/** A single flow step: receives the accumulated context and returns the fields it contributes. */
|
||||
export type StepFn<In, Out> = (ctx: In) => Out | Promise<Out>;
|
||||
|
||||
/** A built flow ready to execute: its ordered steps, terminal handler, and a `run` entry point. */
|
||||
export interface CompiledFlow<Seed, Acc> {
|
||||
steps: { name: string; fn: StepFn<any, any> }[];
|
||||
handler: (ctx: Acc) => unknown;
|
||||
run(seed: Seed): Promise<unknown>;
|
||||
}
|
||||
|
||||
/** Immutable builder that chains typed steps, each widening the accumulated context type. */
|
||||
export class Flow<Seed, Acc> {
|
||||
constructor(private readonly steps: { name: string; fn: StepFn<any, any> }[] = []) {}
|
||||
|
||||
/** Appends a step and returns a new Flow whose context now includes the step's output. */
|
||||
step<Out>(name: string, fn: StepFn<Acc, Out>): Flow<Seed, Acc & Out> {
|
||||
return new Flow<Seed, Acc & Out>([...this.steps, { name, fn }]);
|
||||
}
|
||||
|
||||
/** Seals the flow with a terminal handler, producing a runnable CompiledFlow. */
|
||||
handle(handler: (ctx: Acc) => unknown): CompiledFlow<Seed, Acc> {
|
||||
const steps = this.steps;
|
||||
return {
|
||||
@@ -20,16 +25,19 @@ export class Flow<Seed, Acc> {
|
||||
handler,
|
||||
async run(seed: Seed): Promise<unknown> {
|
||||
let ctx: any = { ...seed };
|
||||
for (const s of steps) {
|
||||
const out = await s.fn(ctx);
|
||||
ctx = { ...ctx, ...out };
|
||||
|
||||
for (const step of steps) {
|
||||
const output = await step.fn(ctx);
|
||||
ctx = { ...ctx, ...output };
|
||||
}
|
||||
|
||||
return handler(ctx);
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** Starts a new flow whose seed and initial context are the same type. */
|
||||
export function flow<Seed extends object>(): Flow<Seed, Seed> {
|
||||
return new Flow<Seed, Seed>();
|
||||
}
|
||||
+219
-26
@@ -1,45 +1,238 @@
|
||||
export interface GraphNodeView { name: string; kind: 'provider' | 'step'; origin: string; needs: string[]; provides: string[] }
|
||||
export interface GraphRouteView { pattern: string; method: string; transport: string; chain: string[] }
|
||||
export interface GraphView { nodes: GraphNodeView[]; routes: GraphRouteView[] }
|
||||
/** Renderable view of a graph node (provider or step). */
|
||||
export interface GraphNodeView {
|
||||
name: string;
|
||||
kind: 'provider' | 'step';
|
||||
origin: string;
|
||||
needs: string[];
|
||||
provides: string[];
|
||||
}
|
||||
/** Renderable view of a route and the chain of nodes feeding its handler. */
|
||||
export interface GraphRouteView {
|
||||
pattern: string;
|
||||
method: string;
|
||||
transport: string;
|
||||
chain: string[];
|
||||
}
|
||||
/** Full graph payload consumed by the diagram renderers. */
|
||||
export interface GraphView {
|
||||
nodes: GraphNodeView[];
|
||||
routes: GraphRouteView[];
|
||||
}
|
||||
|
||||
const nid = (s: string) => 'n_' + s.replace(/[^a-zA-Z0-9]/g, '_');
|
||||
const rid = (s: string) => 'r_' + s.replace(/[^a-zA-Z0-9]/g, '_');
|
||||
/** Sanitizes a node name into a Mermaid/DOT-safe node id. */
|
||||
const nid = (name: string) => 'n_' + name.replace(/[^a-zA-Z0-9]/g, '_');
|
||||
/** Sanitizes a route pattern into a Mermaid/DOT-safe node id. */
|
||||
const rid = (pattern: string) => 'r_' + pattern.replace(/[^a-zA-Z0-9]/g, '_');
|
||||
|
||||
/** Renders the graph view as Mermaid `flowchart` source. */
|
||||
export function toMermaid(view: GraphView): string {
|
||||
const known = new Set(view.nodes.map((n) => n.name));
|
||||
const known = new Set(view.nodes.map((node) => node.name));
|
||||
const out: string[] = ['flowchart LR'];
|
||||
for (const n of view.nodes) {
|
||||
out.push(n.kind === 'provider' ? ` ${nid(n.name)}(["${n.name}"])` : ` ${nid(n.name)}["${n.name}"]`);
|
||||
|
||||
for (const node of view.nodes) {
|
||||
out.push(
|
||||
node.kind === 'provider' ? ` ${nid(node.name)}(["${node.name}"])` : ` ${nid(node.name)}["${node.name}"]`,
|
||||
);
|
||||
}
|
||||
for (const n of view.nodes) for (const need of n.needs) if (known.has(need)) out.push(` ${nid(need)} --> ${nid(n.name)}`);
|
||||
for (const r of view.routes) {
|
||||
out.push(` ${rid(r.pattern)}{{"${r.method} ${r.pattern}"}}`);
|
||||
for (const c of r.chain) if (known.has(c)) out.push(` ${nid(c)} --> ${rid(r.pattern)}`);
|
||||
|
||||
for (const node of view.nodes)
|
||||
for (const need of node.needs) if (known.has(need)) out.push(` ${nid(need)} --> ${nid(node.name)}`);
|
||||
|
||||
for (const route of view.routes) {
|
||||
out.push(` ${rid(route.pattern)}{{"${route.method} ${route.pattern}"}}`);
|
||||
for (const link of route.chain) if (known.has(link)) out.push(` ${nid(link)} --> ${rid(route.pattern)}`);
|
||||
}
|
||||
|
||||
return out.join('\n');
|
||||
}
|
||||
|
||||
/** Renders the graph view as Graphviz DOT source. */
|
||||
export function toDOT(view: GraphView): string {
|
||||
const known = new Set(view.nodes.map((n) => n.name));
|
||||
const known = new Set(view.nodes.map((node) => node.name));
|
||||
const out: string[] = ['digraph green_tea {', ' rankdir=LR;'];
|
||||
for (const n of view.nodes) {
|
||||
out.push(` "${n.name}" [shape=${n.kind === 'provider' ? 'ellipse' : 'box'}];`);
|
||||
|
||||
for (const node of view.nodes) {
|
||||
out.push(` "${node.name}" [shape=${node.kind === 'provider' ? 'ellipse' : 'box'}];`);
|
||||
}
|
||||
for (const n of view.nodes) for (const need of n.needs) if (known.has(need)) out.push(` "${need}" -> "${n.name}";`);
|
||||
for (const r of view.routes) {
|
||||
const label = `${r.method} ${r.pattern}`;
|
||||
|
||||
for (const node of view.nodes)
|
||||
for (const need of node.needs) if (known.has(need)) out.push(` "${need}" -> "${node.name}";`);
|
||||
|
||||
for (const route of view.routes) {
|
||||
const label = `${route.method} ${route.pattern}`;
|
||||
out.push(` "${label}" [shape=hexagon];`);
|
||||
for (const c of r.chain) if (known.has(c)) out.push(` "${c}" -> "${label}";`);
|
||||
for (const link of route.chain) if (known.has(link)) out.push(` "${link}" -> "${label}";`);
|
||||
}
|
||||
|
||||
out.push('}');
|
||||
return out.join('\n');
|
||||
}
|
||||
|
||||
export function graphHtml(mermaid: string): string {
|
||||
return [
|
||||
'<!doctype html><html><head><meta charset="utf-8"><title>green-tea graph</title>',
|
||||
'<script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script></head>',
|
||||
'<body><pre class="mermaid">', mermaid, '</pre>',
|
||||
'<script>mermaid.initialize({ startOnLoad: true });</script></body></html>',
|
||||
].join('\n');
|
||||
/**
|
||||
* Renders the graph as a self-contained, interactive HTML page (Cytoscape.js +
|
||||
* dagre, both from a CDN — no runtime dependency is added). Clicking a route
|
||||
* lights up its exact transitive slice and dims everything else; clicking a
|
||||
* provider/step shows its blast radius (every route that depends on it).
|
||||
*
|
||||
* The whole {@link GraphView} is embedded as JSON, so all interaction is
|
||||
* client-side — the page needs nothing from the server after it loads.
|
||||
*/
|
||||
/** The Green Tea. mark (leaf whose venation is a dependency graph), inlined for the dev graph header. */
|
||||
const BRAND_LOGO =
|
||||
'<svg viewBox="0 0 611 620" fill="none" aria-hidden="true"> <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>';
|
||||
|
||||
export function graphHtml(view: GraphView): string {
|
||||
const data = JSON.stringify(view).replace(/</g, '\\u003c');
|
||||
return `<!doctype html><html lang="en"><head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>green-tea graph</title>
|
||||
<script src="https://cdn.jsdelivr.net/npm/cytoscape@3.30.2/dist/cytoscape.min.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/dagre@0.8.5/dist/dagre.min.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/cytoscape-dagre@2.5.0/cytoscape-dagre.min.js"></script>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Zen+Maru+Gothic:wght@700&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
:root { --bg:#fff; --ink:#1c2128; --dim:#57606a; --line:#d0d7de; --tea:#7c6cf0; --panel:#f6f8fa;
|
||||
--matcha:#3fa873; --prov:#1f9e8a; --step:#7c6cf0; --need:#2f81f7; --feed:#bf8700; }
|
||||
@media (prefers-color-scheme: dark) { :root { --bg:#0d1117; --ink:#e6edf3; --dim:#8b949e; --line:#30363d; --tea:#a78bfa; --panel:#161b22;
|
||||
--matcha:#5fb88a; --prov:#3fd0b8; --step:#a78bfa; --need:#58a6ff; --feed:#e3b341; } }
|
||||
* { box-sizing:border-box; } html,body { margin:0; height:100%; background:var(--bg); color:var(--ink);
|
||||
font:13px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace; }
|
||||
#cy { position:absolute; inset:0; }
|
||||
#bar { position:absolute; top:0; left:0; right:0; padding:10px 14px; z-index:2; pointer-events:none;
|
||||
background:linear-gradient(var(--bg),transparent); }
|
||||
#bar b { color:var(--tea); } #bar span { color:var(--dim); }
|
||||
#bar .brand { display:flex; align-items:center; gap:9px; margin-bottom:5px; }
|
||||
#bar .brand svg { height:27px; width:auto; }
|
||||
#bar .brand .wm { font-family:'Zen Maru Gothic',sans-serif; font-weight:700; font-size:18px; color:var(--matcha); }
|
||||
#bar .brand .wm .dot { color:var(--step); }
|
||||
#legend { margin-top:6px; color:var(--dim); font-size:12px; display:flex; gap:14px; flex-wrap:wrap; }
|
||||
#legend i { display:inline-block; vertical-align:middle; margin-right:5px; }
|
||||
#legend .sw { width:11px; height:11px; border-radius:3px; border:1.5px solid; }
|
||||
#legend .prov { background:var(--panel); border-color:var(--prov); }
|
||||
#legend .step { background:var(--panel); border-color:var(--step); border-radius:0; }
|
||||
#legend .route { background:var(--tea); border-color:var(--tea); }
|
||||
#legend .ln { width:16px; height:0; border-top:3px solid; border-radius:0; }
|
||||
#legend .need { border-color:var(--need); } #legend .feed { border-color:var(--feed); }
|
||||
#legend .tp { background:transparent; border-color:var(--dim); }
|
||||
#legend .tp-http { border-style:solid; } #legend .tp-sse { border-style:dashed; }
|
||||
#legend .tp-ws { border-style:double; border-width:3px; }
|
||||
#info { position:absolute; left:14px; bottom:14px; z-index:2; max-width:340px; padding:10px 12px;
|
||||
background:var(--panel); border:1px solid var(--line); border-radius:8px; white-space:pre-wrap; display:none; }
|
||||
#info .t { color:var(--tea); font-weight:700; } #info .k { color:var(--dim); }
|
||||
</style></head><body>
|
||||
<div id="bar"><div class="brand">${BRAND_LOGO}<span class="wm">Green Tea<span class="dot">.</span></span></div><span>click a <b>route</b> for its slice · click a <b>provider/step</b> for its blast radius · drag to rearrange · click canvas to reset</span>
|
||||
<div id="legend"><span><i class="sw prov"></i>provider</span><span><i class="sw step"></i>step</span><span><i class="ln need"></i>needs</span><span><i class="ln feed"></i>feeds endpoint</span><span><i class="sw tp tp-http"></i>HTTP</span><span><i class="sw tp tp-sse"></i>SSE</span><span><i class="sw tp tp-ws"></i>WS</span></div></div>
|
||||
<div id="cy"></div>
|
||||
<div id="info"></div>
|
||||
<script>
|
||||
var DATA = ${data};
|
||||
try { if (window.cytoscapeDagre) cytoscape.use(window.cytoscapeDagre); } catch (e) {}
|
||||
var css = getComputedStyle(document.documentElement);
|
||||
var C = function (n) { return css.getPropertyValue(n).trim(); };
|
||||
var nodeNames = new Set(DATA.nodes.map(function (n) { return n.name; }));
|
||||
var nid = function (s) { return 'n_' + s.replace(/[^a-zA-Z0-9]/g, '_'); };
|
||||
var rid = function (s) { return 'r_' + s.replace(/[^a-zA-Z0-9]/g, '_'); };
|
||||
|
||||
// HTTP method -> colour, so the endpoint type is visual, not just text.
|
||||
var METHOD_COLORS = { GET: '#3fb950', POST: '#a371f7', PUT: '#d29922', PATCH: '#db61a2', DELETE: '#f85149', HEAD: '#8b949e', OPTIONS: '#8b949e' };
|
||||
var methodColor = function (m) { return METHOD_COLORS[m] || '#8b949e'; };
|
||||
|
||||
var els = [];
|
||||
DATA.nodes.forEach(function (n) {
|
||||
els.push({ data: { id: nid(n.name), label: n.name, kind: n.kind, origin: n.origin,
|
||||
needs: (n.needs || []).join(', '), provides: (n.provides || []).join(', ') } });
|
||||
});
|
||||
DATA.routes.forEach(function (r) {
|
||||
var suffix = r.transport && r.transport !== 'buffer' ? ' · ' + r.transport : '';
|
||||
els.push({ data: { id: rid(r.pattern), label: r.method + ' ' + r.pattern + suffix, kind: 'route',
|
||||
method: r.method, transport: r.transport, color: methodColor(r.method) } });
|
||||
});
|
||||
DATA.nodes.forEach(function (n) {
|
||||
(n.needs || []).forEach(function (need) {
|
||||
if (nodeNames.has(need)) els.push({ data: { id: 'e' + nid(need) + nid(n.name), source: nid(need), target: nid(n.name), rel: 'need' } });
|
||||
});
|
||||
});
|
||||
DATA.routes.forEach(function (r) {
|
||||
(r.chain || []).forEach(function (name) {
|
||||
if (nodeNames.has(name)) els.push({ data: { id: 'e' + nid(name) + rid(r.pattern), source: nid(name), target: rid(r.pattern), rel: 'feed' } });
|
||||
});
|
||||
});
|
||||
|
||||
// Precomputed highlight sets (uses green-tea's real per-route slice).
|
||||
var routeChain = {}; DATA.routes.forEach(function (r) {
|
||||
routeChain[rid(r.pattern)] = (r.chain || []).filter(function (x) { return nodeNames.has(x); }).map(nid);
|
||||
});
|
||||
var nodeRoutes = {}; DATA.nodes.forEach(function (n) {
|
||||
nodeRoutes[nid(n.name)] = DATA.routes.filter(function (r) { return (r.chain || []).indexOf(n.name) >= 0; })
|
||||
.map(function (r) { return rid(r.pattern); });
|
||||
});
|
||||
|
||||
// Method colour chips in the legend — only for methods actually present.
|
||||
var legend = document.getElementById('legend'), seenMethod = {};
|
||||
DATA.routes.forEach(function (r) {
|
||||
if (seenMethod[r.method]) return; seenMethod[r.method] = 1;
|
||||
var s = document.createElement('span');
|
||||
s.innerHTML = '<i class="sw" style="background:' + methodColor(r.method) + ';border-color:' + methodColor(r.method) + '"></i>' + r.method;
|
||||
legend.appendChild(s);
|
||||
});
|
||||
|
||||
var cy = cytoscape({
|
||||
container: document.getElementById('cy'),
|
||||
elements: els,
|
||||
style: [
|
||||
{ selector: 'node', style: { 'label': 'data(label)', 'color': C('--ink'), 'font-family': 'ui-monospace,Menlo,monospace',
|
||||
'font-size': 12, 'text-valign': 'center', 'text-halign': 'center', 'width': 'label', 'height': 'label',
|
||||
'padding': '10px', 'background-color': C('--panel'), 'border-width': 1.5, 'border-color': C('--tea'), 'shape': 'round-rectangle' } },
|
||||
{ selector: 'node[kind = "provider"]', style: { 'shape': 'round-rectangle', 'background-color': C('--panel'), 'border-color': C('--prov') } },
|
||||
{ selector: 'node[kind = "step"]', style: { 'shape': 'rectangle', 'border-color': C('--step') } },
|
||||
{ selector: 'node[kind = "route"]', style: { 'shape': 'round-rectangle', 'background-color': 'data(color)', 'color': '#fff', 'border-width': 1.5, 'border-color': '#fff', 'border-style': 'solid', 'font-weight': 'bold' } },
|
||||
{ selector: 'node[transport = "sse"]', style: { 'border-style': 'dashed', 'border-width': 2.5 } },
|
||||
{ selector: 'node[transport = "negotiate"]', style: { 'border-style': 'dotted', 'border-width': 2.5 } },
|
||||
{ selector: 'node[transport = "ws"]', style: { 'border-style': 'double', 'border-width': 4 } },
|
||||
{ selector: 'edge', style: { 'width': 1, 'target-arrow-shape': 'triangle', 'curve-style': 'bezier', 'arrow-scale': 0.75 } },
|
||||
{ selector: 'edge[rel = "need"]', style: { 'line-color': C('--need'), 'target-arrow-color': C('--need') } },
|
||||
{ selector: 'edge[rel = "feed"]', style: { 'line-color': C('--feed'), 'target-arrow-color': C('--feed') } },
|
||||
{ selector: '.dim', style: { 'opacity': 0.1 } },
|
||||
{ selector: 'node.hot', style: { 'border-width': 3 } },
|
||||
{ selector: 'edge.hot', style: { 'width': 1.9, 'opacity': 1 } }
|
||||
]
|
||||
});
|
||||
|
||||
var layout = { name: 'dagre', rankDir: 'LR', nodeSep: 36, rankSep: 90, edgeSep: 12 };
|
||||
try { cy.layout(layout).run(); } catch (e) { cy.layout({ name: 'breadthfirst', directed: true }).run(); }
|
||||
|
||||
function highlight(idSet) {
|
||||
cy.batch(function () {
|
||||
cy.elements().removeClass('hot').addClass('dim');
|
||||
idSet.forEach(function (id) { cy.getElementById(id).removeClass('dim').addClass('hot'); });
|
||||
cy.edges().forEach(function (e) {
|
||||
if (idSet.has(e.source().id()) && idSet.has(e.target().id())) e.removeClass('dim').addClass('hot');
|
||||
});
|
||||
});
|
||||
}
|
||||
function reset() { cy.batch(function () { cy.elements().removeClass('dim hot'); }); }
|
||||
|
||||
var info = document.getElementById('info');
|
||||
function showInfo(el) {
|
||||
var k = el.data('kind');
|
||||
var body = k === 'route'
|
||||
? '<span class="k">' + el.data('transport') + ' route</span>'
|
||||
: '<span class="k">kind</span> ' + k + '\\n<span class="k">needs</span> ' + (el.data('needs') || '—')
|
||||
+ '\\n<span class="k">provides</span> ' + (el.data('provides') || '—')
|
||||
+ '\\n<span class="k">origin</span> ' + (el.data('origin') || '—');
|
||||
info.style.display = 'block';
|
||||
info.innerHTML = '<span class="t">' + el.data('label') + '</span>\\n' + body;
|
||||
}
|
||||
|
||||
cy.on('tap', 'node', function (evt) {
|
||||
var el = evt.target, id = el.id();
|
||||
var ids = el.data('kind') === 'route'
|
||||
? new Set([id].concat(routeChain[id] || []))
|
||||
: new Set([id].concat(nodeRoutes[id] || []));
|
||||
highlight(ids);
|
||||
showInfo(el);
|
||||
});
|
||||
cy.on('mouseover', 'node', function (evt) { showInfo(evt.target); });
|
||||
cy.on('tap', function (evt) { if (evt.target === cy) { reset(); info.style.display = 'none'; } });
|
||||
</script></body></html>`;
|
||||
}
|
||||
+52
-27
@@ -1,21 +1,40 @@
|
||||
function levenshtein(a: string, b: string): number {
|
||||
const m = a.length, n = b.length;
|
||||
const d: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
|
||||
for (let i = 0; i <= m; i++) d[i][0] = i;
|
||||
for (let j = 0; j <= n; j++) d[0][j] = j;
|
||||
for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++) {
|
||||
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
||||
}
|
||||
return d[m][n];
|
||||
const aLen = a.length,
|
||||
bLen = b.length;
|
||||
const matrix: number[][] = Array.from({ length: aLen + 1 }, () => Array(bLen + 1).fill(0));
|
||||
for (let i = 0; i <= aLen; i++) matrix[i][0] = i;
|
||||
for (let j = 0; j <= bLen; j++) matrix[0][j] = j;
|
||||
|
||||
for (let i = 1; i <= aLen; i++)
|
||||
for (let j = 1; j <= bLen; j++) {
|
||||
matrix[i][j] = Math.min(
|
||||
matrix[i - 1][j] + 1,
|
||||
matrix[i][j - 1] + 1,
|
||||
matrix[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1),
|
||||
);
|
||||
}
|
||||
|
||||
return matrix[aLen][bLen];
|
||||
}
|
||||
|
||||
/** Returns the candidate within edit distance 2 of `token`, for "did you mean?" hints. */
|
||||
export function nearest(token: string, candidates: Iterable<string>): string | undefined {
|
||||
let best: string | undefined;
|
||||
let bestD = 3; // only suggest edit distance <= 2
|
||||
for (const c of candidates) { const dist = levenshtein(token, c); if (dist < bestD) { bestD = dist; best = c; } }
|
||||
let bestDistance = 3; // only suggest edit distance <= 2
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const distance = levenshtein(token, candidate);
|
||||
|
||||
if (distance < bestDistance) {
|
||||
bestDistance = distance;
|
||||
best = candidate;
|
||||
}
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
/** A node in the dependency graph: what it provides, what it needs, and where it came from. */
|
||||
export interface GraphNode {
|
||||
name: string;
|
||||
needs: string[];
|
||||
@@ -23,15 +42,16 @@ export interface GraphNode {
|
||||
origin: string;
|
||||
}
|
||||
|
||||
/** Orders nodes so every dependency precedes its dependents; throws on missing keys or cycles. */
|
||||
export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] {
|
||||
const producedBy = new Map<string, GraphNode>();
|
||||
for (const n of nodes) for (const key of n.provides) producedBy.set(key, n);
|
||||
for (const node of nodes) for (const key of node.provides) producedBy.set(key, node);
|
||||
|
||||
// validate dependencies exist
|
||||
for (const n of nodes) {
|
||||
for (const key of n.needs) {
|
||||
for (const node of nodes) {
|
||||
for (const key of node.needs) {
|
||||
if (!seedKeys.includes(key) && !producedBy.has(key)) {
|
||||
throw new Error(`missing dependency: ${key} needed by ${n.name}`);
|
||||
throw new Error(`missing dependency: ${key} needed by ${node.name}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -39,28 +59,32 @@ export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] {
|
||||
const ordered: GraphNode[] = [];
|
||||
const state = new Map<GraphNode, 'visiting' | 'done'>();
|
||||
|
||||
const visit = (n: GraphNode, trail: string[]): void => {
|
||||
const s = state.get(n);
|
||||
if (s === 'done') return;
|
||||
if (s === 'visiting') throw new Error(`cycle detected: ${[...trail, n.name].join(' -> ')}`);
|
||||
state.set(n, 'visiting');
|
||||
for (const key of n.needs) {
|
||||
const dep = producedBy.get(key);
|
||||
if (dep && dep !== n) visit(dep, [...trail, n.name]);
|
||||
const visit = (node: GraphNode, trail: string[]): void => {
|
||||
const visitState = state.get(node);
|
||||
if (visitState === 'done') return;
|
||||
if (visitState === 'visiting') throw new Error(`cycle detected: ${[...trail, node.name].join(' -> ')}`);
|
||||
state.set(node, 'visiting');
|
||||
|
||||
for (const key of node.needs) {
|
||||
const dependency = producedBy.get(key);
|
||||
if (dependency && dependency !== node) visit(dependency, [...trail, node.name]);
|
||||
}
|
||||
state.set(n, 'done');
|
||||
ordered.push(n);
|
||||
|
||||
state.set(node, 'done');
|
||||
ordered.push(node);
|
||||
};
|
||||
|
||||
for (const n of nodes) visit(n, []);
|
||||
for (const node of nodes) visit(node, []);
|
||||
return ordered;
|
||||
}
|
||||
|
||||
/** Filters `ordered` down to the transitive closure of producers reachable from `needs`. */
|
||||
export function subgraphFor(needs: string[], ordered: GraphNode[]): GraphNode[] {
|
||||
const producedBy = new Map<string, GraphNode>();
|
||||
for (const n of ordered) for (const k of n.provides) producedBy.set(k, n);
|
||||
for (const node of ordered) for (const key of node.provides) producedBy.set(key, node);
|
||||
const inClosure = new Set<GraphNode>();
|
||||
const work = [...needs];
|
||||
|
||||
while (work.length) {
|
||||
const token = work.pop() as string;
|
||||
const node = producedBy.get(token);
|
||||
@@ -68,5 +92,6 @@ export function subgraphFor(needs: string[], ordered: GraphNode[]): GraphNode[]
|
||||
inClosure.add(node);
|
||||
work.push(...node.needs);
|
||||
}
|
||||
return ordered.filter((n) => inClosure.has(n));
|
||||
|
||||
return ordered.filter((node) => inClosure.has(node));
|
||||
}
|
||||
-242
@@ -1,242 +0,0 @@
|
||||
import http from 'http';
|
||||
import { once } from 'events';
|
||||
import { channel } from './channel';
|
||||
import { errorToResponse } from './transformers';
|
||||
import { HttpError, isHttpError } from './signals';
|
||||
import { sseEncoder, ndjsonEncoder, StreamEncoder } from './encoders';
|
||||
import { isStreamResult, type PipelineResult, type ResponseShape } from './pipeline';
|
||||
import type { Transport } from './metadata';
|
||||
import type { Bus } from './bus';
|
||||
|
||||
export interface RequestLimits {
|
||||
maxBodyBytes?: number; // default 1_000_000
|
||||
requestTimeoutMs?: number; // default 30_000
|
||||
headersTimeoutMs?: number; // default 10_000
|
||||
keepAliveTimeoutMs?: number; // default 5_000
|
||||
}
|
||||
export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void> }
|
||||
|
||||
export type RouteHandler = (req: {
|
||||
method: string; url: string;
|
||||
headers: Record<string, string | string[] | undefined>;
|
||||
params: Record<string, string>;
|
||||
query: Record<string, string>;
|
||||
body: unknown;
|
||||
}) => Promise<PipelineResult>;
|
||||
|
||||
export interface RouteDef { method: string; pattern: string; transport: Transport; handler: RouteHandler }
|
||||
export interface MatchedRoute { params: Record<string, string>; def: RouteDef }
|
||||
|
||||
export interface WsOpenCtx {
|
||||
params: Record<string, string>;
|
||||
inbound: AsyncIterable<unknown>;
|
||||
abort: AbortSignal;
|
||||
req: http.IncomingMessage;
|
||||
}
|
||||
export interface WsRouteDef { pattern: string; open: (ctx: WsOpenCtx) => Promise<AsyncIterable<unknown>> }
|
||||
|
||||
export interface MeshControl { path: string; handle(ws: any, req: http.IncomingMessage): void }
|
||||
|
||||
const PING_MS = 15_000;
|
||||
|
||||
export function matchPattern(pattern: string, path: string): Record<string, string> | undefined {
|
||||
const segs = path.split('/').filter(Boolean);
|
||||
const pat = pattern.split('/').filter(Boolean);
|
||||
if (pat.length !== segs.length) return undefined;
|
||||
const params: Record<string, string> = {};
|
||||
for (let i = 0; i < pat.length; i++) {
|
||||
if (pat[i].startsWith(':')) params[pat[i].slice(1)] = decodeURIComponent(segs[i]);
|
||||
else if (pat[i] !== segs[i]) return undefined;
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined {
|
||||
for (const r of routes) {
|
||||
if (r.method !== method) continue;
|
||||
const params = matchPattern(r.pattern, path);
|
||||
if (params) return { params, def: r };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function parseQuery(url: string): Record<string, string> {
|
||||
const qs = url.split('?')[1] ?? '';
|
||||
const out: Record<string, string> = {};
|
||||
for (const [k, v] of new URLSearchParams(qs)) out[k] = v;
|
||||
return out;
|
||||
}
|
||||
|
||||
async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise<string | undefined> {
|
||||
const chunks: Buffer[] = [];
|
||||
let total = 0;
|
||||
for await (const chunk of req) {
|
||||
total += (chunk as Buffer).length;
|
||||
if (total > maxBodyBytes) throw new HttpError(413, 'Payload Too Large');
|
||||
chunks.push(chunk as Buffer);
|
||||
}
|
||||
if (chunks.length === 0) return undefined;
|
||||
const raw = Buffer.concat(chunks).toString('utf8');
|
||||
return raw === '' ? undefined : raw;
|
||||
}
|
||||
|
||||
function pickEncoder(transport: Transport, accept: string): StreamEncoder {
|
||||
if (transport === 'sse') return sseEncoder;
|
||||
if (transport === 'ndjson') return ndjsonEncoder;
|
||||
return accept.includes('text/event-stream') ? sseEncoder : ndjsonEncoder;
|
||||
}
|
||||
|
||||
async function pipeStream(
|
||||
res: http.ServerResponse, stream: AsyncIterable<unknown>, encoder: StreamEncoder,
|
||||
bus?: Bus, name = '', streams?: Set<() => void>,
|
||||
): Promise<void> {
|
||||
res.writeHead(200, encoder.headers);
|
||||
res.flushHeaders(); // establish the stream immediately so idle-until-event sources (e.g. subscriptions) don't deadlock clients awaiting headers
|
||||
bus?.emit('stream:open', { name });
|
||||
const it = stream[Symbol.asyncIterator]();
|
||||
let ping: ReturnType<typeof setInterval> | undefined;
|
||||
if (encoder.ping) { ping = setInterval(() => res.write(encoder.ping!()), PING_MS); ping.unref?.(); }
|
||||
const stop = () => { if (ping) clearInterval(ping); void Promise.resolve(it.return?.()).catch(() => {}); };
|
||||
res.on('close', stop);
|
||||
const closer = () => { try { res.destroy(); } catch { /* */ } };
|
||||
streams?.add(closer);
|
||||
const onClose = once(res, 'close');
|
||||
try {
|
||||
while (true) {
|
||||
const { value, done } = await it.next();
|
||||
if (done) break;
|
||||
if (!res.write(encoder.encode(value))) {
|
||||
await Promise.race([once(res, 'drain'), onClose]);
|
||||
if (res.destroyed) break; // let finally clean up
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
bus?.emit('stream:error', { name, error: err });
|
||||
const frame = encoder.encodeError(err);
|
||||
if (frame && !res.writableEnded) res.write(frame);
|
||||
} finally {
|
||||
if (ping) clearInterval(ping);
|
||||
streams?.delete(closer);
|
||||
if (!res.writableEnded && !res.destroyed) res.end();
|
||||
bus?.emit('stream:close', { name });
|
||||
}
|
||||
}
|
||||
|
||||
function loadWss(): any | null {
|
||||
try { return require('ws').WebSocketServer; } catch { return null; }
|
||||
}
|
||||
|
||||
function attachWs(
|
||||
server: http.Server, wsRoutes: WsRouteDef[], bus?: Bus, meshControl?: MeshControl, streams?: Set<() => void>,
|
||||
): void {
|
||||
if (wsRoutes.length === 0 && !meshControl) return;
|
||||
const WSS = loadWss();
|
||||
const wss = WSS ? new WSS({ noServer: true }) : null;
|
||||
server.on('upgrade', (req, socket, head) => {
|
||||
const path = (req.url ?? '/').split('?')[0];
|
||||
if (meshControl && path === meshControl.path) {
|
||||
if (!wss) { socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n'); socket.destroy(); return; }
|
||||
wss.handleUpgrade(req, socket, head, (ws: any) => meshControl.handle(ws, req));
|
||||
return;
|
||||
}
|
||||
const route = wsRoutes.map((r) => ({ r, params: matchPattern(r.pattern, path) })).find((x) => x.params);
|
||||
if (!route) { socket.destroy(); return; }
|
||||
if (!wss) { socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n'); socket.destroy(); return; }
|
||||
wss.handleUpgrade(req, socket, head, async (ws: any) => {
|
||||
const closer = () => { try { (ws.terminate ?? ws.close).call(ws); } catch { /* */ } };
|
||||
streams?.add(closer);
|
||||
ws.on('close', () => streams?.delete(closer));
|
||||
const inbound = channel<unknown>();
|
||||
const ac = new AbortController();
|
||||
ws.on('message', (d: Buffer) => inbound.push(d.toString()));
|
||||
ws.on('close', () => { inbound.close(); ac.abort(); });
|
||||
ws.on('error', (e: unknown) => inbound.fail(e));
|
||||
|
||||
const name = route.r.pattern;
|
||||
let it: AsyncIterator<unknown> | undefined;
|
||||
ws.on('close', () => { void Promise.resolve(it?.return?.()).catch(() => {}); }); // force-cancel outbound
|
||||
bus?.emit('stream:open', { name });
|
||||
try {
|
||||
const out = await route.r.open({ params: route.params!, inbound, abort: ac.signal, req });
|
||||
it = out[Symbol.asyncIterator]();
|
||||
while (true) {
|
||||
const { value, done } = await it.next();
|
||||
if (done) break;
|
||||
if (ws.readyState !== 1) break; // 1 = OPEN; stop if socket gone
|
||||
ws.send(typeof value === 'string' ? value : JSON.stringify(value));
|
||||
}
|
||||
try { ws.close(); } catch { /* already closed */ }
|
||||
} catch (err) {
|
||||
bus?.emit('stream:error', { name, error: err });
|
||||
if (isHttpError(err)) {
|
||||
const reason = Buffer.from(String(err.message)).subarray(0, 120).toString();
|
||||
try { ws.close(4000 + err.status, reason); } catch { /* already closed */ }
|
||||
} else {
|
||||
try { ws.close(1011); } catch { /* already closed */ }
|
||||
}
|
||||
} finally {
|
||||
ac.abort();
|
||||
bus?.emit('stream:close', { name });
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function createHttpServer(
|
||||
routes: RouteDef[], wsRoutes: WsRouteDef[] = [], bus?: Bus, meshControl?: MeshControl, opts?: HttpOptions,
|
||||
): http.Server {
|
||||
const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000;
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const url = req.url ?? '/';
|
||||
const path = url.split('?')[0];
|
||||
const matched = matchRoute(routes, req.method ?? 'GET', path);
|
||||
if (!matched) {
|
||||
res.writeHead(404, { 'content-type': 'application/json' });
|
||||
res.end(JSON.stringify({ error: 'Not Found' }));
|
||||
return;
|
||||
}
|
||||
let raw: string | undefined;
|
||||
try {
|
||||
raw = await readBody(req, maxBody);
|
||||
} catch (error) {
|
||||
const r = errorToResponse(error);
|
||||
res.writeHead(r.status, { ...r.headers, connection: 'close' });
|
||||
res.end(r.body);
|
||||
return;
|
||||
}
|
||||
let body: unknown = raw;
|
||||
const ct = String(req.headers['content-type'] ?? '');
|
||||
if (raw !== undefined && ct.includes('application/json')) {
|
||||
try { body = JSON.parse(raw); }
|
||||
catch {
|
||||
res.writeHead(400, { 'content-type': 'application/json' });
|
||||
res.end(JSON.stringify({ error: 'Invalid JSON body' }));
|
||||
return;
|
||||
}
|
||||
} else if (raw !== undefined && ct.includes('application/x-www-form-urlencoded')) {
|
||||
body = Object.fromEntries(new URLSearchParams(raw));
|
||||
}
|
||||
let result: PipelineResult;
|
||||
try {
|
||||
result = await matched.def.handler({
|
||||
method: req.method ?? 'GET', url, headers: req.headers,
|
||||
params: matched.params, query: parseQuery(url), body,
|
||||
});
|
||||
} catch (error) {
|
||||
result = errorToResponse(error);
|
||||
}
|
||||
if (isStreamResult(result)) {
|
||||
const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? ''));
|
||||
await pipeStream(res, result.stream, encoder, bus, matched.def.pattern, opts?.streams);
|
||||
return;
|
||||
}
|
||||
const r: ResponseShape = result;
|
||||
res.writeHead(r.status, r.headers);
|
||||
res.end(r.body);
|
||||
});
|
||||
server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000;
|
||||
server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000;
|
||||
server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000;
|
||||
attachWs(server, wsRoutes, bus, meshControl, opts?.streams);
|
||||
return server;
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
// src/http/core.ts — runtime-neutral request handling core, shared by the Node adapter and (later) app.fetch.
|
||||
import { HttpError, NotFound } from '../signals';
|
||||
import { renderError } from '../transformers';
|
||||
import { isStreamResult, type PipelineResult } from '../pipeline';
|
||||
import { buildSecurityHeaders, resolveCors, corsPreflightHeaders } from '../security';
|
||||
import { resolveRoute, allowedMethods, normalizeRequestPath, parseQuery } from './router';
|
||||
import { pickEncoder } from './stream';
|
||||
import type { RouteDef, HttpOptions } from './types';
|
||||
import type { StreamEncoder } from '../encoders';
|
||||
|
||||
/** A runtime-neutral inbound request: body already parsed by the caller's ingress (Node stream, fetch Request, …). */
|
||||
export interface NeutralRequest {
|
||||
method: string;
|
||||
url: string; // path + query, e.g. "/users/9?x=1"
|
||||
headers: Record<string, string | string[] | undefined>;
|
||||
body: unknown; // already-parsed body
|
||||
secure: boolean;
|
||||
ip: string;
|
||||
}
|
||||
|
||||
/** The neutral shape of a response: a fully buffered body, or a stream to pipe frame-by-frame. */
|
||||
export type NeutralOutcome =
|
||||
| { kind: 'buffered'; status: number; headers: Record<string, string>; body: string | Buffer }
|
||||
| { kind: 'stream'; headers: Record<string, string>; stream: AsyncIterable<unknown>; encoder: StreamEncoder };
|
||||
|
||||
/** {@link handle}'s result for a normal (non-preflight) request. */
|
||||
export interface HandleResult {
|
||||
injected: Record<string, string>;
|
||||
outcome: NeutralOutcome;
|
||||
}
|
||||
|
||||
/** {@link handle}'s result for a CORS preflight: the caller must answer with 204 + these headers. */
|
||||
export interface Preflight {
|
||||
preflight: Record<string, string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the security + CORS headers that get injected into every response for a request — the same
|
||||
* authoritative set {@link handle} applies to its outcomes. Shared with `buildFetch` (src/http/web.ts)
|
||||
* so early-failure responses (413/400/501, before a route even matches) carry the same headers Node's
|
||||
* `patchResponseHeaders` would have installed up-front.
|
||||
*/
|
||||
export function computeInjected(
|
||||
opts: HttpOptions | undefined,
|
||||
req: { secure: boolean; headers: Record<string, string | string[] | undefined> },
|
||||
): Record<string, string> {
|
||||
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, req.secure) };
|
||||
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req));
|
||||
return injected;
|
||||
}
|
||||
|
||||
function errorOutcome(
|
||||
error: unknown,
|
||||
req: NeutralRequest,
|
||||
injected: Record<string, string>,
|
||||
opts: HttpOptions | undefined,
|
||||
headers: Record<string, string> = {},
|
||||
): HandleResult {
|
||||
const rendered = renderError(error, { method: req.method, url: req.url, headers: req.headers }, opts?.onError);
|
||||
return {
|
||||
injected,
|
||||
outcome: {
|
||||
kind: 'buffered',
|
||||
status: rendered.status,
|
||||
headers: { ...rendered.headers, ...headers },
|
||||
body: req.method === 'HEAD' ? '' : rendered.body,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function unmatchedOutcome(
|
||||
routes: RouteDef[],
|
||||
opts: HttpOptions | undefined,
|
||||
req: NeutralRequest,
|
||||
path: string,
|
||||
injected: Record<string, string>,
|
||||
): Promise<HandleResult> {
|
||||
if ((req.method === 'GET' || req.method === 'HEAD') && opts?.static) {
|
||||
const hit = await opts.static(path);
|
||||
|
||||
if (hit) {
|
||||
return {
|
||||
injected,
|
||||
outcome: {
|
||||
kind: 'buffered',
|
||||
status: 200,
|
||||
headers: { 'content-type': hit.contentType },
|
||||
body: req.method === 'HEAD' ? '' : hit.body,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const allow = allowedMethods(routes, path);
|
||||
|
||||
if (req.method === 'OPTIONS' && allow.length) {
|
||||
return {
|
||||
injected,
|
||||
outcome: { kind: 'buffered', status: 204, headers: { allow: allow.join(', ') }, body: '' },
|
||||
};
|
||||
}
|
||||
|
||||
const error = allow.length ? new HttpError(405, 'Method Not Allowed') : new NotFound('Not Found');
|
||||
return errorOutcome(error, req, injected, opts, allow.length ? { allow: allow.join(', ') } : {});
|
||||
}
|
||||
|
||||
/**
|
||||
* Runtime-neutral request handler: security/CORS headers, preflight short-circuit, route match / 404 / 405,
|
||||
* route-handler invocation with error rendering, and the buffered-vs-stream decision. Does no I/O — the
|
||||
* caller (a Node adapter, a fetch adapter, …) reads/writes the actual request/response.
|
||||
*/
|
||||
export async function handle(
|
||||
routes: RouteDef[],
|
||||
opts: HttpOptions | undefined,
|
||||
req: NeutralRequest,
|
||||
): Promise<HandleResult | Preflight> {
|
||||
const injected = computeInjected(opts, req);
|
||||
let path: string;
|
||||
|
||||
try {
|
||||
path = normalizeRequestPath(req.url.split('?')[0]);
|
||||
} catch {
|
||||
return errorOutcome(new HttpError(400, 'Bad Request'), req, injected, opts);
|
||||
}
|
||||
|
||||
if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) {
|
||||
return { preflight: corsPreflightHeaders(opts.cors, req) };
|
||||
}
|
||||
|
||||
const matched = resolveRoute(routes, req.method, path);
|
||||
|
||||
if (!matched) return unmatchedOutcome(routes, opts, req, path, injected);
|
||||
|
||||
let result: PipelineResult;
|
||||
|
||||
try {
|
||||
result = await matched.def.handler({
|
||||
method: req.method,
|
||||
url: req.url,
|
||||
headers: req.headers,
|
||||
params: matched.params,
|
||||
query: parseQuery(req.url),
|
||||
body: req.body,
|
||||
protocol: req.secure ? 'https' : 'http',
|
||||
ip: req.ip,
|
||||
});
|
||||
} catch (error) {
|
||||
result = renderError(error, { method: req.method, url: req.url, headers: req.headers }, opts?.onError);
|
||||
}
|
||||
|
||||
if (isStreamResult(result)) {
|
||||
const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? ''));
|
||||
return { injected, outcome: { kind: 'stream', headers: encoder.headers, stream: result.stream, encoder } };
|
||||
}
|
||||
|
||||
return {
|
||||
injected,
|
||||
outcome: {
|
||||
kind: 'buffered',
|
||||
status: result.status,
|
||||
headers: result.headers,
|
||||
body: req.method === 'HEAD' ? '' : result.body,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { mergeVary } from '../security';
|
||||
|
||||
/**
|
||||
* Merges a handler's response headers with authoritative `injected` headers
|
||||
* (security + CORS). Injected keys win case-insensitively; `vary` is merged.
|
||||
* Extracted from the Node writeHead patch so app.fetch shares the exact logic.
|
||||
*/
|
||||
export function mergeInjectedHeaders(
|
||||
handlerHeaders: Record<string, any> | undefined,
|
||||
injected: Record<string, string>,
|
||||
): Record<string, any> {
|
||||
const merged: Record<string, any> = {};
|
||||
const injectedLower = new Set(Object.keys(injected).map((key) => key.toLowerCase()));
|
||||
let handlerVary: string | undefined;
|
||||
|
||||
if (handlerHeaders)
|
||||
for (const key of Object.keys(handlerHeaders)) {
|
||||
const lowerKey = key.toLowerCase();
|
||||
|
||||
if (lowerKey === 'vary') {
|
||||
handlerVary = handlerHeaders[key];
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!injectedLower.has(lowerKey)) merged[key] = handlerHeaders[key];
|
||||
}
|
||||
|
||||
Object.assign(merged, injected);
|
||||
if (injected['vary']) merged['vary'] = mergeVary(handlerVary, injected['vary']);
|
||||
else if (handlerVary !== undefined) merged['vary'] = handlerVary;
|
||||
return merged;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Public surface of the HTTP module. Internal helpers (request parsing, streaming,
|
||||
// ws upgrade) live in sibling files and are composed by ./server.
|
||||
export type {
|
||||
RequestLimits,
|
||||
HttpOptions,
|
||||
RouteHandler,
|
||||
RouteDef,
|
||||
MatchedRoute,
|
||||
WsOpenCtx,
|
||||
WsRouteDef,
|
||||
MeshControl,
|
||||
} from './types';
|
||||
export { matchPattern, matchRoute, parseQuery } from './router';
|
||||
export { createHttpServer } from './server';
|
||||
@@ -0,0 +1,42 @@
|
||||
import type http from 'http';
|
||||
import { HttpError } from '../signals';
|
||||
|
||||
/** Reads the full request body, enforcing the max-bytes ceiling (throws 413 if exceeded). */
|
||||
export async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise<Buffer | undefined> {
|
||||
const chunks: Buffer[] = [];
|
||||
let total = 0;
|
||||
|
||||
for await (const chunk of req) {
|
||||
total += (chunk as Buffer).length;
|
||||
if (total > maxBodyBytes) throw new HttpError(413, 'Payload Too Large');
|
||||
chunks.push(chunk as Buffer);
|
||||
}
|
||||
|
||||
return chunks.length === 0 ? undefined : Buffer.concat(chunks);
|
||||
}
|
||||
|
||||
/** Returns the first comma-separated token of a header value (handles array-valued headers). */
|
||||
function firstToken(value: string | string[] | undefined): string | undefined {
|
||||
const first = Array.isArray(value) ? value[0] : value;
|
||||
return first?.split(',')[0].trim();
|
||||
}
|
||||
|
||||
/** Determines whether the request arrived over HTTPS, honoring `x-forwarded-proto` when proxy is trusted. */
|
||||
export function deriveSecure(req: http.IncomingMessage, trustProxy: boolean): boolean {
|
||||
if (trustProxy) {
|
||||
const proto = firstToken(req.headers['x-forwarded-proto']);
|
||||
if (proto) return proto === 'https';
|
||||
}
|
||||
|
||||
return (req.socket as any).encrypted === true;
|
||||
}
|
||||
|
||||
/** Resolves the client IP, honoring `x-forwarded-for` when proxy is trusted. */
|
||||
export function deriveIp(req: http.IncomingMessage, trustProxy: boolean): string {
|
||||
if (trustProxy) {
|
||||
const forwarded = firstToken(req.headers['x-forwarded-for']);
|
||||
if (forwarded) return forwarded;
|
||||
}
|
||||
|
||||
return req.socket.remoteAddress ?? '';
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
import type { RouteDef, MatchedRoute } from './types';
|
||||
|
||||
export type CompiledSegment =
|
||||
| { kind: 'static'; value: string }
|
||||
| { kind: 'param'; name: string; constraint?: RegExp; constraintSource?: string }
|
||||
| { kind: 'catchAll'; name: string };
|
||||
|
||||
/** Parsed route pattern reused by matching, specificity, ambiguity checks, and OpenAPI projection. */
|
||||
export interface CompiledPattern {
|
||||
source: string;
|
||||
normalized: string;
|
||||
shape: string;
|
||||
segments: CompiledSegment[];
|
||||
kinds: number[];
|
||||
catchAll: boolean;
|
||||
}
|
||||
|
||||
const compiledCache = new Map<string, CompiledPattern>();
|
||||
const PARAM_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
||||
const MAX_CONSTRAINT_LENGTH = 128;
|
||||
|
||||
/** Request-path syntax error. Adapters translate this to the standard 400 response envelope. */
|
||||
export class InvalidRequestPathError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'InvalidRequestPathError';
|
||||
}
|
||||
}
|
||||
|
||||
interface ConstraintToken {
|
||||
length: number;
|
||||
unbounded: boolean;
|
||||
separator: boolean;
|
||||
}
|
||||
|
||||
/** Reads one atom plus its optional quantifier from the deliberately small safe-regex subset. */
|
||||
function readConstraintToken(source: string): ConstraintToken | undefined {
|
||||
const atom = /^(?:\\[dDsSwW]|\\[.\-_/]|[A-Za-z0-9_.-]|\[(?:\\.|[^\]\\])+\])/u.exec(source)?.[0];
|
||||
if (!atom) return undefined;
|
||||
|
||||
const rest = source.slice(atom.length);
|
||||
const quantifier = /^(?:[+*?]|\{\d+(?:,\d*)?\})/u.exec(rest)?.[0] ?? '';
|
||||
if (quantifier.startsWith('{')) assertBoundedQuantifier(quantifier);
|
||||
|
||||
return {
|
||||
length: atom.length + quantifier.length,
|
||||
unbounded: quantifier === '+' || quantifier === '*' || quantifier.endsWith(',}'),
|
||||
separator: quantifier === '' && /^(?:\\[.\-_/]|[._-])$/u.test(atom),
|
||||
};
|
||||
}
|
||||
|
||||
/** Rejects nonsensical or excessively large counted quantifiers before RegExp compilation. */
|
||||
function assertBoundedQuantifier(quantifier: string): void {
|
||||
const [minText, maxText] = quantifier.slice(1, -1).split(',');
|
||||
const min = Number(minText);
|
||||
const max = maxText === undefined || maxText === '' ? min : Number(maxText);
|
||||
if (min > max || max > 2048) throw new Error(`unsafe route constraint: invalid quantifier '${quantifier}'`);
|
||||
}
|
||||
|
||||
/** Accepts only a linear, group-free regex subset to keep attacker-controlled segments ReDoS-safe. */
|
||||
function assertSafeConstraint(source: string): void {
|
||||
if (!source || source.length > MAX_CONSTRAINT_LENGTH)
|
||||
throw new Error('unsafe route constraint: expression must contain 1-128 characters');
|
||||
|
||||
let offset = 0;
|
||||
let previousUnbounded = false;
|
||||
|
||||
while (offset < source.length) {
|
||||
const token = readConstraintToken(source.slice(offset));
|
||||
if (!token) throw new Error(`unsafe route constraint: unsupported expression '${source}'`);
|
||||
if (previousUnbounded && token.unbounded)
|
||||
throw new Error(`unsafe route constraint: adjacent unbounded quantifiers in '${source}'`);
|
||||
previousUnbounded = token.separator ? false : token.unbounded;
|
||||
offset += token.length;
|
||||
}
|
||||
}
|
||||
|
||||
function assertParamName(name: string, pattern: string): void {
|
||||
if (!PARAM_NAME.test(name)) throw new Error(`invalid route pattern '${pattern}': invalid parameter name '${name}'`);
|
||||
}
|
||||
|
||||
function compileParam(segment: string, pattern: string): Extract<CompiledSegment, { kind: 'param' }> {
|
||||
const constraintStart = segment.indexOf('(');
|
||||
|
||||
if (constraintStart < 0) {
|
||||
const name = segment.slice(1);
|
||||
assertParamName(name, pattern);
|
||||
return { kind: 'param', name };
|
||||
}
|
||||
|
||||
if (!segment.endsWith(')')) throw new Error(`invalid route pattern '${pattern}': malformed constraint`);
|
||||
const name = segment.slice(1, constraintStart);
|
||||
const constraintSource = segment.slice(constraintStart + 1, -1);
|
||||
assertParamName(name, pattern);
|
||||
assertSafeConstraint(constraintSource);
|
||||
return {
|
||||
kind: 'param',
|
||||
name,
|
||||
constraintSource,
|
||||
constraint: new RegExp(`^(?:${constraintSource})$`, 'u'),
|
||||
};
|
||||
}
|
||||
|
||||
function compileSegments(pattern: string, rawSegments: string[]): CompiledSegment[] {
|
||||
const names = new Set<string>();
|
||||
const compiled: CompiledSegment[] = [];
|
||||
|
||||
for (let index = 0; index < rawSegments.length; index++) {
|
||||
const raw = rawSegments[index];
|
||||
let segment: CompiledSegment;
|
||||
|
||||
if (raw.startsWith(':') && raw.endsWith('*')) {
|
||||
const name = raw.slice(1, -1);
|
||||
assertParamName(name, pattern);
|
||||
if (index !== rawSegments.length - 1)
|
||||
throw new Error(`invalid route pattern '${pattern}': catch-all must be the final segment`);
|
||||
segment = { kind: 'catchAll', name };
|
||||
} else if (raw.startsWith(':')) {
|
||||
segment = compileParam(raw, pattern);
|
||||
} else {
|
||||
segment = { kind: 'static', value: raw };
|
||||
}
|
||||
|
||||
if (segment.kind !== 'static') {
|
||||
if (names.has(segment.name))
|
||||
throw new Error(`invalid route pattern '${pattern}': duplicate parameter '${segment.name}'`);
|
||||
names.add(segment.name);
|
||||
}
|
||||
|
||||
compiled.push(segment);
|
||||
}
|
||||
|
||||
return compiled;
|
||||
}
|
||||
|
||||
function segmentShape(segment: CompiledSegment): string {
|
||||
if (segment.kind === 'static') return `s:${segment.value}`;
|
||||
if (segment.kind === 'catchAll') return 'c';
|
||||
return segment.constraintSource ? `r:${segment.constraintSource}` : 'p';
|
||||
}
|
||||
|
||||
/** Compiles and validates one route pattern. Results are cached by source string. */
|
||||
export function compilePattern(pattern: string): CompiledPattern {
|
||||
const cached = compiledCache.get(pattern);
|
||||
if (cached) return cached;
|
||||
if (!pattern.startsWith('/')) throw new Error(`invalid route pattern '${pattern}': pattern must start with '/'`);
|
||||
if (pattern.includes('//')) throw new Error(`invalid route pattern '${pattern}': repeated slash`);
|
||||
|
||||
const normalized = pattern.length > 1 && pattern.endsWith('/') ? pattern.slice(0, -1) : pattern;
|
||||
const rawSegments = normalized === '/' ? [] : normalized.split('/').slice(1);
|
||||
const segments = compileSegments(pattern, rawSegments);
|
||||
const compiled: CompiledPattern = {
|
||||
source: pattern,
|
||||
normalized,
|
||||
shape: segments.map(segmentShape).join('/'),
|
||||
segments,
|
||||
kinds: segments
|
||||
.filter((segment) => segment.kind !== 'catchAll')
|
||||
.map((segment) => (segment.kind === 'static' ? 3 : segment.constraint ? 2 : 1)),
|
||||
catchAll: segments.at(-1)?.kind === 'catchAll',
|
||||
};
|
||||
compiledCache.set(pattern, compiled);
|
||||
return compiled;
|
||||
}
|
||||
|
||||
/** Applies the public trailing-slash policy and validates every segment's percent encoding. */
|
||||
export function normalizeRequestPath(path: string): string {
|
||||
if (!path.startsWith('/')) throw new InvalidRequestPathError('invalid request path: path must start with slash');
|
||||
if (path.includes('//')) throw new InvalidRequestPathError('invalid request path: repeated slash');
|
||||
const normalized = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;
|
||||
|
||||
try {
|
||||
for (const segment of normalized.split('/').slice(1)) decodeURIComponent(segment);
|
||||
} catch {
|
||||
throw new InvalidRequestPathError('invalid request path: malformed path encoding');
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function decodeSegment(value: string): string {
|
||||
return decodeURIComponent(value);
|
||||
}
|
||||
|
||||
function matchCompiled(compiled: CompiledPattern, path: string): Record<string, string> | undefined {
|
||||
const pathSegs = path.split('/').filter(Boolean);
|
||||
const params: Record<string, string> = {};
|
||||
|
||||
for (let index = 0; index < compiled.segments.length; index++) {
|
||||
const segment = compiled.segments[index];
|
||||
|
||||
if (segment.kind === 'catchAll') {
|
||||
params[segment.name] = pathSegs.slice(index).map(decodeSegment).join('/');
|
||||
return params;
|
||||
}
|
||||
|
||||
if (index >= pathSegs.length) return undefined;
|
||||
|
||||
if (segment.kind === 'static') {
|
||||
if (segment.value !== pathSegs[index]) return undefined;
|
||||
continue;
|
||||
}
|
||||
|
||||
const value = decodeSegment(pathSegs[index]);
|
||||
if (segment.constraint && !segment.constraint.test(value)) return undefined;
|
||||
params[segment.name] = value;
|
||||
}
|
||||
|
||||
return compiled.segments.length === pathSegs.length ? params : undefined;
|
||||
}
|
||||
|
||||
/** Matches a compiled segment pattern and returns its decoded parameters. */
|
||||
export function matchPattern(pattern: string, path: string): Record<string, string> | undefined {
|
||||
return matchCompiled(compilePattern(pattern), path);
|
||||
}
|
||||
|
||||
/** Orders matching patterns by exactness, then static/constrained/plain segment specificity. */
|
||||
function moreSpecific(a: string, b: string): number {
|
||||
const scoreA = compilePattern(a);
|
||||
const scoreB = compilePattern(b);
|
||||
if (scoreA.catchAll !== scoreB.catchAll) return scoreA.catchAll ? -1 : 1;
|
||||
const length = Math.max(scoreA.kinds.length, scoreB.kinds.length);
|
||||
|
||||
for (let index = 0; index < length; index++) {
|
||||
const kindA = scoreA.kinds[index] ?? -1;
|
||||
const kindB = scoreB.kinds[index] ?? -1;
|
||||
if (kindA !== kindB) return kindA - kindB;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** Finds the most specific route matching both method and path; ties keep registration order. */
|
||||
export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined {
|
||||
let best: MatchedRoute | undefined;
|
||||
let bestPattern = '';
|
||||
|
||||
for (const route of routes) {
|
||||
if (route.method !== method) continue;
|
||||
const params = matchPattern(route.pattern, path);
|
||||
if (!params) continue;
|
||||
|
||||
if (!best || moreSpecific(route.pattern, bestPattern) > 0) {
|
||||
best = { params, def: route };
|
||||
bestPattern = route.pattern;
|
||||
}
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
/** Route resolution adds the one HTTP fallback the matcher supports: buffered GET serves HEAD. */
|
||||
export interface ResolvedRoute extends MatchedRoute {
|
||||
implicitHead: boolean;
|
||||
}
|
||||
|
||||
export function resolveRoute(routes: RouteDef[], method: string, path: string): ResolvedRoute | undefined {
|
||||
const explicit = matchRoute(routes, method, path);
|
||||
if (explicit) return { ...explicit, implicitHead: false };
|
||||
if (method !== 'HEAD') return undefined;
|
||||
|
||||
const fallback = matchRoute(
|
||||
routes.filter((route) => route.transport === 'buffer'),
|
||||
'GET',
|
||||
path,
|
||||
);
|
||||
return fallback ? { ...fallback, implicitHead: true } : undefined;
|
||||
}
|
||||
|
||||
const METHOD_ORDER = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
|
||||
|
||||
/** Lists the distinct HTTP methods whose pattern matches the path — used to build a 405 `Allow` header. */
|
||||
export function allowedMethods(routes: RouteDef[], path: string): string[] {
|
||||
const methods = new Set<string>();
|
||||
|
||||
for (const route of routes) {
|
||||
if (!matchPattern(route.pattern, path)) continue;
|
||||
methods.add(route.method);
|
||||
if (route.method === 'GET' && route.transport === 'buffer') methods.add('HEAD');
|
||||
}
|
||||
|
||||
if (methods.size) methods.add('OPTIONS');
|
||||
return [...methods].sort((a, b) => {
|
||||
const indexA = METHOD_ORDER.indexOf(a);
|
||||
const indexB = METHOD_ORDER.indexOf(b);
|
||||
return (
|
||||
(indexA < 0 ? METHOD_ORDER.length : indexA) - (indexB < 0 ? METHOD_ORDER.length : indexB) || a.localeCompare(b)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/** Parses a URL's query string into a flat string map (last value wins for repeated keys). */
|
||||
export function parseQuery(url: string): Record<string, string> {
|
||||
const queryString = url.split('?')[1] ?? '';
|
||||
const out: Record<string, string> = {};
|
||||
for (const [key, value] of new URLSearchParams(queryString)) out[key] = value;
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
import type http from 'http';
|
||||
import type https from 'https';
|
||||
import { renderError, type ErrorRequest } from '../transformers';
|
||||
import { isHttpError, HttpError } from '../signals';
|
||||
import type { Bus } from '../bus';
|
||||
import { buildSecurityHeaders, resolveCors } from '../security';
|
||||
import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart';
|
||||
import { normalizeRequestPath, resolveRoute } from './router';
|
||||
import { readBody, deriveSecure, deriveIp } from './request';
|
||||
import { pipeStream } from './stream';
|
||||
import { attachWs } from './ws';
|
||||
import { mergeInjectedHeaders } from './headers';
|
||||
import { handle } from './core';
|
||||
import type { RouteDef, WsRouteDef, MatchedRoute, MeshControl, HttpOptions } from './types';
|
||||
|
||||
interface HandlerConfig {
|
||||
routes: RouteDef[];
|
||||
bus?: Bus;
|
||||
opts?: HttpOptions;
|
||||
maxBody: number;
|
||||
trustProxy: boolean;
|
||||
}
|
||||
|
||||
/** A ready-to-send error response produced while acquiring the request body. */
|
||||
type BodyFailure = { fail: { status: number; headers: Record<string, string>; body: string } };
|
||||
|
||||
/** Builds the {@link ErrorRequest} handed to a user error renderer. */
|
||||
function errorRequest(req: http.IncomingMessage): ErrorRequest {
|
||||
return { method: req.method ?? 'GET', url: req.url ?? '/', headers: req.headers };
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds an HTTP/HTTPS server that routes requests, parses bodies, streams results, and handles WebSocket upgrades.
|
||||
* @param routes HTTP route definitions.
|
||||
* @param wsRoutes WebSocket route definitions (requires the optional `ws` peer dependency).
|
||||
* @param bus Optional event bus for stream lifecycle events.
|
||||
* @param meshControl Optional mesh gateway hook for a reserved upgrade path.
|
||||
* @param opts Limits, TLS, security, CORS, and body-parsing options.
|
||||
*/
|
||||
export function createHttpServer(
|
||||
routes: RouteDef[],
|
||||
wsRoutes: WsRouteDef[] = [],
|
||||
bus?: Bus,
|
||||
meshControl?: MeshControl,
|
||||
opts?: HttpOptions,
|
||||
): http.Server {
|
||||
const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000;
|
||||
const trustProxy = opts?.trustProxy ?? false;
|
||||
const handler = createRequestHandler({ routes, bus, opts, maxBody, trustProxy });
|
||||
|
||||
// Node http/https are loaded lazily so importing createApp stays edge/workerd-safe
|
||||
// (workerd's nodejs_compat provides no node:http/node:https). This path only runs under listen().
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const nodeHttp = require('http') as typeof import('http');
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const nodeHttps = require('https') as typeof import('https');
|
||||
|
||||
// runtime-compatible; only @types differ (https.Server lacks the http-only timeout props)
|
||||
const server: http.Server = (opts?.tls
|
||||
? nodeHttps.createServer(opts.tls as https.ServerOptions, handler)
|
||||
: nodeHttp.createServer(handler)) as unknown as http.Server;
|
||||
server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000;
|
||||
server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000;
|
||||
server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000;
|
||||
attachWs(server, wsRoutes, bus, meshControl, opts?.streams);
|
||||
return server;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the request listener: a thin Node adapter around the runtime-neutral {@link handle} core.
|
||||
* Reads the body (Node-specific), delegates security/CORS/routing/error-rendering to `handle()`,
|
||||
* then writes the result to `res` (buffered or streamed). The security-header monkeypatch is
|
||||
* installed here — and stays the single source of truth for merging headers into every response —
|
||||
* so `handle()`'s own `injected` is intentionally unused by this adapter.
|
||||
*/
|
||||
function createRequestHandler(cfg: HandlerConfig) {
|
||||
const { routes, bus, opts, maxBody, trustProxy } = cfg;
|
||||
|
||||
return async (req: http.IncomingMessage, res: http.ServerResponse): Promise<void> => {
|
||||
const url = req.url ?? '/';
|
||||
const path = url.split('?')[0];
|
||||
const method = req.method ?? 'GET';
|
||||
// Install the security-header patch BEFORE any routing/response so every path
|
||||
// (200, 404, error, stream) writes headers through the same patched writeHead.
|
||||
const secure = deriveSecure(req, trustProxy);
|
||||
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, secure) };
|
||||
patchResponseHeaders(res, injected);
|
||||
|
||||
// CORS is added to `injected` AFTER the patch is installed — the patch reads it lazily
|
||||
// by reference at writeHead time, so keys added here still land on every response.
|
||||
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req));
|
||||
|
||||
// Mirror handle()'s own preflight/route-match decision here, so we only read the body
|
||||
// (below) for a request that actually reaches a route handler — matching prior behaviour.
|
||||
const isPreflight = Boolean(opts?.cors && method === 'OPTIONS' && req.headers['access-control-request-method']);
|
||||
let matched: ReturnType<typeof resolveRoute>;
|
||||
|
||||
try {
|
||||
matched = isPreflight ? undefined : resolveRoute(routes, method, normalizeRequestPath(path));
|
||||
} catch {
|
||||
matched = undefined; // handle() owns the standard 400 envelope and injected headers
|
||||
}
|
||||
|
||||
let body: unknown;
|
||||
|
||||
if (matched) {
|
||||
const acquired = await acquireBody(req, matched, opts, maxBody);
|
||||
|
||||
if ('fail' in acquired) {
|
||||
res.writeHead(acquired.fail.status, acquired.fail.headers);
|
||||
res.end(acquired.fail.body);
|
||||
return;
|
||||
}
|
||||
|
||||
body = acquired.body;
|
||||
}
|
||||
|
||||
const result = await handle(routes, opts, {
|
||||
method,
|
||||
url,
|
||||
headers: req.headers,
|
||||
body,
|
||||
secure,
|
||||
ip: deriveIp(req, trustProxy),
|
||||
});
|
||||
|
||||
if ('preflight' in result) {
|
||||
res.writeHead(204, result.preflight);
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.outcome.kind === 'stream') {
|
||||
await pipeStream(res, result.outcome.stream, result.outcome.encoder, bus, matched?.def.pattern, opts?.streams);
|
||||
return;
|
||||
}
|
||||
|
||||
res.writeHead(result.outcome.status, result.outcome.headers);
|
||||
res.end(result.outcome.body);
|
||||
};
|
||||
}
|
||||
|
||||
/** Reads and parses the request body, returning `{ body }` or a ready-to-send `{ fail }` error response. */
|
||||
async function acquireBody(
|
||||
req: http.IncomingMessage,
|
||||
matched: MatchedRoute,
|
||||
opts: HttpOptions | undefined,
|
||||
maxBody: number,
|
||||
): Promise<{ body: unknown } | BodyFailure> {
|
||||
let buf: Buffer | undefined;
|
||||
const bodyLimit = matched.def.maxBodyBytes ?? maxBody; // per-route override falls back to the server default
|
||||
|
||||
try {
|
||||
buf = await readBody(req, bodyLimit);
|
||||
} catch (error) {
|
||||
const rendered = renderError(error, errorRequest(req), opts?.onError);
|
||||
return { fail: { ...rendered, headers: { ...rendered.headers, connection: 'close' } } };
|
||||
}
|
||||
|
||||
const contentType = String(req.headers['content-type'] ?? '');
|
||||
const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last';
|
||||
const maxParts = matched.def.maxParts ?? opts?.limits?.maxParts ?? 1000;
|
||||
const parsed = await parseRequestBody(buf, contentType, duplicates, maxParts);
|
||||
|
||||
if ('error' in parsed) {
|
||||
const rendered = renderError(new HttpError(parsed.status ?? 400, parsed.error), errorRequest(req), opts?.onError);
|
||||
return { fail: rendered };
|
||||
}
|
||||
|
||||
return { body: parsed.body };
|
||||
}
|
||||
|
||||
/**
|
||||
* Monkey-patches `res.writeHead` so injected (security/CORS) headers are authoritative on every response.
|
||||
* Handler headers that case-insensitively collide with an injected key are dropped; `Vary` is merged.
|
||||
* Reads `injected` by reference, so CORS keys added after installation still land.
|
||||
*/
|
||||
function patchResponseHeaders(res: http.ServerResponse, injected: Record<string, string>): void {
|
||||
const origWriteHead = res.writeHead.bind(res);
|
||||
|
||||
(res as any).writeHead = (status: number, arg2?: any, arg3?: any) => {
|
||||
const handlerHeaders = (typeof arg2 === 'string' ? arg3 : arg2) as Record<string, any> | undefined;
|
||||
const merged = mergeInjectedHeaders(handlerHeaders, injected);
|
||||
return typeof arg2 === 'string' ? origWriteHead(status, arg2, merged) : origWriteHead(status, merged);
|
||||
};
|
||||
}
|
||||
|
||||
/** Parse outcome: the decoded body, or an error message plus the status to send (400 unless set). */
|
||||
type ParseResult = { body: unknown } | { error: string; status?: number };
|
||||
|
||||
/**
|
||||
* Parses a raw request body by content type (JSON, urlencoded, multipart, or plain text).
|
||||
* @returns `{ body }` on success, or `{ error, status? }` on malformed input / missing multipart support.
|
||||
*/
|
||||
export async function parseRequestBody(
|
||||
buf: Buffer | undefined,
|
||||
contentType: string,
|
||||
duplicates: 'array' | 'last',
|
||||
maxParts: number,
|
||||
): Promise<ParseResult> {
|
||||
if (buf !== undefined && contentType.includes('application/json')) {
|
||||
try {
|
||||
return { body: JSON.parse(buf.toString('utf8')) };
|
||||
} catch {
|
||||
return { error: 'Invalid JSON body' };
|
||||
}
|
||||
}
|
||||
|
||||
if (buf !== undefined && contentType.includes('application/x-www-form-urlencoded')) {
|
||||
return { body: collapseDuplicates(new URLSearchParams(buf.toString('utf8')), duplicates) };
|
||||
}
|
||||
|
||||
if (buf !== undefined && contentType.includes('multipart/form-data')) {
|
||||
const boundary = extractBoundary(contentType);
|
||||
if (!boundary) return { error: 'Invalid multipart body' };
|
||||
|
||||
try {
|
||||
return { body: await parseMultipart(buf, boundary, { maxParts, duplicates }) };
|
||||
} catch (error) {
|
||||
// HttpError = the busboy peer dep is missing (501); anything else = malformed input (400).
|
||||
if (isHttpError(error)) return { error: error.message, status: error.status };
|
||||
return { error: 'Invalid multipart body' };
|
||||
}
|
||||
}
|
||||
|
||||
const text = buf?.toString('utf8');
|
||||
return { body: text === '' ? undefined : text };
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import type http from 'http';
|
||||
import { once } from 'events';
|
||||
import { sseEncoder, ndjsonEncoder, StreamEncoder } from '../encoders';
|
||||
import type { Transport } from '../metadata';
|
||||
import type { Bus } from '../bus';
|
||||
|
||||
const PING_MS = 15_000;
|
||||
|
||||
/**
|
||||
* Stream encoder per transport, or `null` for transports that never produce an HTTP stream.
|
||||
* A new transport must add a row — the compiler fails until it does, so it can't silently
|
||||
* inherit ndjson framing.
|
||||
*/
|
||||
const STREAM_ENCODERS: Record<Transport, ((accept: string) => StreamEncoder) | null> = {
|
||||
buffer: null, // a buffered handler returning a stream throws TransportMismatchError before reaching here
|
||||
ws: null, // not an HTTP response; ws routes are served via upgrade, not handle()
|
||||
sse: () => sseEncoder,
|
||||
ndjson: () => ndjsonEncoder,
|
||||
negotiate: (accept) => (accept.includes('text/event-stream') ? sseEncoder : ndjsonEncoder),
|
||||
};
|
||||
|
||||
/** Selects the stream encoder for a transport, falling back to the client's `Accept` header for `negotiate`. */
|
||||
export function pickEncoder(transport: Transport, accept: string): StreamEncoder {
|
||||
const pick = STREAM_ENCODERS[transport];
|
||||
if (!pick) throw new Error(`transport '${transport}' does not produce an HTTP stream`);
|
||||
|
||||
return pick(accept);
|
||||
}
|
||||
|
||||
/** Pipes an async-iterable result to the response as an HTTP stream, with keep-alive pings and backpressure handling. */
|
||||
export async function pipeStream(
|
||||
res: http.ServerResponse,
|
||||
stream: AsyncIterable<unknown>,
|
||||
encoder: StreamEncoder,
|
||||
bus?: Bus,
|
||||
name = '',
|
||||
streams?: Set<() => void>,
|
||||
): Promise<void> {
|
||||
res.writeHead(200, encoder.headers);
|
||||
res.flushHeaders(); // establish the stream immediately so idle-until-event sources (e.g. subscriptions) don't deadlock clients awaiting headers
|
||||
bus?.emit('stream:open', { name });
|
||||
const iterator = stream[Symbol.asyncIterator]();
|
||||
let ping: ReturnType<typeof setInterval> | undefined;
|
||||
|
||||
if (encoder.ping) {
|
||||
ping = setInterval(() => res.write(encoder.ping!()), PING_MS);
|
||||
ping.unref?.();
|
||||
}
|
||||
|
||||
const stop = () => {
|
||||
if (ping) clearInterval(ping);
|
||||
void Promise.resolve(iterator.return?.()).catch(() => {});
|
||||
};
|
||||
|
||||
res.on('close', stop);
|
||||
|
||||
const closer = () => {
|
||||
try {
|
||||
res.destroy();
|
||||
} catch {
|
||||
/* */
|
||||
}
|
||||
};
|
||||
|
||||
streams?.add(closer);
|
||||
const onClose = once(res, 'close');
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const { value, done } = await iterator.next();
|
||||
if (done) break;
|
||||
|
||||
if (!res.write(encoder.encode(value))) {
|
||||
await Promise.race([once(res, 'drain'), onClose]);
|
||||
if (res.destroyed) break; // let finally clean up
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
bus?.emit('stream:error', { name, error: err });
|
||||
const frame = encoder.encodeError(err);
|
||||
if (frame && !res.writableEnded) res.write(frame);
|
||||
} finally {
|
||||
if (ping) clearInterval(ping);
|
||||
streams?.delete(closer);
|
||||
if (!res.writableEnded && !res.destroyed) res.end();
|
||||
bus?.emit('stream:close', { name });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import type { Transport } from '../metadata';
|
||||
import type { PipelineResult } from '../pipeline';
|
||||
import type { ErrorRenderer } from '../transformers';
|
||||
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
|
||||
import type { WsRequest, WsSocket } from './ws-core';
|
||||
import type { StaticResolver } from '../views';
|
||||
|
||||
/** Per-request size and timeout ceilings applied by the server. */
|
||||
export interface RequestLimits {
|
||||
maxBodyBytes?: number; // default 1_000_000
|
||||
requestTimeoutMs?: number; // default 30_000
|
||||
headersTimeoutMs?: number; // default 10_000
|
||||
keepAliveTimeoutMs?: number; // default 5_000
|
||||
maxParts?: number; // default 1000
|
||||
}
|
||||
|
||||
/** Options controlling server construction: limits, TLS, proxy trust, security headers, CORS, and body parsing. */
|
||||
export interface HttpOptions {
|
||||
limits?: RequestLimits;
|
||||
streams?: Set<() => void>;
|
||||
tls?: TlsOptions;
|
||||
trustProxy?: boolean;
|
||||
security?: boolean | SecurityOptions;
|
||||
cors?: CorsOptions;
|
||||
bodyDuplicates?: 'array' | 'last';
|
||||
onError?: ErrorRenderer;
|
||||
static?: StaticResolver;
|
||||
}
|
||||
|
||||
/** Handler for a matched HTTP route; receives a normalized request and resolves to a pipeline result. */
|
||||
export type RouteHandler = (req: {
|
||||
method: string;
|
||||
url: string;
|
||||
headers: Record<string, string | string[] | undefined>;
|
||||
params: Record<string, string>;
|
||||
query: Record<string, string>;
|
||||
body: unknown;
|
||||
protocol: 'http' | 'https';
|
||||
ip: string;
|
||||
}) => Promise<PipelineResult>;
|
||||
|
||||
/** A registered HTTP route: method, path pattern, streaming transport, and handler. */
|
||||
export interface RouteDef {
|
||||
method: string;
|
||||
pattern: string;
|
||||
transport: Transport;
|
||||
handler: RouteHandler;
|
||||
bodyDuplicates?: 'array' | 'last';
|
||||
maxBodyBytes?: number; // per-route override of the server's maxBodyBytes
|
||||
maxParts?: number; // per-route override of the server's multipart maxParts
|
||||
}
|
||||
|
||||
/** Result of matching a request path against a route: extracted params plus the matched definition. */
|
||||
export interface MatchedRoute {
|
||||
params: Record<string, string>;
|
||||
def: RouteDef;
|
||||
}
|
||||
|
||||
/** Context passed to a WebSocket route's `open`: path params, inbound message stream, abort signal, and neutral request. */
|
||||
export interface WsOpenCtx {
|
||||
params: Record<string, string>;
|
||||
inbound: AsyncIterable<unknown>;
|
||||
abort: AbortSignal;
|
||||
req: WsRequest;
|
||||
}
|
||||
|
||||
/** A registered WebSocket route: path pattern and an `open` that returns the outbound message stream. */
|
||||
export interface WsRouteDef {
|
||||
pattern: string;
|
||||
open: (ctx: WsOpenCtx) => Promise<AsyncIterable<unknown>>;
|
||||
}
|
||||
|
||||
/** Hook for a mesh gateway to take over WebSocket upgrades on a fixed path. */
|
||||
export interface MeshControl {
|
||||
path: string;
|
||||
/**
|
||||
* Serves one control connection over the neutral socket — the same capability every other ws
|
||||
* consumer takes, so Node (via `nodeSocket`) and Deno/Bun (via `app.upgrade`) both feed it.
|
||||
* Resolves when the connection ends, like `runWsConnection`.
|
||||
*/
|
||||
handle(socket: WsSocket): Promise<void>;
|
||||
}
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
import type { StreamEncoder } from '../encoders';
|
||||
import { handle, computeInjected, type HandleResult } from './core';
|
||||
import { mergeInjectedHeaders } from './headers';
|
||||
import { parseRequestBody } from './server';
|
||||
import { normalizeRequestPath, resolveRoute } from './router';
|
||||
import { HttpError } from '../signals';
|
||||
import { renderError, type ErrorRequest, type ErrorResponse } from '../transformers';
|
||||
import type { RouteDef, HttpOptions, MatchedRoute } from './types';
|
||||
|
||||
/** Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream cancel. */
|
||||
export function asReadableStream(source: AsyncIterable<unknown>, encoder: StreamEncoder): ReadableStream<Uint8Array> {
|
||||
const iterator = source[Symbol.asyncIterator]();
|
||||
const te = new TextEncoder();
|
||||
return new ReadableStream<Uint8Array>({
|
||||
async pull(controller) {
|
||||
try {
|
||||
const { value, done } = await iterator.next();
|
||||
|
||||
if (done) {
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
|
||||
const encoded = encoder.encode(value);
|
||||
const bytes = typeof encoded === 'string' ? te.encode(encoded) : encoded;
|
||||
controller.enqueue(bytes);
|
||||
} catch (err) {
|
||||
controller.error(err);
|
||||
}
|
||||
},
|
||||
async cancel() {
|
||||
await iterator.return?.();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Converts a web `Headers` into the plain record shape the neutral core and body parser expect. */
|
||||
function headersToRecord(headers: Headers): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
headers.forEach((value, key) => {
|
||||
out[key] = value;
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns a rendered error (or any {status, headers, body}) into a web `Response`, merging in the
|
||||
* authoritative `injected` security/CORS headers — mirrors the Node adapter, where
|
||||
* `patchResponseHeaders` installs these before body acquisition even runs, so early failures
|
||||
* (413/400/501) carry them too.
|
||||
*/
|
||||
function errorResponse(rendered: ErrorResponse, injected: Record<string, string>): Response {
|
||||
const headers = mergeInjectedHeaders(rendered.headers, injected);
|
||||
return new Response(rendered.body, { status: rendered.status, headers });
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads and parses a matched request's body (enforcing `maxBodyBytes` → 413), mirroring the Node
|
||||
* adapter's `acquireBody`. Returns `{ body }` on success, or a ready-to-send `{ response }` on failure.
|
||||
*/
|
||||
async function acquireFetchBody(
|
||||
request: Request,
|
||||
matched: MatchedRoute,
|
||||
headers: Record<string, string>,
|
||||
path: string,
|
||||
maxBody: number,
|
||||
opts: HttpOptions | undefined,
|
||||
injected: Record<string, string>,
|
||||
): Promise<{ body: unknown } | { response: Response }> {
|
||||
const errReq: ErrorRequest = { method: request.method, url: path, headers };
|
||||
let buf: Buffer | undefined;
|
||||
|
||||
if (request.body) {
|
||||
const arrayBuffer = await request.arrayBuffer();
|
||||
const bodyLimit = matched.def.maxBodyBytes ?? maxBody;
|
||||
|
||||
if (arrayBuffer.byteLength > bodyLimit) {
|
||||
return {
|
||||
response: errorResponse(renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError), injected),
|
||||
};
|
||||
}
|
||||
|
||||
buf = arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer);
|
||||
}
|
||||
|
||||
const contentType = headers['content-type'] ?? '';
|
||||
const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last';
|
||||
const maxParts = matched.def.maxParts ?? opts?.limits?.maxParts ?? 1000;
|
||||
const parsed = await parseRequestBody(buf, contentType, duplicates, maxParts);
|
||||
|
||||
if ('error' in parsed) {
|
||||
return {
|
||||
response: errorResponse(
|
||||
renderError(new HttpError(parsed.status ?? 400, parsed.error), errReq, opts?.onError),
|
||||
injected,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
return { body: parsed.body };
|
||||
}
|
||||
|
||||
/** Converts a {@link HandleResult}'s outcome into a web `Response`, buffered or streamed. */
|
||||
function outcomeToResponse(result: HandleResult): Response {
|
||||
const headers = mergeInjectedHeaders(result.outcome.headers, result.injected) as Record<string, string>;
|
||||
|
||||
if (result.outcome.kind === 'stream') {
|
||||
return new Response(asReadableStream(result.outcome.stream, result.outcome.encoder), { headers });
|
||||
}
|
||||
|
||||
const body = [204, 205, 304].includes(result.outcome.status) ? null : result.outcome.body;
|
||||
return new Response(body, { status: result.outcome.status, headers });
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a Web-Standards `fetch(request)` handler over the same route table the Node adapter uses:
|
||||
* reads the body (enforcing `maxBodyBytes` → 413), parses it by content type, runs it through the
|
||||
* runtime-neutral {@link handle}, and converts the outcome to a `Response` (buffered or streamed).
|
||||
*/
|
||||
export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
|
||||
const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000;
|
||||
|
||||
return async (request: Request): Promise<Response> => {
|
||||
const url = new URL(request.url);
|
||||
const path = url.pathname + url.search;
|
||||
const headers = headersToRecord(request.headers);
|
||||
let matched: ReturnType<typeof resolveRoute>;
|
||||
|
||||
try {
|
||||
matched = resolveRoute(routes, request.method, normalizeRequestPath(url.pathname));
|
||||
} catch {
|
||||
matched = undefined; // handle() renders the shared 400 response without reading a body
|
||||
}
|
||||
|
||||
const secure = url.protocol === 'https:';
|
||||
// Computed up-front from the same inputs `handle()` uses, so early-failure responses (413/400/501,
|
||||
// before a route handler even runs) carry the same security/CORS headers Node's writeHead patch
|
||||
// would have installed before body acquisition.
|
||||
const injected = computeInjected(opts, { secure, headers });
|
||||
let body: unknown;
|
||||
|
||||
if (matched) {
|
||||
const acquired = await acquireFetchBody(request, matched, headers, path, maxBody, opts, injected);
|
||||
if ('response' in acquired) return acquired.response;
|
||||
body = acquired.body;
|
||||
}
|
||||
|
||||
const result = await handle(routes, opts, {
|
||||
method: request.method,
|
||||
url: path,
|
||||
headers,
|
||||
body,
|
||||
secure,
|
||||
// Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the proxy is
|
||||
// trusted, and take its first hop — an untrusted XFF is client-spoofable, and there's no socket
|
||||
// peer address to fall back to on the fetch path, so the untrusted case is simply ''.
|
||||
ip: opts?.trustProxy
|
||||
? String(headers['x-forwarded-for'] ?? '')
|
||||
.split(',')[0]
|
||||
.trim()
|
||||
: '',
|
||||
});
|
||||
|
||||
// Mirrors the Node adapter, where `result.preflight` is written through the writeHead patch and
|
||||
// so picks up the same authoritative security headers `injected` carries (Node's writeHead patch
|
||||
// merges every response — including the 204 preflight — with `injected`; this adapter must too).
|
||||
if ('preflight' in result) {
|
||||
return new Response(null, { status: 204, headers: mergeInjectedHeaders(result.preflight, injected) });
|
||||
}
|
||||
|
||||
return outcomeToResponse(result);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import { channel } from '../channel';
|
||||
import type { App } from '../app/types';
|
||||
import type { WsRequest, WsSocket } from './ws-core';
|
||||
|
||||
/**
|
||||
* Shared plumbing for the runtime adapters (Bun/Deno/edge) that bridge a host WebSocket
|
||||
* to the neutral {@link WsSocket} the core talks to. Separate from `ws-core` on purpose:
|
||||
* that module *runs* a connection, this one *builds* one from a host runtime's socket.
|
||||
*/
|
||||
|
||||
const decoder = new TextDecoder();
|
||||
const OPEN = 1; // WebSocket.OPEN — same constant in every runtime; avoids a per-runtime ambient
|
||||
|
||||
/** Decodes a host `message` payload to the string the core expects (parity with Node's Buffer.toString()). */
|
||||
export function decodeMessage(data: string | ArrayBuffer | Uint8Array): string {
|
||||
return typeof data === 'string' ? data : decoder.decode(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a neutral {@link WsRequest} from a Web-standard `Request`. Every adapter derives
|
||||
* url/headers/protocol identically; only the client IP is runtime-specific, so it's passed in.
|
||||
*/
|
||||
export function toWsRequest(request: Request, ip: string): WsRequest {
|
||||
const url = new URL(request.url);
|
||||
const headers: Record<string, string> = {};
|
||||
request.headers.forEach((value, key) => {
|
||||
headers[key] = value;
|
||||
});
|
||||
|
||||
return {
|
||||
url: url.pathname + url.search,
|
||||
headers,
|
||||
protocol: url.protocol === 'https:' ? 'https' : 'http',
|
||||
ip,
|
||||
};
|
||||
}
|
||||
|
||||
/** The subset of a host WebSocket that {@link eventSocket} drives (Deno's WebSocket and workerd's both satisfy it). */
|
||||
export interface EventfulSocket {
|
||||
readonly readyState: number;
|
||||
send(data: string): void;
|
||||
close(code?: number, reason?: string): void;
|
||||
addEventListener(
|
||||
type: 'open' | 'message' | 'close' | 'error',
|
||||
listener: (event: { data?: string | ArrayBuffer; error?: unknown }) => void,
|
||||
): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps an `addEventListener`-style host socket (Deno, workerd) as a neutral {@link WsSocket}:
|
||||
* creates the inbound channel and abort controller and wires message/close/error into them.
|
||||
* Bun does not use this — its socket events are delivered to a server-level handler rather
|
||||
* than the socket, so it builds its own {@link WsSocket} over state stashed on `ws.data`.
|
||||
*/
|
||||
export function eventSocket(host: EventfulSocket): WsSocket {
|
||||
const inbound = channel<unknown>();
|
||||
const ac = new AbortController();
|
||||
|
||||
host.addEventListener('message', (event) => {
|
||||
inbound.push(decodeMessage(event.data as string | ArrayBuffer));
|
||||
});
|
||||
host.addEventListener('close', () => {
|
||||
inbound.close();
|
||||
ac.abort();
|
||||
});
|
||||
host.addEventListener('error', () => {
|
||||
inbound.fail(new Error('websocket error'));
|
||||
ac.abort();
|
||||
});
|
||||
|
||||
return neutralSocket(host, inbound, ac);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps a host socket's send/close/readyState as a neutral {@link WsSocket} over an
|
||||
* already-wired channel and abort controller. `close`/`terminate` swallow throws so
|
||||
* callers never have to guard an already-closed socket.
|
||||
*/
|
||||
export function neutralSocket(
|
||||
host: Pick<EventfulSocket, 'readyState' | 'send' | 'close'> & { terminate?(): void },
|
||||
inbound: ReturnType<typeof channel<unknown>>,
|
||||
ac: AbortController,
|
||||
): WsSocket {
|
||||
return {
|
||||
inbound,
|
||||
abort: ac.signal,
|
||||
get isOpen() {
|
||||
return host.readyState === OPEN;
|
||||
},
|
||||
send: (data) => {
|
||||
host.send(data);
|
||||
},
|
||||
close: (code, reason) => {
|
||||
try {
|
||||
host.close(code, reason);
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
},
|
||||
terminate: () => {
|
||||
try {
|
||||
(host.terminate ?? host.close).call(host);
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Constructs a host WebSocket *client*. Both the platform global and the `ws` package satisfy it. */
|
||||
export type SocketCtor = new (url: string) => EventfulSocket;
|
||||
|
||||
/**
|
||||
* The WebSocket client implementation: the platform global where it exists (Deno, Bun, and
|
||||
* Node >= 22), else the `ws` optional peer — Node 18-21, our declared floor, has no global.
|
||||
*
|
||||
* Both expose the same `addEventListener` API and deliver text frames as `event.data` strings,
|
||||
* so one bridge covers both. That is verified rather than assumed: `ws` implements the
|
||||
* browser-compatible event API alongside its EventEmitter one.
|
||||
*/
|
||||
export function loadWebSocketCtor(): SocketCtor {
|
||||
const platform = (globalThis as { WebSocket?: SocketCtor }).WebSocket;
|
||||
|
||||
if (platform) return platform;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
return require('ws') as SocketCtor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a client connection and wraps it as a neutral {@link WsSocket}. `opened` resolves once
|
||||
* the socket is live (the caller's cue to send its first frame) and rejects if it never opens.
|
||||
*
|
||||
* `Ctor` is injectable so both implementations can be exercised on one runtime — otherwise CI
|
||||
* on a single Node version would silently cover only one of the two paths.
|
||||
*/
|
||||
export function connectSocket(
|
||||
url: string,
|
||||
Ctor: SocketCtor = loadWebSocketCtor(),
|
||||
): { socket: WsSocket; opened: Promise<void> } {
|
||||
const host = new Ctor(url);
|
||||
// registered before eventSocket's own error listener, so a connect failure rejects `opened`
|
||||
// with the host's real error rather than eventSocket's generic one
|
||||
const opened = new Promise<void>((resolve, reject) => {
|
||||
host.addEventListener('open', () => resolve());
|
||||
host.addEventListener('error', (event) => reject(event?.error ?? new Error(`websocket error: ${url}`)));
|
||||
});
|
||||
|
||||
return { socket: eventSocket(host), opened };
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the ws lifecycle, closing with 1011 if it rejects. `app.upgrade` can reject *before*
|
||||
* `runWsConnection`'s own try/catch (mesh-before-listen, provider boot failure); unguarded,
|
||||
* that surfaces as an uncaught rejection and is fatal on Bun/Deno. Returns the promise so
|
||||
* edge can hand it to `ctx.waitUntil`.
|
||||
*/
|
||||
export function upgradeSafely(app: App, request: WsRequest, socket: WsSocket): Promise<void> {
|
||||
return app.upgrade(request, socket).catch(() => {
|
||||
socket.close(1011, 'internal error'); // neutral close already swallows throws
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import { isHttpError } from '../signals';
|
||||
import type { Bus } from '../bus';
|
||||
import { matchPattern } from './router';
|
||||
import type { WsRouteDef } from './types';
|
||||
|
||||
/** Neutral, runtime-free WebSocket request context (replaces the raw Node req). */
|
||||
export interface WsRequest {
|
||||
url: string;
|
||||
headers: Record<string, string | string[] | undefined>;
|
||||
protocol: 'http' | 'https';
|
||||
ip: string;
|
||||
}
|
||||
|
||||
/** Capability an adapter builds from its runtime socket. The neutral core talks only to this. */
|
||||
export interface WsSocket {
|
||||
readonly inbound: AsyncIterable<unknown>;
|
||||
readonly abort: AbortSignal;
|
||||
readonly isOpen: boolean;
|
||||
send(data: string): void;
|
||||
close(code?: number, reason?: string): void;
|
||||
terminate(): void;
|
||||
}
|
||||
|
||||
/** Finds the first ws route whose pattern matches `path`, capturing its params. */
|
||||
export function matchWsRoute(
|
||||
wsRoutes: WsRouteDef[],
|
||||
path: string,
|
||||
): { def: WsRouteDef; params: Record<string, string> | undefined } | undefined {
|
||||
return wsRoutes
|
||||
.map((candidate) => ({ def: candidate, params: matchPattern(candidate.pattern, path) }))
|
||||
.find((entry) => entry.params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs `connection` with the socket registered for force-close on shutdown, unregistering it
|
||||
* when the connection ends. Without this a long-lived socket keeps `server.close()` waiting for
|
||||
* a peer that has no reason to hang up — the mesh control channel is exactly that shape.
|
||||
*/
|
||||
export async function trackUntil(
|
||||
socket: WsSocket,
|
||||
connection: Promise<void>,
|
||||
streams?: Set<() => void>,
|
||||
): Promise<void> {
|
||||
const { closer } = trackConnection(socket, streams);
|
||||
|
||||
try {
|
||||
await connection;
|
||||
} finally {
|
||||
streams?.delete(closer);
|
||||
}
|
||||
}
|
||||
|
||||
/** Registers the connection with the stream registry so it can be force-closed on shutdown. */
|
||||
function trackConnection(socket: WsSocket, streams?: Set<() => void>): { closer: () => void } {
|
||||
const closer = () => {
|
||||
try {
|
||||
socket.terminate();
|
||||
} catch {
|
||||
/* */
|
||||
}
|
||||
};
|
||||
|
||||
streams?.add(closer);
|
||||
return { closer };
|
||||
}
|
||||
|
||||
/** Drives the outbound async iterator, sending each yielded value until done or the socket closes. */
|
||||
async function pumpOutbound(socket: WsSocket, iterator: AsyncIterator<unknown>): Promise<void> {
|
||||
while (true) {
|
||||
const { value, done } = await iterator.next();
|
||||
if (done) break;
|
||||
if (!socket.isOpen) break;
|
||||
socket.send(typeof value === 'string' ? value : JSON.stringify(value));
|
||||
}
|
||||
|
||||
try {
|
||||
socket.close();
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
}
|
||||
|
||||
/** Closes with 4000+status for HttpErrors, 1011 otherwise. */
|
||||
function closeOnError(socket: WsSocket, err: unknown): void {
|
||||
if (isHttpError(err)) {
|
||||
const reason = new TextDecoder().decode(new TextEncoder().encode(String(err.message)).subarray(0, 120));
|
||||
|
||||
try {
|
||||
socket.close(4000 + err.status, reason);
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
socket.close(1011);
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs the full per-connection lifecycle over a neutral socket capability. */
|
||||
export async function runWsConnection(
|
||||
socket: WsSocket,
|
||||
request: WsRequest,
|
||||
route: { def: WsRouteDef; params: Record<string, string> | undefined },
|
||||
bus?: Bus,
|
||||
streams?: Set<() => void>,
|
||||
): Promise<void> {
|
||||
const { closer } = trackConnection(socket, streams);
|
||||
const name = route.def.pattern;
|
||||
let iterator: AsyncIterator<unknown> | undefined;
|
||||
|
||||
const onAbort = () => {
|
||||
streams?.delete(closer);
|
||||
void Promise.resolve(iterator?.return?.()).catch(() => {});
|
||||
};
|
||||
|
||||
socket.abort.addEventListener('abort', onAbort, { once: true });
|
||||
bus?.emit('stream:open', { name });
|
||||
|
||||
try {
|
||||
const outbound = await route.def.open({
|
||||
params: route.params ?? {},
|
||||
inbound: socket.inbound,
|
||||
abort: socket.abort,
|
||||
req: request,
|
||||
});
|
||||
iterator = outbound[Symbol.asyncIterator]();
|
||||
await pumpOutbound(socket, iterator);
|
||||
} catch (err) {
|
||||
bus?.emit('stream:error', { name, error: err });
|
||||
closeOnError(socket, err);
|
||||
} finally {
|
||||
bus?.emit('stream:close', { name });
|
||||
}
|
||||
}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
import type http from 'http';
|
||||
import { channel } from '../channel';
|
||||
import type { Bus } from '../bus';
|
||||
import { runWsConnection, matchWsRoute, trackUntil, type WsSocket, type WsRequest } from './ws-core';
|
||||
import type { WsRouteDef, MeshControl } from './types';
|
||||
|
||||
/** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */
|
||||
function loadWss(): any | null {
|
||||
try {
|
||||
// `ws` is an OPTIONAL peer dependency: lazy-required so installs without WebSocket
|
||||
// support don't fail. When absent this throws and we fall back to null (501 on upgrade).
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
return require('ws').WebSocketServer;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes a 501 Not Implemented status to the raw socket and destroys it. */
|
||||
function reject501(socket: any): void {
|
||||
socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n');
|
||||
socket.destroy();
|
||||
}
|
||||
|
||||
/** Handles the mesh-control upgrade path; returns true when the request was for the mesh control endpoint. */
|
||||
function handleMeshUpgrade(
|
||||
wss: any,
|
||||
meshControl: MeshControl,
|
||||
path: string,
|
||||
req: http.IncomingMessage,
|
||||
socket: any,
|
||||
head: Buffer,
|
||||
streams?: Set<() => void>,
|
||||
): boolean {
|
||||
if (path !== meshControl.path) return false;
|
||||
|
||||
if (!wss) {
|
||||
reject501(socket);
|
||||
return true;
|
||||
}
|
||||
|
||||
// nodeSocket, not the raw ws: the control channel is the last consumer that spoke the
|
||||
// `ws` EventEmitter API directly. It now takes the same neutral socket every route does.
|
||||
// Tracked like any other long-lived socket: a connected teacup has no reason to hang up, so
|
||||
// an untracked control channel leaves the teapot's server.close() waiting on it forever.
|
||||
// serveFrames swallows its own failures, so the floating promise cannot reject.
|
||||
wss.handleUpgrade(req, socket, head, (ws: any) => {
|
||||
const neutral = nodeSocket(ws);
|
||||
|
||||
void trackUntil(neutral, meshControl.handle(neutral), streams);
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Builds the neutral WsRequest from a Node upgrade request. Same values the old open() read from req.socket. */
|
||||
function nodeWsRequest(req: http.IncomingMessage): WsRequest {
|
||||
return {
|
||||
url: req.url ?? '/',
|
||||
headers: req.headers,
|
||||
protocol: (req.socket as any).encrypted ? 'https' : 'http',
|
||||
ip: req.socket.remoteAddress ?? '',
|
||||
};
|
||||
}
|
||||
|
||||
/** Wraps a `ws` socket as a neutral WsSocket: inbound channel + abort on close + send/close/terminate. */
|
||||
function nodeSocket(ws: any): WsSocket {
|
||||
const inbound = channel<unknown>();
|
||||
const ac = new AbortController();
|
||||
ws.on('message', (data: Buffer) => inbound.push(data.toString()));
|
||||
ws.on('close', () => {
|
||||
inbound.close();
|
||||
ac.abort();
|
||||
});
|
||||
ws.on('error', (err: unknown) => inbound.fail(err));
|
||||
return {
|
||||
inbound,
|
||||
abort: ac.signal,
|
||||
get isOpen() {
|
||||
return ws.readyState === 1; // 1 = OPEN
|
||||
},
|
||||
send: (data) => ws.send(data),
|
||||
close: (code, reason) => {
|
||||
try {
|
||||
ws.close(code, reason);
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
},
|
||||
terminate: () => (ws.terminate ?? ws.close).call(ws),
|
||||
};
|
||||
}
|
||||
|
||||
/** Attaches WebSocket upgrade handling to the server: routes to `wsRoutes` or a mesh control path. */
|
||||
export function attachWs(
|
||||
server: http.Server,
|
||||
wsRoutes: WsRouteDef[],
|
||||
bus?: Bus,
|
||||
meshControl?: MeshControl,
|
||||
streams?: Set<() => void>,
|
||||
): void {
|
||||
if (wsRoutes.length === 0 && !meshControl) return;
|
||||
const WebSocketServer = loadWss();
|
||||
const wss = WebSocketServer ? new WebSocketServer({ noServer: true }) : null;
|
||||
server.on('upgrade', (req, socket, head) => {
|
||||
const path = (req.url ?? '/').split('?')[0];
|
||||
|
||||
if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head, streams)) return;
|
||||
|
||||
const route = matchWsRoute(wsRoutes, path);
|
||||
|
||||
if (!route) {
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!wss) {
|
||||
reject501(socket);
|
||||
return;
|
||||
}
|
||||
|
||||
wss.handleUpgrade(req, socket, head, (ws: any) => {
|
||||
void runWsConnection(nodeSocket(ws), nodeWsRequest(req), route, bus, streams);
|
||||
});
|
||||
});
|
||||
}
|
||||
+64
-9
@@ -1,29 +1,84 @@
|
||||
/**
|
||||
* @green-tea/core — a decorator-driven, type-safe HTTP framework.
|
||||
* Public API barrel: application bootstrap, routing/DI decorators, streaming,
|
||||
* request validation, security helpers, and the cross-server mesh.
|
||||
*/
|
||||
import 'reflect-metadata';
|
||||
|
||||
export const VERSION = '0.0.0';
|
||||
/** Package version, replaced at publish time. */
|
||||
export const VERSION = '26.8.0-beta.0';
|
||||
|
||||
// Application
|
||||
export { createApp } from './app';
|
||||
export type { App, InspectLine, Explain } from './app';
|
||||
export type { App, InspectLine, Explain, MeshConfig } from './app';
|
||||
|
||||
// Graph visualization
|
||||
export { toMermaid, toDOT } from './graph-viz';
|
||||
export type { GraphView } from './graph-viz';
|
||||
export { Provider, Step, Route, Get, Module, Transformer } from './metadata';
|
||||
export { buildOpenApi } from './openapi';
|
||||
export type { OpenApiDoc, OpenApiInfo, OpenApiRoute } from './openapi';
|
||||
|
||||
// Views
|
||||
export { render } from './views';
|
||||
|
||||
// Routing & decorators
|
||||
export {
|
||||
Provider,
|
||||
Step,
|
||||
Route,
|
||||
Get,
|
||||
Head,
|
||||
Module,
|
||||
Transformer,
|
||||
Sse,
|
||||
Ws,
|
||||
Stream,
|
||||
Post,
|
||||
Put,
|
||||
Patch,
|
||||
Delete,
|
||||
Options,
|
||||
Html,
|
||||
} from './metadata';
|
||||
export type { Transport, HttpMethod } from './metadata';
|
||||
export type { Plugin } from './plugin';
|
||||
|
||||
// Transformers & error signals
|
||||
export { JsonTransformer } from './transformers';
|
||||
export { HttpError, Unauthorized, NotFound, Redirect, NotModified } from './signals';
|
||||
export type { ErrorRenderer, ErrorRequest, ErrorResponse } from './transformers';
|
||||
export {
|
||||
HttpError,
|
||||
Unauthorized,
|
||||
NotFound,
|
||||
Redirect,
|
||||
NotModified,
|
||||
ValidationError,
|
||||
TransportMismatchError,
|
||||
} from './signals';
|
||||
|
||||
// Bus & flow
|
||||
export { Bus } from './bus';
|
||||
export { flow, Flow } from './flow';
|
||||
export type { StepFn, CompiledFlow } from './flow';
|
||||
export { needs, ctx, param, query, body, headers } from './params';
|
||||
|
||||
// Parameter decorators
|
||||
export { needs, ctx, param, query, body, headers, header, inbound, abort } from './params';
|
||||
export type { Query, Headers, Context, ArgSpec } from './params';
|
||||
|
||||
// Streaming
|
||||
export { channel, isAsyncIterable } from './channel';
|
||||
export type { Channel } from './channel';
|
||||
export { Rooms } from './rooms';
|
||||
export { Sse, Ws, Stream, Post, Put, Patch, Delete } from './metadata';
|
||||
export type { Transport, HttpMethod } from './metadata';
|
||||
export { inbound, abort } from './params';
|
||||
export { sseEncoder, ndjsonEncoder } from './encoders';
|
||||
export type { StreamEncoder } from './encoders';
|
||||
export type { MeshConfig } from './app';
|
||||
|
||||
// HTTP, security & validation
|
||||
export type { RequestLimits } from './http';
|
||||
export type { TlsOptions, CorsOptions, SecurityOptions } from './security';
|
||||
export type { UploadedFile, MultipartBody } from './multipart';
|
||||
export type { StandardSchemaV1 } from './standard-schema';
|
||||
|
||||
// Mesh
|
||||
export { connectLink } from './mesh/link';
|
||||
export { buildRemote, envelopeFrom } from './mesh/teacup';
|
||||
export { buildManifest, createMeshControl, MESH_CONTROL_PATH } from './mesh/teapot';
|
||||
|
||||
+227
-67
@@ -1,99 +1,259 @@
|
||||
import type { Bus } from '../bus';
|
||||
import { HttpError } from '../signals';
|
||||
import { encode, decode, type Manifest, type RequestEnvelope, type Frame } from './protocol';
|
||||
|
||||
let connSeq = 0; // module-level: deterministic unique connection-id prefix (no Date.now/Math.random)
|
||||
import { connectSocket, type SocketCtor } from '../http/ws-adapter';
|
||||
import type { WsSocket } from '../http/ws-core';
|
||||
import { encode, decode, MESH_PROTOCOL_VERSION, type Manifest, type RequestEnvelope, type Frame } from './protocol';
|
||||
|
||||
/** Client handle to a remote mesh server: its manifest, an RPC caller, and a close(). */
|
||||
export interface Link {
|
||||
manifest: Manifest;
|
||||
rpc(kind: 'scope' | 'route', name: string, ctx: RequestEnvelope): Promise<unknown>;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
function loadWs(): any {
|
||||
return require('ws'); // lazy/optional, like streams; the ws CJS export is the WebSocket class
|
||||
/** An in-flight RPC awaiting its `rpc-res`, keyed by id in the pending map. */
|
||||
type PendingEntry = {
|
||||
resolve: (v: unknown) => void;
|
||||
reject: (e: unknown) => void;
|
||||
timer: ReturnType<typeof setTimeout>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Reject and clear every in-flight RPC — used when the link closes.
|
||||
* 503, not a bare Error: a dead upstream is not "this service broke", and the status is what
|
||||
* tells a caller it may retry and an operator where to look. A bare Error renders as a 500.
|
||||
*/
|
||||
function rejectAllPending(pending: Map<string, PendingEntry>, reason: string): void {
|
||||
for (const [, entry] of pending) {
|
||||
clearTimeout(entry.timer);
|
||||
entry.reject(new HttpError(503, reason));
|
||||
}
|
||||
|
||||
pending.clear();
|
||||
}
|
||||
|
||||
/** Register one RPC in `pending` by id, send its request, and reject it on timeout. */
|
||||
function sendRpc(
|
||||
socket: WsSocket,
|
||||
pending: Map<string, PendingEntry>,
|
||||
id: string,
|
||||
kind: 'scope' | 'route',
|
||||
name: string,
|
||||
ctx: RequestEnvelope,
|
||||
timeoutMs: number,
|
||||
): Promise<unknown> {
|
||||
// Answer now rather than in timeoutMs. A closed socket cannot deliver the frame, so waiting
|
||||
// would make every request to a downed teapot hang for the full timeout (30s by default)
|
||||
// before failing anyway — the caller pays for a verdict already known.
|
||||
if (!socket.isOpen) {
|
||||
return Promise.reject(new HttpError(503, `mesh link is down: cannot resolve '${name}'`));
|
||||
}
|
||||
|
||||
return new Promise((resolveCall, rejectCall) => {
|
||||
// 504: the link is alive but the teapot did not answer in time — a gateway timeout,
|
||||
// which is a different operational story from a link that is down.
|
||||
const timer = setTimeout(() => {
|
||||
pending.delete(id);
|
||||
rejectCall(new HttpError(504, `mesh rpc timeout: ${name}`));
|
||||
}, timeoutMs);
|
||||
|
||||
pending.set(id, { resolve: resolveCall, reject: rejectCall, timer });
|
||||
socket.send(encode({ type: 'rpc-req', id, kind, name, ctx }));
|
||||
});
|
||||
}
|
||||
|
||||
/** Assemble the client-facing Link once the manifest arrives. */
|
||||
function buildLink(socket: WsSocket, pending: Map<string, PendingEntry>, manifest: Manifest, timeoutMs: number): Link {
|
||||
// ids only need to be unique within this link: `pending` is per-connection, so a
|
||||
// per-link counter suffices (no module-global sequence, no test-order coupling).
|
||||
let counter = 0;
|
||||
|
||||
return {
|
||||
manifest,
|
||||
rpc(kind, name, ctx) {
|
||||
const id = String(counter++);
|
||||
|
||||
return sendRpc(socket, pending, id, kind, name, ctx, timeoutMs);
|
||||
},
|
||||
close() {
|
||||
socket.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Settle a pending RPC from its `rpc-res` frame — resolve on ok, reject (and emit) on error. */
|
||||
function settleRpcResponse(
|
||||
pending: Map<string, PendingEntry>,
|
||||
frame: Extract<Frame, { type: 'rpc-res' }>,
|
||||
bus?: Bus,
|
||||
): void {
|
||||
const entry = pending.get(frame.id);
|
||||
if (!entry) return;
|
||||
pending.delete(frame.id);
|
||||
clearTimeout(entry.timer);
|
||||
|
||||
if (frame.ok) {
|
||||
entry.resolve(frame.result);
|
||||
} else {
|
||||
bus?.emit('mesh:rpc:error', { name: frame.id, error: frame.error });
|
||||
entry.reject(new HttpError(frame.error.status ?? 500, frame.error.message));
|
||||
}
|
||||
}
|
||||
|
||||
/** Default gap between heartbeat pings. Two missed rounds close the link. */
|
||||
const HEARTBEAT_MS = 15_000;
|
||||
|
||||
/**
|
||||
* Close code for a link we hang up on because its teapot went quiet.
|
||||
*
|
||||
* Not 1011: a *client* may only send 1000 or 3000-4999 — anything else throws `invalid code`,
|
||||
* and our neutral close swallows throws, so a reserved code would leave the link open while
|
||||
* looking like it closed. 4000+ is the application range, so 4011 mirrors 1011's meaning.
|
||||
*/
|
||||
const CLOSE_HEARTBEAT_TIMEOUT = 4011;
|
||||
|
||||
/**
|
||||
* Pings the teapot on an interval and closes the link if a round goes unanswered.
|
||||
*
|
||||
* A TCP connection can die without either side noticing — a dropped route, a killed container,
|
||||
* a NAT timing out — leaving the socket "open" with nobody home. Without this, a teacup only
|
||||
* learns on the next request, which pays the full rpc timeout before failing. Closing the socket
|
||||
* turns that into an immediate 503 from the dead-link guard, and emits `mesh:disconnect`.
|
||||
*
|
||||
* The interval is unref'd, so a heartbeat never holds the process open by itself.
|
||||
*/
|
||||
function startHeartbeat(socket: WsSocket, everyMs: number): { stop: () => void; markAlive: () => void } {
|
||||
let answered = true;
|
||||
|
||||
const timer = setInterval(() => {
|
||||
if (!answered) {
|
||||
socket.close(CLOSE_HEARTBEAT_TIMEOUT, 'mesh heartbeat timeout'); // aborts -> disconnect + reject pending
|
||||
return;
|
||||
}
|
||||
|
||||
answered = false;
|
||||
socket.send(encode({ type: 'ping' }));
|
||||
}, everyMs);
|
||||
timer.unref?.();
|
||||
|
||||
return {
|
||||
stop: () => clearInterval(timer),
|
||||
markAlive: () => {
|
||||
answered = true;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Handle for the in-flight handshake, so the frame loop can settle `connectLink`'s promise. */
|
||||
interface Handshake {
|
||||
url: string;
|
||||
socket: WsSocket;
|
||||
pending: Map<string, PendingEntry>;
|
||||
timeoutMs: number;
|
||||
bus?: Bus;
|
||||
resolve: (link: Link) => void;
|
||||
reject: (error: unknown) => void;
|
||||
onManifest: () => void;
|
||||
onPong: () => void;
|
||||
}
|
||||
|
||||
/** Settle the handshake from a `manifest` frame: refuse a version mismatch, else build the Link. */
|
||||
function settleManifest(frame: Extract<Frame, { type: 'manifest' }>, hs: Handshake): void {
|
||||
if (frame.v !== MESH_PROTOCOL_VERSION) {
|
||||
hs.socket.close();
|
||||
hs.reject(
|
||||
new Error(
|
||||
`mesh protocol version mismatch at ${hs.url}: teapot speaks v${frame.v}, this teacup speaks v${MESH_PROTOCOL_VERSION}`,
|
||||
),
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
hs.onManifest();
|
||||
hs.bus?.emit('mesh:connect', { name: hs.url });
|
||||
hs.resolve(buildLink(hs.socket, hs.pending, { scopes: frame.scopes, routes: frame.routes }, hs.timeoutMs));
|
||||
}
|
||||
|
||||
/** Consume the link's inbound frames until it closes, settling the handshake then each RPC. */
|
||||
async function readFrames(hs: Handshake): Promise<void> {
|
||||
for await (const data of hs.socket.inbound) {
|
||||
let frame: Frame;
|
||||
|
||||
try {
|
||||
frame = decode(String(data));
|
||||
} catch {
|
||||
continue; // undecodable frames are ignored
|
||||
}
|
||||
|
||||
if (frame.type === 'manifest') settleManifest(frame, hs);
|
||||
else if (frame.type === 'pong') hs.onPong();
|
||||
else if (frame.type === 'rpc-res') settleRpcResponse(hs.pending, frame, hs.bus);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a WebSocket link to a mesh server, handshake with `secret`, and resolve once its manifest
|
||||
* arrives. `Ctor` is injectable to exercise both client implementations on a single runtime.
|
||||
*/
|
||||
export function connectLink(args: {
|
||||
url: string;
|
||||
secret: string;
|
||||
timeoutMs?: number;
|
||||
heartbeatMs?: number;
|
||||
bus?: Bus;
|
||||
Ctor?: SocketCtor;
|
||||
}): Promise<Link> {
|
||||
const timeoutMs = args.timeoutMs ?? 30_000;
|
||||
const WS = loadWs();
|
||||
const ws = new WS(args.url);
|
||||
const pending = new Map<
|
||||
string,
|
||||
{ resolve: (v: unknown) => void; reject: (e: unknown) => void; timer: ReturnType<typeof setTimeout> }
|
||||
>();
|
||||
let counter = 0;
|
||||
const connId = `c${connSeq++}`;
|
||||
let manifest: Manifest | undefined;
|
||||
const { socket, opened } = connectSocket(args.url, args.Ctor ?? undefined);
|
||||
const pending = new Map<string, PendingEntry>();
|
||||
let manifest = false;
|
||||
let heartbeat: { stop: () => void; markAlive: () => void } | undefined;
|
||||
|
||||
return new Promise<Link>((resolve, reject) => {
|
||||
const connectTimer = setTimeout(() => {
|
||||
ws.close();
|
||||
socket.close();
|
||||
reject(new Error(`mesh connect timeout: ${args.url}`));
|
||||
}, timeoutMs);
|
||||
|
||||
ws.on('open', () => ws.send(encode({ type: 'hello', secret: args.secret })));
|
||||
ws.on('error', (e: unknown) => reject(e));
|
||||
ws.on('close', () => {
|
||||
const hs: Handshake = {
|
||||
url: args.url,
|
||||
socket,
|
||||
pending,
|
||||
timeoutMs,
|
||||
bus: args.bus,
|
||||
resolve,
|
||||
reject,
|
||||
onManifest: () => {
|
||||
manifest = true;
|
||||
clearTimeout(connectTimer);
|
||||
// started only once authenticated: an unauthenticated peer should not be pinging
|
||||
heartbeat = startHeartbeat(socket, args.heartbeatMs ?? HEARTBEAT_MS);
|
||||
},
|
||||
onPong: () => heartbeat?.markAlive(),
|
||||
};
|
||||
|
||||
opened.then(
|
||||
() => socket.send(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: args.secret })),
|
||||
(error) => reject(error),
|
||||
);
|
||||
|
||||
// abort fires on close *and* on error (see eventSocket), covering both paths the raw
|
||||
// 'close' listener used to: a refused handshake and a dropped link.
|
||||
socket.abort.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
clearTimeout(connectTimer);
|
||||
heartbeat?.stop();
|
||||
args.bus?.emit('mesh:disconnect', { name: args.url });
|
||||
for (const [, p] of pending) {
|
||||
clearTimeout(p.timer);
|
||||
p.reject(new Error('mesh link closed'));
|
||||
}
|
||||
pending.clear();
|
||||
rejectAllPending(pending, `mesh link to ${args.url} is down`);
|
||||
if (!manifest) reject(new Error(`mesh handshake failed: ${args.url}`));
|
||||
});
|
||||
|
||||
ws.on('message', (data: unknown) => {
|
||||
let frame: Frame;
|
||||
try {
|
||||
frame = decode(String(data));
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
if (frame.type === 'manifest') {
|
||||
manifest = { scopes: frame.scopes, routes: frame.routes };
|
||||
clearTimeout(connectTimer);
|
||||
args.bus?.emit('mesh:connect', { name: args.url });
|
||||
resolve({
|
||||
manifest,
|
||||
rpc(kind, name, ctx) {
|
||||
const id = `${connId}:${counter++}`;
|
||||
return new Promise((res, rej) => {
|
||||
const timer = setTimeout(() => {
|
||||
pending.delete(id);
|
||||
rej(new Error(`mesh rpc timeout: ${name}`));
|
||||
}, timeoutMs);
|
||||
pending.set(id, { resolve: res, reject: rej, timer });
|
||||
ws.send(encode({ type: 'rpc-req', id, kind, name, ctx }));
|
||||
});
|
||||
},
|
||||
close() {
|
||||
ws.close();
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
{ once: true },
|
||||
);
|
||||
|
||||
if (frame.type === 'rpc-res') {
|
||||
const p = pending.get(frame.id);
|
||||
if (!p) return;
|
||||
pending.delete(frame.id);
|
||||
clearTimeout(p.timer);
|
||||
if (frame.ok) {
|
||||
p.resolve(frame.result);
|
||||
} else {
|
||||
args.bus?.emit('mesh:rpc:error', { name: frame.id, error: frame.error });
|
||||
p.reject(new HttpError(frame.error.status ?? 500, frame.error.message));
|
||||
}
|
||||
}
|
||||
void readFrames(hs).catch(() => {
|
||||
/* inbound failed; the abort listener above reports it */
|
||||
});
|
||||
});
|
||||
}
|
||||
+94
-15
@@ -1,3 +1,12 @@
|
||||
/**
|
||||
* Version of the mesh wire protocol. Peers are separate processes on separate deploy
|
||||
* cadences — possibly on different runtimes — so the frame shapes are a contract between
|
||||
* green-tea versions, not an internal detail. Bump on any breaking frame change; peers
|
||||
* refuse each other on mismatch rather than misparsing downstream.
|
||||
*/
|
||||
export const MESH_PROTOCOL_VERSION = 1;
|
||||
|
||||
/** Serialized request context sent across the mesh for a scope or route RPC. */
|
||||
export interface RequestEnvelope {
|
||||
method: string;
|
||||
params: Record<string, string>;
|
||||
@@ -6,27 +15,97 @@ export interface RequestEnvelope {
|
||||
headers: Record<string, string | string[] | undefined>;
|
||||
}
|
||||
|
||||
export interface ScopeEntry { token: string; scope: 'app' | 'request' }
|
||||
export interface RouteEntry { method: string; pattern: string }
|
||||
export interface Manifest { scopes: ScopeEntry[]; routes: RouteEntry[] }
|
||||
/** Manifest entry for an exported scope token and its lifetime. */
|
||||
export interface ScopeEntry {
|
||||
token: string;
|
||||
scope: 'app' | 'request';
|
||||
}
|
||||
/** Manifest entry for an exported route. */
|
||||
export interface RouteEntry {
|
||||
method: string;
|
||||
pattern: string;
|
||||
}
|
||||
/** A mesh server's advertised scopes and routes. */
|
||||
export interface Manifest {
|
||||
scopes: ScopeEntry[];
|
||||
routes: RouteEntry[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Discriminated union of every message on the mesh wire. The handshake frames carry `v`.
|
||||
*
|
||||
* `ping`/`pong` are application frames rather than WebSocket protocol pings on purpose: the `ws`
|
||||
* package exposes `ws.ping()`, but the platform `WebSocket` that Deno and Bun provide does not,
|
||||
* so a protocol-level heartbeat could not work on every runtime mesh claims to support.
|
||||
*/
|
||||
export type Frame =
|
||||
| { type: 'hello'; secret: string }
|
||||
| { type: 'manifest'; scopes: ScopeEntry[]; routes: RouteEntry[] }
|
||||
| { type: 'hello'; v: number; secret: string }
|
||||
| { type: 'manifest'; v: number; scopes: ScopeEntry[]; routes: RouteEntry[] }
|
||||
| { type: 'rpc-req'; id: string; kind: 'scope' | 'route'; name: string; ctx: RequestEnvelope }
|
||||
| { type: 'rpc-res'; id: string; ok: true; result: unknown }
|
||||
| { type: 'rpc-res'; id: string; ok: false; error: { message: string; status?: number } };
|
||||
| { type: 'rpc-res'; id: string; ok: false; error: { message: string; status?: number } }
|
||||
| { type: 'ping' }
|
||||
| { type: 'pong' };
|
||||
|
||||
const TYPES = new Set(['hello', 'manifest', 'rpc-req', 'rpc-res']);
|
||||
const isString = (value: unknown): value is string => typeof value === 'string';
|
||||
const isNumber = (value: unknown): boolean => typeof value === 'number';
|
||||
const isObject = (value: unknown): boolean => typeof value === 'object' && value !== null;
|
||||
|
||||
export function encode(f: Frame): string {
|
||||
return JSON.stringify(f);
|
||||
/** Rejects a frame whose fields don't match its `type` tag. `bad` always throws. */
|
||||
type ShapeCheck = (frame: Record<string, unknown>, bad: (why: string) => never) => void;
|
||||
|
||||
/**
|
||||
* Field checks per frame type. `decode` is the mesh's trust boundary: past it, frames are fed
|
||||
* straight to the scope/route resolvers, so a bad shape must die here rather than surface as a
|
||||
* confusing failure downstream. A new frame type must add a row — the compiler fails until it does.
|
||||
*/
|
||||
const SHAPE: Record<Frame['type'], ShapeCheck> = {
|
||||
hello: (frame, bad) => {
|
||||
if (!isNumber(frame.v)) bad('missing protocol version');
|
||||
if (!isString(frame.secret)) bad('secret must be a string');
|
||||
},
|
||||
manifest: (frame, bad) => {
|
||||
if (!isNumber(frame.v)) bad('missing protocol version');
|
||||
if (!Array.isArray(frame.scopes) || !Array.isArray(frame.routes)) bad('scopes and routes must be arrays');
|
||||
},
|
||||
'rpc-req': (frame, bad) => {
|
||||
if (!isString(frame.id)) bad('id must be a string');
|
||||
if (frame.kind !== 'scope' && frame.kind !== 'route') bad("kind must be 'scope' or 'route'");
|
||||
if (!isString(frame.name)) bad('name must be a string');
|
||||
if (!isObject(frame.ctx)) bad('ctx must be an object');
|
||||
},
|
||||
'rpc-res': (frame, bad) => {
|
||||
if (!isString(frame.id)) bad('id must be a string');
|
||||
if (typeof frame.ok !== 'boolean') bad('ok must be a boolean');
|
||||
if (frame.ok === false && !isObject(frame.error)) bad('error must be an object when ok is false');
|
||||
},
|
||||
ping: () => {
|
||||
/* the tag is the whole frame */
|
||||
},
|
||||
pong: () => {
|
||||
/* the tag is the whole frame */
|
||||
},
|
||||
};
|
||||
|
||||
/** Serialize a frame to a JSON wire string. */
|
||||
export function encode(frame: Frame): string {
|
||||
return JSON.stringify(frame);
|
||||
}
|
||||
|
||||
export function decode(s: string): Frame {
|
||||
const f = JSON.parse(s) as { type?: unknown };
|
||||
if (typeof f.type !== 'string' || !TYPES.has(f.type)) {
|
||||
throw new Error(`unknown frame type: ${String(f.type)}`);
|
||||
}
|
||||
return f as Frame;
|
||||
/** Parse a wire string into a frame, throwing if the `type` tag is unknown or the shape is malformed. */
|
||||
export function decode(json: string): Frame {
|
||||
const parsed = JSON.parse(json) as Record<string, unknown>;
|
||||
const type = parsed.type;
|
||||
// own-property check, not a bare lookup: `type` is peer-controlled, and SHAPE['constructor']
|
||||
// would otherwise resolve up the prototype chain to a truthy non-check.
|
||||
const known = isString(type) && Object.prototype.hasOwnProperty.call(SHAPE, type);
|
||||
const check = known ? SHAPE[type as Frame['type']] : undefined;
|
||||
|
||||
if (!check) throw new Error(`unknown frame type: ${String(type)}`);
|
||||
|
||||
check(parsed, (why) => {
|
||||
throw new Error(`malformed ${String(type)} frame: ${why}`);
|
||||
});
|
||||
|
||||
return parsed as unknown as Frame;
|
||||
}
|
||||
+27
-11
@@ -2,9 +2,19 @@ import type { Link } from './link';
|
||||
import type { RequestEnvelope } from './protocol';
|
||||
import type { ResponseShape } from '../pipeline';
|
||||
|
||||
export interface RemoteScopeNode { name: string; run: (ctx: any) => Promise<Record<string, unknown>> }
|
||||
export interface RemoteRoute { method: string; pattern: string; handler: (req: RequestEnvelope) => Promise<ResponseShape> }
|
||||
/** Local proxy for a remote scope: runs the RPC and returns its token→value binding. */
|
||||
export interface RemoteScopeNode {
|
||||
name: string;
|
||||
run: (ctx: any) => Promise<Record<string, unknown>>;
|
||||
}
|
||||
/** Local proxy for a remote route: forwards the request envelope over the link. */
|
||||
export interface RemoteRoute {
|
||||
method: string;
|
||||
pattern: string;
|
||||
handler: (req: RequestEnvelope) => Promise<ResponseShape>;
|
||||
}
|
||||
|
||||
/** Extract a {@link RequestEnvelope} from a local request context for transmission over the mesh. */
|
||||
export function envelopeFrom(ctx: any): RequestEnvelope {
|
||||
return {
|
||||
method: ctx?.req?.method ?? ctx?.method ?? 'GET',
|
||||
@@ -15,21 +25,27 @@ export function envelopeFrom(ctx: any): RequestEnvelope {
|
||||
};
|
||||
}
|
||||
|
||||
export function buildRemote(link: Link, origin: string): {
|
||||
providers: RemoteScopeNode[]; steps: RemoteScopeNode[]; routes: RemoteRoute[];
|
||||
/** Turn a link's manifest into local proxy nodes: app-scope providers, request-scope steps, and routes. */
|
||||
export function buildRemote(link: Link): {
|
||||
providers: RemoteScopeNode[];
|
||||
steps: RemoteScopeNode[];
|
||||
routes: RemoteRoute[];
|
||||
} {
|
||||
const providers: RemoteScopeNode[] = [];
|
||||
const steps: RemoteScopeNode[] = [];
|
||||
for (const s of link.manifest.scopes) {
|
||||
|
||||
for (const scope of link.manifest.scopes) {
|
||||
const node: RemoteScopeNode = {
|
||||
name: s.token,
|
||||
run: async (ctx: any) => ({ [s.token]: await link.rpc('scope', s.token, envelopeFrom(ctx)) }),
|
||||
name: scope.token,
|
||||
run: async (ctx: any) => ({ [scope.token]: await link.rpc('scope', scope.token, envelopeFrom(ctx)) }),
|
||||
};
|
||||
(s.scope === 'app' ? providers : steps).push(node);
|
||||
(scope.scope === 'app' ? providers : steps).push(node);
|
||||
}
|
||||
const routes: RemoteRoute[] = link.manifest.routes.map((r) => ({
|
||||
method: r.method, pattern: r.pattern,
|
||||
handler: async (req: RequestEnvelope) => (await link.rpc('route', r.pattern, req)) as ResponseShape,
|
||||
|
||||
const routes: RemoteRoute[] = link.manifest.routes.map((route) => ({
|
||||
method: route.method,
|
||||
pattern: route.pattern,
|
||||
handler: async (req: RequestEnvelope) => (await link.rpc('route', route.pattern, req)) as ResponseShape,
|
||||
}));
|
||||
return { providers, steps, routes };
|
||||
}
|
||||
+174
-46
@@ -1,11 +1,25 @@
|
||||
import crypto from 'crypto';
|
||||
// node: prefix, not a bare specifier: this is the mesh auth path, and on Deno/Bun a bare
|
||||
// 'crypto' leans on node-compat resolution heuristics. Buffer + timingSafeEqual resolve
|
||||
// under node-compat on both; edge/workerd is out of scope (see the cross-runtime spec).
|
||||
import crypto from 'node:crypto';
|
||||
import type { Bus } from '../bus';
|
||||
import type { WsSocket } from '../http/ws-core';
|
||||
import type { ResponseShape } from '../pipeline';
|
||||
import { isHttpError } from '../signals';
|
||||
import { encode, decode, type Manifest, type RequestEnvelope, type RouteEntry, type Frame } from './protocol';
|
||||
import {
|
||||
encode,
|
||||
decode,
|
||||
MESH_PROTOCOL_VERSION,
|
||||
type Manifest,
|
||||
type RequestEnvelope,
|
||||
type RouteEntry,
|
||||
type Frame,
|
||||
} from './protocol';
|
||||
|
||||
/** WebSocket path where a teapot exposes its mesh control channel. */
|
||||
export const MESH_CONTROL_PATH = '/__mesh__/control';
|
||||
|
||||
/** Assemble a {@link Manifest} from exported provider/step tokens and buffered routes. */
|
||||
export function buildManifest(args: {
|
||||
providers: string[]; // exported provider tokens (app-scope)
|
||||
steps: string[]; // exported step tokens (request-scope)
|
||||
@@ -20,13 +34,14 @@ export function buildManifest(args: {
|
||||
};
|
||||
}
|
||||
|
||||
function safeEqual(a: string, b: string): boolean {
|
||||
const ba = Buffer.from(a);
|
||||
const bb = Buffer.from(b);
|
||||
if (ba.length !== bb.length) return false;
|
||||
return crypto.timingSafeEqual(ba, bb);
|
||||
function safeEqual(left: string, right: string): boolean {
|
||||
const leftBuf = Buffer.from(left);
|
||||
const rightBuf = Buffer.from(right);
|
||||
if (leftBuf.length !== rightBuf.length) return false;
|
||||
return crypto.timingSafeEqual(leftBuf, rightBuf);
|
||||
}
|
||||
|
||||
/** Dependencies for the mesh control handler: shared secret, manifest, and scope/route resolvers. */
|
||||
export interface MeshControlDeps {
|
||||
secret: string;
|
||||
manifest: Manifest;
|
||||
@@ -35,48 +50,161 @@ export interface MeshControlDeps {
|
||||
bus?: Bus;
|
||||
}
|
||||
|
||||
export function createMeshControl(deps: MeshControlDeps): { path: string; handle: (ws: any) => void } {
|
||||
const exportedScopes = new Set(deps.manifest.scopes.map((s) => s.token));
|
||||
const exportedRoutes = new Set(deps.manifest.routes.map((r) => `${r.method} ${r.pattern}`));
|
||||
/** The rpc-req member of the {@link Frame} union. */
|
||||
type RpcReqFrame = Extract<Frame, { type: 'rpc-req' }>;
|
||||
|
||||
/** Build a 403 "not exported" error for an unknown scope/route token. */
|
||||
function notExported(name: string): Error {
|
||||
const error: any = new Error(`not exported: ${name}`);
|
||||
error.status = 403;
|
||||
|
||||
return error;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an unauthenticated hello frame; reply with the manifest on success or close on mismatch.
|
||||
* The version is checked *before* the secret: a skewed peer is not an auth failure, and telling it
|
||||
* "wrong secret" would send its operator hunting the wrong bug.
|
||||
*/
|
||||
function handleHandshake(socket: WsSocket, frame: Frame, deps: MeshControlDeps): boolean {
|
||||
if (frame.type !== 'hello') {
|
||||
socket.close(1008);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (frame.v !== MESH_PROTOCOL_VERSION) {
|
||||
socket.close(
|
||||
1008,
|
||||
`mesh protocol version mismatch: peer speaks v${frame.v}, this teapot speaks v${MESH_PROTOCOL_VERSION}`,
|
||||
);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!safeEqual(frame.secret, deps.secret)) {
|
||||
socket.close(1008);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
socket.send(
|
||||
encode({
|
||||
type: 'manifest',
|
||||
v: MESH_PROTOCOL_VERSION,
|
||||
scopes: deps.manifest.scopes,
|
||||
routes: deps.manifest.routes,
|
||||
}),
|
||||
);
|
||||
deps.bus?.emit('mesh:connect', { name: 'teapot' });
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Resolve an authenticated rpc-req against the exported scopes/routes, enforcing export gating. */
|
||||
function resolveRpc(
|
||||
frame: RpcReqFrame,
|
||||
deps: MeshControlDeps,
|
||||
exportedScopes: Set<string>,
|
||||
exportedRoutes: Set<string>,
|
||||
): Promise<unknown> {
|
||||
const { kind, name, ctx } = frame;
|
||||
|
||||
if (kind === 'scope') {
|
||||
if (!exportedScopes.has(name)) throw notExported(name);
|
||||
|
||||
return deps.resolveScope(name, ctx);
|
||||
}
|
||||
|
||||
if (![...exportedRoutes].some((key) => key.endsWith(` ${name}`))) throw notExported(name);
|
||||
|
||||
return deps.resolveRoute(name, ctx);
|
||||
}
|
||||
|
||||
/** Serve one authenticated rpc-req: resolve it and frame the ok/error response back to the peer. */
|
||||
async function handleRpc(
|
||||
socket: WsSocket,
|
||||
frame: RpcReqFrame,
|
||||
deps: MeshControlDeps,
|
||||
exportedScopes: Set<string>,
|
||||
exportedRoutes: Set<string>,
|
||||
): Promise<void> {
|
||||
const { id, name } = frame;
|
||||
|
||||
try {
|
||||
const result = await resolveRpc(frame, deps, exportedScopes, exportedRoutes);
|
||||
|
||||
socket.send(encode({ type: 'rpc-res', id, ok: true, result }));
|
||||
} catch (err) {
|
||||
const status = isHttpError(err) ? err.status : ((err as any)?.status ?? 500);
|
||||
|
||||
deps.bus?.emit('mesh:rpc:error', { name, error: err });
|
||||
socket.send(encode({ type: 'rpc-res', id, ok: false, error: { message: (err as Error).message, status } }));
|
||||
}
|
||||
}
|
||||
|
||||
/** Drive one control connection to completion: handshake, then serve RPCs until the socket ends. */
|
||||
async function serveFrames(
|
||||
socket: WsSocket,
|
||||
deps: MeshControlDeps,
|
||||
exportedScopes: Set<string>,
|
||||
exportedRoutes: Set<string>,
|
||||
): Promise<void> {
|
||||
let authed = false;
|
||||
|
||||
try {
|
||||
for await (const data of socket.inbound) {
|
||||
let frame: Frame;
|
||||
|
||||
try {
|
||||
frame = decode(String(data));
|
||||
} catch {
|
||||
continue; // undecodable frames are ignored, as before
|
||||
}
|
||||
|
||||
if (!authed) {
|
||||
authed = handleHandshake(socket, frame, deps);
|
||||
continue;
|
||||
}
|
||||
|
||||
// answered only after the handshake: an unauthenticated peer gets no signal at all
|
||||
if (frame.type === 'ping') {
|
||||
socket.send(encode({ type: 'pong' }));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (frame.type !== 'rpc-req') continue;
|
||||
|
||||
// deliberately not awaited: RPCs overlap, exactly as they did under the `ws.on('message')`
|
||||
// listener. The id-keyed `pending` map on the peer exists to allow in-flight concurrency —
|
||||
// awaiting here would silently serialize every mesh call.
|
||||
void handleRpc(socket, frame, deps, exportedScopes, exportedRoutes);
|
||||
}
|
||||
} catch {
|
||||
/* socket failed; the disconnect emit below is the same signal a clean close gives */
|
||||
} finally {
|
||||
deps.bus?.emit('mesh:disconnect', { name: 'teapot' });
|
||||
}
|
||||
}
|
||||
|
||||
/** Build a control handler that authenticates peers and serves scope/route RPCs from the manifest. */
|
||||
export function createMeshControl(deps: MeshControlDeps): {
|
||||
path: string;
|
||||
handle: (socket: WsSocket) => Promise<void>;
|
||||
} {
|
||||
const exportedScopes = new Set(deps.manifest.scopes.map((scope) => scope.token));
|
||||
const exportedRoutes = new Set(deps.manifest.routes.map((route) => `${route.method} ${route.pattern}`));
|
||||
|
||||
return {
|
||||
path: MESH_CONTROL_PATH,
|
||||
handle(ws: any) {
|
||||
let authed = false;
|
||||
ws.on('message', async (data: unknown) => {
|
||||
let frame: Frame;
|
||||
try { frame = decode(String(data)); } catch { return; }
|
||||
|
||||
if (!authed) {
|
||||
if (frame.type === 'hello' && safeEqual(frame.secret, deps.secret)) {
|
||||
authed = true;
|
||||
ws.send(encode({ type: 'manifest', scopes: deps.manifest.scopes, routes: deps.manifest.routes }));
|
||||
deps.bus?.emit('mesh:connect', { name: 'teapot' });
|
||||
} else {
|
||||
ws.close(1008);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (frame.type !== 'rpc-req') return;
|
||||
const { id, kind, name, ctx } = frame;
|
||||
try {
|
||||
let result: unknown;
|
||||
if (kind === 'scope') {
|
||||
if (!exportedScopes.has(name)) { const e: any = new Error(`not exported: ${name}`); e.status = 403; throw e; }
|
||||
result = await deps.resolveScope(name, ctx);
|
||||
} else {
|
||||
if (![...exportedRoutes].some((k) => k.endsWith(` ${name}`))) { const e: any = new Error(`not exported: ${name}`); e.status = 403; throw e; }
|
||||
result = await deps.resolveRoute(name, ctx);
|
||||
}
|
||||
ws.send(encode({ type: 'rpc-res', id, ok: true, result }));
|
||||
} catch (err) {
|
||||
const status = isHttpError(err) ? err.status : (err as any)?.status ?? 500;
|
||||
deps.bus?.emit('mesh:rpc:error', { name, error: err });
|
||||
ws.send(encode({ type: 'rpc-res', id, ok: false, error: { message: (err as Error).message, status } }));
|
||||
}
|
||||
});
|
||||
ws.on('close', () => deps.bus?.emit('mesh:disconnect', { name: 'teapot' }));
|
||||
/**
|
||||
* Resolves when the connection ends, mirroring `runWsConnection` — so `app.upgrade` can await
|
||||
* the control channel's lifetime the same way it awaits a regular ws route's.
|
||||
* `channel` is fan-out and subscribes when the async iterator is created, which `for await`
|
||||
* does synchronously, so the loop is live before any frame can arrive.
|
||||
*/
|
||||
handle(socket: WsSocket): Promise<void> {
|
||||
return serveFrames(socket, deps, exportedScopes, exportedRoutes);
|
||||
},
|
||||
};
|
||||
}
|
||||
+144
-16
@@ -1,15 +1,50 @@
|
||||
import 'reflect-metadata';
|
||||
|
||||
/** Any class constructor. Kept `any` because decorators must accept every target shape. */
|
||||
export type Ctor = new (...args: any[]) => any;
|
||||
/** Serializes a handler's return value into an HTTP response envelope. */
|
||||
export type TransformerFn = (value: unknown) => { status?: number; headers?: Record<string, string>; body: string };
|
||||
|
||||
export interface ProviderMeta { provides: string; needs: string[]; optional: boolean; export: boolean }
|
||||
export interface StepMeta { provides: string; needs: string[]; optional: boolean; export: boolean }
|
||||
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
||||
/** Metadata attached by `@Html`: optional file path and whether it is a template. */
|
||||
export interface HtmlMeta {
|
||||
path?: string;
|
||||
template?: boolean;
|
||||
}
|
||||
/** Metadata attached by `@Provider`: what it provides, what it needs, and its visibility. */
|
||||
export interface ProviderMeta {
|
||||
provides: string;
|
||||
needs: string[];
|
||||
optional: boolean;
|
||||
export: boolean;
|
||||
}
|
||||
/** Metadata attached by `@Step`: what it provides, what it needs, and its visibility. */
|
||||
export interface StepMeta {
|
||||
provides: string;
|
||||
needs: string[];
|
||||
optional: boolean;
|
||||
export: boolean;
|
||||
}
|
||||
/** HTTP verbs supported by the route decorators. */
|
||||
export type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS';
|
||||
/** Wire transport a route responds with. */
|
||||
export type Transport = 'buffer' | 'sse' | 'ndjson' | 'negotiate' | 'ws';
|
||||
export interface RouteMeta { method: HttpMethod; path: string; handlerName: string; transport: Transport; export: boolean }
|
||||
/** Metadata attached by a route decorator to a single handler method. */
|
||||
export interface RouteMeta {
|
||||
method: HttpMethod;
|
||||
path: string;
|
||||
handlerName: string;
|
||||
transport: Transport;
|
||||
export: boolean;
|
||||
duplicates?: 'array' | 'last';
|
||||
maxBodyBytes?: number;
|
||||
maxParts?: number;
|
||||
}
|
||||
/** Options accepted by the `@Module` decorator. */
|
||||
export interface ModuleOptions {
|
||||
mountpoint: string; providers?: Ctor[]; steps?: Ctor[]; controllers?: Ctor[];
|
||||
mountpoint: string;
|
||||
providers?: Ctor[];
|
||||
steps?: Ctor[];
|
||||
controllers?: Ctor[];
|
||||
}
|
||||
|
||||
const K = {
|
||||
@@ -19,73 +54,166 @@ const K = {
|
||||
routes: Symbol('gt:routes'),
|
||||
module: Symbol('gt:module'),
|
||||
transformer: Symbol('gt:transformer'),
|
||||
html: Symbol('gt:html'),
|
||||
};
|
||||
|
||||
export function Provider(opts: { provides: string; needs?: string[]; optional?: boolean; export?: boolean }): ClassDecorator {
|
||||
/** Marks a class as a provider: a lazily-built dependency addressable by its `provides` key. */
|
||||
export function Provider(opts: {
|
||||
provides: string;
|
||||
needs?: string[];
|
||||
optional?: boolean;
|
||||
export?: boolean;
|
||||
}): ClassDecorator {
|
||||
return (target) => {
|
||||
const meta: ProviderMeta = { provides: opts.provides, needs: opts.needs ?? [], optional: opts.optional ?? false, export: opts.export ?? false };
|
||||
const meta: ProviderMeta = {
|
||||
provides: opts.provides,
|
||||
needs: opts.needs ?? [],
|
||||
optional: opts.optional ?? false,
|
||||
export: opts.export ?? false,
|
||||
};
|
||||
Reflect.defineMetadata(K.provider, meta, target);
|
||||
};
|
||||
}
|
||||
|
||||
export function Step(opts: { provides: string; needs?: string[]; optional?: boolean; export?: boolean }): ClassDecorator {
|
||||
/** Marks a class as a step: a per-request unit that runs in dependency order and contributes to the context. */
|
||||
export function Step(opts: {
|
||||
provides: string;
|
||||
needs?: string[];
|
||||
optional?: boolean;
|
||||
export?: boolean;
|
||||
}): ClassDecorator {
|
||||
return (target) => {
|
||||
const meta: StepMeta = { provides: opts.provides, needs: opts.needs ?? [], optional: opts.optional ?? false, export: opts.export ?? false };
|
||||
const meta: StepMeta = {
|
||||
provides: opts.provides,
|
||||
needs: opts.needs ?? [],
|
||||
optional: opts.optional ?? false,
|
||||
export: opts.export ?? false,
|
||||
};
|
||||
Reflect.defineMetadata(K.step, meta, target);
|
||||
};
|
||||
}
|
||||
|
||||
/** Sets the shared path prefix for every route declared on the decorated controller. */
|
||||
export function Route(prefix: string): ClassDecorator {
|
||||
return (target) => { Reflect.defineMetadata(K.routePrefix, prefix, target); };
|
||||
return (target) => {
|
||||
Reflect.defineMetadata(K.routePrefix, prefix, target);
|
||||
};
|
||||
}
|
||||
|
||||
function routeDecorator(method: HttpMethod, transport: Transport) {
|
||||
return (path: string, opts?: { export?: boolean }): MethodDecorator =>
|
||||
return (
|
||||
path: string,
|
||||
opts?: { export?: boolean; duplicates?: 'array' | 'last'; maxBodyBytes?: number; maxParts?: number },
|
||||
): MethodDecorator =>
|
||||
(target, propertyKey) => {
|
||||
const ctor = target.constructor;
|
||||
const routes = (Reflect.getMetadata(K.routes, ctor) as RouteMeta[]) ?? [];
|
||||
routes.push({ method, path, handlerName: String(propertyKey), transport, export: opts?.export ?? false });
|
||||
routes.push({
|
||||
method,
|
||||
path,
|
||||
handlerName: String(propertyKey),
|
||||
transport,
|
||||
export: opts?.export ?? false,
|
||||
duplicates: opts?.duplicates,
|
||||
maxBodyBytes: opts?.maxBodyBytes,
|
||||
maxParts: opts?.maxParts,
|
||||
});
|
||||
Reflect.defineMetadata(K.routes, routes, ctor);
|
||||
};
|
||||
}
|
||||
|
||||
/** Declares a buffered `GET` route. */
|
||||
export const Get = routeDecorator('GET', 'buffer');
|
||||
/** Declares a buffered `HEAD` route. */
|
||||
export const Head = routeDecorator('HEAD', 'buffer');
|
||||
/** Declares a buffered `POST` route. */
|
||||
export const Post = routeDecorator('POST', 'buffer');
|
||||
/** Declares a buffered `PUT` route. */
|
||||
export const Put = routeDecorator('PUT', 'buffer');
|
||||
/** Declares a buffered `PATCH` route. */
|
||||
export const Patch = routeDecorator('PATCH', 'buffer');
|
||||
/** Declares a buffered `DELETE` route. */
|
||||
export const Delete = routeDecorator('DELETE', 'buffer');
|
||||
/** Declares a buffered `OPTIONS` route. */
|
||||
export const Options = routeDecorator('OPTIONS', 'buffer');
|
||||
/** Declares a `GET` route streamed as Server-Sent Events. */
|
||||
export const Sse = routeDecorator('GET', 'sse');
|
||||
/** Declares a `GET` route whose transport is content-negotiated at request time. */
|
||||
export const Stream = routeDecorator('GET', 'negotiate');
|
||||
/** Declares a `GET` route upgraded to a WebSocket. */
|
||||
export const Ws = routeDecorator('GET', 'ws');
|
||||
|
||||
/** Attaches a response transformer to a handler method. */
|
||||
export function Transformer(fn: TransformerFn): MethodDecorator {
|
||||
return (target, propertyKey) => {
|
||||
Reflect.defineMetadata(K.transformer, fn, target.constructor, String(propertyKey));
|
||||
};
|
||||
}
|
||||
|
||||
/** Marks a class as a module and records its providers, steps, controllers, and mountpoint. */
|
||||
export function Module(opts: ModuleOptions): ClassDecorator {
|
||||
return (target) => { Reflect.defineMetadata(K.module, opts, target); };
|
||||
return (target) => {
|
||||
Reflect.defineMetadata(K.module, opts, target);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks a buffered GET/POST handler as serving HTML. Bare `@Html` sends the handler's string return as
|
||||
* `text/html`. `@Html('file.html')` serves that file (return ignored). `@Html('file.html', { template: true })`
|
||||
* renders the file with the handler's returned data. Placement is validated at boot (buffered GET/POST only).
|
||||
*/
|
||||
export function Html(path: string, opts?: { template?: boolean }): MethodDecorator;
|
||||
export function Html(target: object, propertyKey: string | symbol): void;
|
||||
|
||||
export function Html(a: unknown, b?: unknown): MethodDecorator | void {
|
||||
if (typeof a !== 'string') {
|
||||
// Bare usage: TS calls (prototype, propertyKey, descriptor?).
|
||||
Reflect.defineMetadata(K.html, {}, (a as { constructor: Ctor }).constructor, String(b));
|
||||
return;
|
||||
}
|
||||
|
||||
const path = a;
|
||||
const opts = b as { template?: boolean } | undefined;
|
||||
|
||||
return (target, propertyKey) => {
|
||||
const meta: HtmlMeta = { path, template: opts?.template };
|
||||
Reflect.defineMetadata(K.html, meta, (target as { constructor: Ctor }).constructor, String(propertyKey));
|
||||
};
|
||||
}
|
||||
|
||||
/** Reads the `@Html` metadata registered for a handler method, if any. */
|
||||
export function getHtmlMeta(cls: Ctor, methodName: string): HtmlMeta | undefined {
|
||||
return Reflect.getMetadata(K.html, cls, methodName);
|
||||
}
|
||||
|
||||
/** Reads the `@Provider` metadata off a class, if any. */
|
||||
export function getProviderMeta(cls: Ctor): ProviderMeta | undefined {
|
||||
return Reflect.getMetadata(K.provider, cls);
|
||||
}
|
||||
|
||||
/** Reads the `@Step` metadata off a class, if any. */
|
||||
export function getStepMeta(cls: Ctor): StepMeta | undefined {
|
||||
return Reflect.getMetadata(K.step, cls);
|
||||
}
|
||||
|
||||
/** Reads the `@Module` metadata off a class, if any. */
|
||||
export function getModuleMeta(cls: Ctor): ModuleOptions | undefined {
|
||||
return Reflect.getMetadata(K.module, cls);
|
||||
}
|
||||
|
||||
/** Reads the response transformer registered for a handler method, if any. */
|
||||
export function getTransformer(cls: Ctor, methodName: string): TransformerFn | undefined {
|
||||
return Reflect.getMetadata(K.transformer, cls, methodName);
|
||||
}
|
||||
|
||||
/** Returns every route on a controller with its path resolved against the class prefix. */
|
||||
export function getRoutes(cls: Ctor): RouteMeta[] {
|
||||
const prefix: string = Reflect.getMetadata(K.routePrefix, cls) ?? '';
|
||||
const routes: RouteMeta[] = Reflect.getMetadata(K.routes, cls) ?? [];
|
||||
return routes.map((r) => ({ ...r, path: joinPath(prefix, r.path) }));
|
||||
return routes.map((route) => ({ ...route, path: joinPath(prefix, route.path) }));
|
||||
}
|
||||
|
||||
export function joinPath(a: string, b: string): string {
|
||||
return `${a.replace(/\/$/, '')}/${b.replace(/^\//, '')}`.replace(/\/+/g, '/');
|
||||
/** Joins two path segments with exactly one slash, collapsing any duplicates. */
|
||||
export function joinPath(base: string, segment: string): string {
|
||||
return `${base.replace(/\/$/, '')}/${segment.replace(/^\//, '')}`.replace(/\/+/g, '/');
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
// src/multipart.ts — multipart/form-data parsing on top of the optional `busboy` peer dependency.
|
||||
import { Readable } from 'stream';
|
||||
import { HttpError } from './signals';
|
||||
|
||||
/** A single uploaded file part decoded from a multipart body. */
|
||||
export interface UploadedFile {
|
||||
filename: string;
|
||||
contentType: string;
|
||||
data: Buffer;
|
||||
size: number;
|
||||
}
|
||||
|
||||
/** Decoded multipart body: text fields and file uploads, keyed by part name. */
|
||||
export interface MultipartBody {
|
||||
fields: Record<string, string | string[]>;
|
||||
files: Record<string, UploadedFile | UploadedFile[]>;
|
||||
}
|
||||
|
||||
/** Parser limits and duplicate-key policy for {@link parseMultipart}. */
|
||||
export interface MultipartOpts {
|
||||
maxParts: number;
|
||||
duplicates: 'array' | 'last';
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the boundary token from a Content-Type value (supports the quoted form).
|
||||
* @returns The boundary, or undefined when absent.
|
||||
*/
|
||||
export function extractBoundary(contentType: string): string | undefined {
|
||||
const match = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(contentType);
|
||||
const boundary = (match?.[1] ?? match?.[2])?.trim();
|
||||
return boundary || undefined;
|
||||
}
|
||||
|
||||
function addField(fields: MultipartBody['fields'], name: string, value: string, duplicates: 'array' | 'last'): void {
|
||||
if (duplicates === 'array') {
|
||||
const existing = fields[name];
|
||||
if (Array.isArray(existing)) existing.push(value);
|
||||
else fields[name] = [value];
|
||||
} else {
|
||||
fields[name] = value; // last-wins
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Collapses an iterable of [key, value] pairs (e.g. URLSearchParams) into an object,
|
||||
* applying the same duplicate-key policy as multipart fields so urlencoded bodies behave identically.
|
||||
*/
|
||||
export function collapseDuplicates(
|
||||
pairs: Iterable<[string, string]>,
|
||||
duplicates: 'array' | 'last',
|
||||
): Record<string, string | string[]> {
|
||||
const out: Record<string, string | string[]> = {};
|
||||
for (const [key, value] of pairs) addField(out, key, value, duplicates);
|
||||
return out;
|
||||
}
|
||||
|
||||
function addFile(files: MultipartBody['files'], name: string, file: UploadedFile): void {
|
||||
const existing = files[name];
|
||||
if (existing === undefined) files[name] = file;
|
||||
else if (Array.isArray(existing)) existing.push(file);
|
||||
else files[name] = [existing, file];
|
||||
}
|
||||
|
||||
/** Lazily loads the optional `busboy` peer dependency, or null when it is not installed. */
|
||||
function loadBusboy(): ((cfg: unknown) => NodeJS.WritableStream & NodeJS.EventEmitter) | null {
|
||||
try {
|
||||
// `busboy` is an OPTIONAL peer dependency: only multipart uploads need it, so it is
|
||||
// lazy-required and its absence surfaces as a clear 501 rather than a load-time crash.
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
return require('busboy');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a raw multipart/form-data buffer into decoded fields and files, using `busboy`.
|
||||
* @param raw The full (already size-capped) request body.
|
||||
* @param boundary The boundary token (see {@link extractBoundary}).
|
||||
* @throws HttpError 501 when the optional `busboy` peer dependency is not installed.
|
||||
* @throws Error 'Invalid multipart body' on malformed input or when `maxParts` is exceeded.
|
||||
*/
|
||||
export function parseMultipart(raw: Buffer, boundary: string, opts: MultipartOpts): Promise<MultipartBody> {
|
||||
const busboy = loadBusboy();
|
||||
|
||||
if (!busboy) {
|
||||
throw new HttpError(501, 'multipart/form-data requires the optional "busboy" peer dependency — run `npm i busboy`');
|
||||
}
|
||||
|
||||
return new Promise<MultipartBody>((resolve, reject) => {
|
||||
const body: MultipartBody = { fields: {}, files: {} };
|
||||
const fail = () => reject(new Error('Invalid multipart body'));
|
||||
let bb: NodeJS.WritableStream & NodeJS.EventEmitter;
|
||||
|
||||
try {
|
||||
bb = busboy({
|
||||
headers: { 'content-type': `multipart/form-data; boundary=${boundary}` },
|
||||
limits: { parts: opts.maxParts },
|
||||
});
|
||||
} catch {
|
||||
return fail();
|
||||
}
|
||||
|
||||
bb.on('field', (name: string, value: string) => addField(body.fields, name, value, opts.duplicates));
|
||||
|
||||
bb.on('file', (name: string, stream: Readable, info: { filename?: string; mimeType?: string }) => {
|
||||
const chunks: Buffer[] = [];
|
||||
stream.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||
stream.on('close', () => {
|
||||
const data = Buffer.concat(chunks);
|
||||
const filename = info.filename ?? '';
|
||||
if (filename === '' && data.length === 0) return; // unselected file input
|
||||
|
||||
addFile(body.files, name, {
|
||||
filename,
|
||||
contentType: info.mimeType || 'application/octet-stream',
|
||||
data,
|
||||
size: data.length,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
bb.on('partsLimit', fail); // more parts than maxParts → treat as malformed (matches prior behavior)
|
||||
bb.on('error', fail);
|
||||
bb.on('close', () => resolve(body));
|
||||
|
||||
Readable.from(raw).pipe(bb);
|
||||
});
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
import type { ArgSpec } from './params';
|
||||
import type { Transport } from './metadata';
|
||||
import { compilePattern } from './http/router';
|
||||
|
||||
/** Minimal per-route input the OpenAPI projection needs, derived from a route plan. */
|
||||
export interface OpenApiRoute {
|
||||
method: string;
|
||||
pattern: string;
|
||||
transport: Transport;
|
||||
args: ArgSpec[];
|
||||
}
|
||||
|
||||
/** `info` block overrides for the generated document. */
|
||||
export interface OpenApiInfo {
|
||||
title?: string;
|
||||
version?: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
/** A generated OpenAPI 3.1 document (structural: paths, params, and error responses; body/response schemas are generic). */
|
||||
export interface OpenApiDoc {
|
||||
openapi: string;
|
||||
info: { title: string; version: string; description?: string };
|
||||
paths: Record<string, Record<string, unknown>>;
|
||||
}
|
||||
|
||||
type Parameter = {
|
||||
name: string;
|
||||
in: 'path' | 'query' | 'header';
|
||||
required: boolean;
|
||||
schema: { type: 'string'; pattern?: string };
|
||||
};
|
||||
|
||||
/** Converts a route pattern to an OpenAPI path template: `/users/:id` → `/users/{id}`, `:rest*` → `{rest}`. */
|
||||
function templatePath(pattern: string): string {
|
||||
const segments = compilePattern(pattern).segments.map((segment) =>
|
||||
segment.kind === 'static' ? segment.value : `{${segment.name}}`,
|
||||
);
|
||||
return `/${segments.join('/')}`;
|
||||
}
|
||||
|
||||
/** Every `:name` (and `:name*`) segment of a pattern becomes a required path parameter. */
|
||||
function pathParams(pattern: string): Parameter[] {
|
||||
return compilePattern(pattern).segments.flatMap((segment): Parameter[] => {
|
||||
if (segment.kind === 'static') return [];
|
||||
return [
|
||||
{
|
||||
name: segment.name,
|
||||
in: 'path',
|
||||
required: true,
|
||||
schema: {
|
||||
type: 'string',
|
||||
...(segment.kind === 'param' && segment.constraintSource ? { pattern: segment.constraintSource } : {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
/** Query and header parameters declared by the handler's `@query` / `@headers` / `@header` argument decorators. */
|
||||
function argParams(args: ArgSpec[]): Parameter[] {
|
||||
const params: Parameter[] = [];
|
||||
|
||||
for (const arg of args) {
|
||||
if (arg.source !== 'query' && arg.source !== 'headers') continue;
|
||||
const location = arg.source === 'query' ? 'query' : 'header';
|
||||
const names = arg.keys ?? (arg.key ? [arg.key] : []);
|
||||
for (const name of names) params.push({ name, in: location, required: false, schema: { type: 'string' } });
|
||||
}
|
||||
|
||||
return params;
|
||||
}
|
||||
|
||||
/**
|
||||
* The documented `200` per transport. `ws` is absent by construction — ws routes are not
|
||||
* HTTP request/response and are filtered out before this runs. A new transport adds a row,
|
||||
* and the compiler fails until it does.
|
||||
*/
|
||||
type HttpTransport = Exclude<Transport, 'ws'>;
|
||||
|
||||
const TRANSPORT_OK: Record<HttpTransport, Record<string, unknown>> = {
|
||||
buffer: { description: 'OK', content: { 'application/json': { schema: {} } } },
|
||||
sse: { description: 'Event stream', content: { 'text/event-stream': {} } },
|
||||
ndjson: { description: 'Stream', content: { 'application/x-ndjson': {} } },
|
||||
negotiate: { description: 'Stream', content: { 'application/x-ndjson': {} } },
|
||||
};
|
||||
|
||||
/** The success/error responses documented for a route, keyed by transport and whether any input is validated. */
|
||||
function responses(route: OpenApiRoute, transport: HttpTransport): Record<string, unknown> {
|
||||
const result: Record<string, unknown> = { '200': TRANSPORT_OK[transport] };
|
||||
|
||||
if (route.args.some((arg) => arg.schema)) result['422'] = { description: 'Validation failed' };
|
||||
result['500'] = { description: 'Internal Server Error' };
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Builds a single OpenAPI operation object for a route. */
|
||||
function operation(route: OpenApiRoute, transport: HttpTransport): Record<string, unknown> {
|
||||
const parameters = [...pathParams(route.pattern), ...argParams(route.args)];
|
||||
const op: Record<string, unknown> = { responses: responses(route, transport) };
|
||||
|
||||
if (parameters.length) op.parameters = parameters;
|
||||
|
||||
if (route.args.some((arg) => arg.source === 'body')) {
|
||||
op.requestBody = { content: { 'application/json': { schema: {} } } };
|
||||
}
|
||||
|
||||
return op;
|
||||
}
|
||||
|
||||
/**
|
||||
* Projects the route graph into a structural OpenAPI 3.1 document: paths, methods, path/query/header
|
||||
* parameters, which routes take a body, and the systematic error responses. Body and response *schemas*
|
||||
* are generic — Standard Schema doesn't expose JSON Schema (see the roadmap). WebSocket routes are omitted.
|
||||
*/
|
||||
export function buildOpenApi(routes: OpenApiRoute[], info?: OpenApiInfo): OpenApiDoc {
|
||||
const paths: Record<string, Record<string, unknown>> = {};
|
||||
|
||||
for (const route of routes) {
|
||||
const transport = route.transport;
|
||||
if (transport === 'ws') continue; // not an HTTP request/response; narrows to HttpTransport below
|
||||
const path = templatePath(route.pattern);
|
||||
(paths[path] ??= {})[route.method.toLowerCase()] = operation(route, transport);
|
||||
}
|
||||
|
||||
return {
|
||||
openapi: '3.1.0',
|
||||
info: {
|
||||
title: info?.title ?? 'green-tea API',
|
||||
version: info?.version ?? '0.0.0',
|
||||
...(info?.description ? { description: info.description } : {}),
|
||||
},
|
||||
paths,
|
||||
};
|
||||
}
|
||||
+70
-25
@@ -1,12 +1,24 @@
|
||||
import 'reflect-metadata';
|
||||
import type { Ctor } from './metadata';
|
||||
import { isStandardSchema, type StandardSchemaV1 } from './standard-schema';
|
||||
import { ValidationError } from './signals';
|
||||
|
||||
/** Parsed URL query string as flat key/value pairs. */
|
||||
export type Query = Record<string, string>;
|
||||
/** Incoming request headers; a header may repeat, hence the array variant. */
|
||||
export type Headers = Record<string, string | string[] | undefined>;
|
||||
/** Per-request bag that accumulates values produced by steps and providers. */
|
||||
export type Context = Record<string, unknown>;
|
||||
|
||||
type ArgSource = 'ctx' | 'needs' | 'params' | 'query' | 'body' | 'headers' | 'inbound' | 'abort';
|
||||
export interface ArgSpec { index: number; source: ArgSource; key?: string; keys?: string[] }
|
||||
/** Describes how a single handler parameter is sourced and (optionally) validated. */
|
||||
export interface ArgSpec {
|
||||
index: number;
|
||||
source: ArgSource;
|
||||
key?: string;
|
||||
keys?: string[];
|
||||
schema?: StandardSchemaV1;
|
||||
}
|
||||
|
||||
const ARGS = Symbol('gt:args');
|
||||
|
||||
@@ -21,68 +33,101 @@ function record(target: object, methodKey: string | symbol | undefined, spec: Ar
|
||||
}
|
||||
|
||||
function envelope(source: ArgSource) {
|
||||
return (arg?: string | string[]): ParameterDecorator =>
|
||||
return (arg?: string | string[] | StandardSchemaV1, schema?: StandardSchemaV1): ParameterDecorator =>
|
||||
(target, methodKey, index) => {
|
||||
const spec: ArgSpec = Array.isArray(arg)
|
||||
? { index, source, keys: arg }
|
||||
: typeof arg === 'string'
|
||||
? { index, source, key: arg }
|
||||
: { index, source };
|
||||
const spec: ArgSpec = { index, source };
|
||||
if (Array.isArray(arg)) spec.keys = arg;
|
||||
else if (typeof arg === 'string') spec.key = arg;
|
||||
else if (isStandardSchema(arg)) spec.schema = arg;
|
||||
else if (arg !== undefined) throw new Error(`@${source}: expected a Standard Schema or a string/array key`);
|
||||
|
||||
if (schema !== undefined) {
|
||||
if (!isStandardSchema(schema)) throw new Error(`@${source}: second argument must be a Standard Schema`);
|
||||
spec.schema = schema;
|
||||
}
|
||||
|
||||
record(target, methodKey, spec);
|
||||
};
|
||||
}
|
||||
|
||||
/** Inject a route path parameter; pass a key to pick one, or a schema/array to shape it. */
|
||||
export const param = envelope('params');
|
||||
/** Inject a query-string value; pass a key to pick one, or a schema/array to shape it. */
|
||||
export const query = envelope('query');
|
||||
/** Inject the request body; pass a schema to validate it. */
|
||||
export const body = envelope('body');
|
||||
/** Inject request headers; pass a key to pick one, an array to pick several, or no arg for the whole bag. */
|
||||
export const headers = envelope('headers');
|
||||
/** Inject a single request header by name (singular alias of {@link headers}); accepts a schema to validate it. */
|
||||
export const header = envelope('headers');
|
||||
|
||||
/** Inject a value produced upstream by a step or provider, addressed by key. */
|
||||
export function needs(key: string): ParameterDecorator {
|
||||
return (target, methodKey, index) => record(target, methodKey, { index, source: 'needs', key });
|
||||
}
|
||||
|
||||
/** Inject the whole request context bag. */
|
||||
export function ctx(): ParameterDecorator {
|
||||
return (target, methodKey, index) => record(target, methodKey, { index, source: 'ctx' });
|
||||
}
|
||||
|
||||
/** Inject the inbound stream (for streaming/upload handlers). */
|
||||
export function inbound(): ParameterDecorator {
|
||||
return (target, methodKey, index) => record(target, methodKey, { index, source: 'inbound' });
|
||||
}
|
||||
|
||||
/** Inject the request's abort signal. */
|
||||
export function abort(): ParameterDecorator {
|
||||
return (target, methodKey, index) => record(target, methodKey, { index, source: 'abort' });
|
||||
}
|
||||
|
||||
/** Read the recorded parameter specs for a handler method, ordered by parameter index. */
|
||||
export function getArgs(cls: Ctor, methodName: string): ArgSpec[] {
|
||||
const map: Record<string, ArgSpec[]> = Reflect.getMetadata(ARGS, cls) ?? {};
|
||||
return [...(map[methodName] ?? [])].sort((a, b) => a.index - b.index);
|
||||
}
|
||||
|
||||
/** Extract the `@needs` keys a handler depends on, for dependency resolution. */
|
||||
export function getHandlerNeeds(specs: ArgSpec[]): string[] {
|
||||
return specs.filter((s) => s.source === 'needs' && s.key).map((s) => s.key as string);
|
||||
return specs.filter((spec) => spec.source === 'needs' && spec.key).map((spec) => spec.key as string);
|
||||
}
|
||||
|
||||
export function resolveArgs(specs: ArgSpec[], context: Context): unknown[] {
|
||||
/** Build the positional argument array for a handler by sourcing and validating each spec. */
|
||||
export async function resolveArgs(specs: ArgSpec[], context: Context): Promise<unknown[]> {
|
||||
if (specs.length === 0) return [];
|
||||
const max = Math.max(...specs.map((s) => s.index));
|
||||
const args: unknown[] = new Array(max + 1).fill(undefined);
|
||||
for (const s of specs) args[s.index] = resolveOne(s, context);
|
||||
const maxIndex = Math.max(...specs.map((spec) => spec.index));
|
||||
const args: unknown[] = new Array(maxIndex + 1).fill(undefined);
|
||||
|
||||
for (const spec of specs) {
|
||||
let value = resolveOne(spec, context);
|
||||
|
||||
if (spec.schema) {
|
||||
const result = await spec.schema['~standard'].validate(value);
|
||||
if (result.issues) throw new ValidationError([...result.issues], spec.source);
|
||||
value = result.value;
|
||||
}
|
||||
|
||||
args[spec.index] = value;
|
||||
}
|
||||
|
||||
return args;
|
||||
}
|
||||
|
||||
function resolveOne(s: ArgSpec, context: Context): unknown {
|
||||
if (s.source === 'ctx') return context;
|
||||
if (s.source === 'needs') return context[s.key as string];
|
||||
if (s.source === 'inbound') return context.inbound;
|
||||
if (s.source === 'abort') return context.abort;
|
||||
const bag = context[s.source];
|
||||
function resolveOne(spec: ArgSpec, context: Context): unknown {
|
||||
if (spec.source === 'ctx') return context;
|
||||
if (spec.source === 'needs') return context[spec.key as string];
|
||||
if (spec.source === 'inbound') return context.inbound;
|
||||
if (spec.source === 'abort') return context.abort;
|
||||
const bag = context[spec.source];
|
||||
if (typeof bag !== 'object' || bag === null) return bag; // can't pick from a non-object; return as-is
|
||||
const record = bag as Record<string, unknown>;
|
||||
if (s.keys) {
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const k of s.keys) out[k] = record[k];
|
||||
return out;
|
||||
const values = bag as Record<string, unknown>;
|
||||
|
||||
if (spec.keys) {
|
||||
const picked: Record<string, unknown> = {};
|
||||
for (const key of spec.keys) picked[key] = values[key];
|
||||
return picked;
|
||||
}
|
||||
if (s.key !== undefined) return record[s.key];
|
||||
return record;
|
||||
|
||||
if (spec.key !== undefined) return values[spec.key];
|
||||
return values;
|
||||
}
|
||||
+86
-19
@@ -1,39 +1,106 @@
|
||||
import { Bus } from './bus';
|
||||
import { errorToResponse } from './transformers';
|
||||
import { renderError, type ErrorRenderer } from './transformers';
|
||||
import { isAsyncIterable } from './channel';
|
||||
import type { TransformerFn } from './metadata';
|
||||
import type { TransformerFn, Transport } from './metadata';
|
||||
import { TransportMismatchError } from './signals';
|
||||
|
||||
export interface PipelineStep { name: string; origin: string; run: (ctx: any) => any }
|
||||
export interface ResponseShape { status: number; headers: Record<string, string>; body: string }
|
||||
export interface StreamResult { stream: AsyncIterable<unknown> }
|
||||
/** A single step in a request pipeline: a named unit whose `run` merges its output into the shared context. */
|
||||
export interface PipelineStep {
|
||||
name: string;
|
||||
origin: string;
|
||||
run: (ctx: any) => any;
|
||||
}
|
||||
/** A fully materialized HTTP response produced by a transformer. */
|
||||
export interface ResponseShape {
|
||||
status: number;
|
||||
headers: Record<string, string>;
|
||||
body: string;
|
||||
}
|
||||
/** A streaming response; the async iterable is written to the socket and bypasses the transformer. */
|
||||
export interface StreamResult {
|
||||
stream: AsyncIterable<unknown>;
|
||||
}
|
||||
/** The outcome of {@link runPipeline}: either a buffered response or a stream. */
|
||||
export type PipelineResult = ResponseShape | StreamResult;
|
||||
|
||||
export function isStreamResult(r: PipelineResult): r is StreamResult {
|
||||
return 'stream' in r;
|
||||
/** What a route's declared transport requires its handler to return. */
|
||||
export type ReturnContract = 'buffer' | 'stream' | 'either';
|
||||
|
||||
/** Return contract per transport. A new transport just adds a row. `ws` never reaches runPipeline (filtered earlier). */
|
||||
export const TRANSPORT_RETURN: Record<Transport, ReturnContract> = {
|
||||
buffer: 'buffer',
|
||||
sse: 'stream',
|
||||
ndjson: 'stream',
|
||||
ws: 'stream',
|
||||
negotiate: 'either',
|
||||
};
|
||||
|
||||
/** Type guard narrowing a {@link PipelineResult} to a {@link StreamResult}. */
|
||||
export function isStreamResult(result: PipelineResult): result is StreamResult {
|
||||
return 'stream' in result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run `steps` in order, merging each step's output into the context and emitting
|
||||
* `request:step:enter`/`leave` on the bus. The single place steps are executed — every
|
||||
* transport (HTTP, ws, mesh) goes through here so observability is uniform by construction.
|
||||
*/
|
||||
export async function runSteps(steps: PipelineStep[], seed: Record<string, unknown>, bus: Bus): Promise<any> {
|
||||
// context is intentionally `any`: each step merges arbitrary keys into the accumulator
|
||||
const context: any = seed;
|
||||
|
||||
for (const step of steps) {
|
||||
bus.emit('request:step:enter', { name: step.name, scope: step.origin });
|
||||
const output = await step.run(context);
|
||||
Object.assign(context, output);
|
||||
bus.emit('request:step:leave', { name: step.name, scope: step.origin });
|
||||
}
|
||||
|
||||
return context;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run `steps` in order over a context seeded from `seed`, then invoke `handler`.
|
||||
* An async-iterable handler result becomes a stream; anything else is run through `transformer`.
|
||||
* Errors are caught, emitted on `bus`, and converted to an error response.
|
||||
*/
|
||||
export async function runPipeline(args: {
|
||||
steps: PipelineStep[];
|
||||
handler: (ctx: any) => unknown;
|
||||
transformer: TransformerFn;
|
||||
seed: Record<string, unknown>;
|
||||
bus: Bus;
|
||||
transport: Transport;
|
||||
onError?: ErrorRenderer;
|
||||
}): Promise<PipelineResult> {
|
||||
const { steps, handler, transformer, seed, bus } = args;
|
||||
let ctx: any = { ...seed };
|
||||
const { steps, handler, transformer, seed, bus, transport, onError } = args;
|
||||
// context is intentionally `any`: each step merges arbitrary keys into the accumulator
|
||||
let context: any = { ...seed };
|
||||
|
||||
try {
|
||||
for (const s of steps) {
|
||||
bus.emit('request:step:enter', { name: s.name, scope: s.origin });
|
||||
const out = await s.run(ctx);
|
||||
ctx = { ...ctx, ...out };
|
||||
bus.emit('request:step:leave', { name: s.name, scope: s.origin });
|
||||
context = await runSteps(steps, context, bus);
|
||||
const result = await handler(context);
|
||||
const streaming = isAsyncIterable(result);
|
||||
const contract = TRANSPORT_RETURN[transport];
|
||||
|
||||
if (contract === 'buffer' && streaming) {
|
||||
throw new TransportMismatchError(transport, 'stream', context.req as { method?: string; url?: string });
|
||||
}
|
||||
const result = await handler(ctx);
|
||||
if (isAsyncIterable(result)) return { stream: result }; // stream path: transformer bypassed
|
||||
const r = transformer(result);
|
||||
return { status: r.status ?? 200, headers: r.headers ?? {}, body: r.body };
|
||||
|
||||
if (contract === 'stream' && !streaming) {
|
||||
throw new TransportMismatchError(transport, 'value', context.req as { method?: string; url?: string });
|
||||
}
|
||||
|
||||
if (streaming) return { stream: result }; // stream path: transformer bypassed
|
||||
const transformed = transformer(result);
|
||||
return { status: transformed.status ?? 200, headers: transformed.headers ?? {}, body: transformed.body };
|
||||
} catch (error) {
|
||||
bus.emit('request:step:error', { name: 'pipeline', error });
|
||||
return errorToResponse(error);
|
||||
const req = (context.req ?? {}) as { method?: string; url?: string; headers?: Record<string, unknown> };
|
||||
return renderError(
|
||||
error,
|
||||
{ method: req.method ?? '', url: req.url ?? '', headers: (context.headers ?? req.headers ?? {}) as never },
|
||||
onError,
|
||||
);
|
||||
}
|
||||
}
|
||||
+12
-2
@@ -1,5 +1,6 @@
|
||||
import { Bus } from './bus';
|
||||
|
||||
/** A step or provider a plugin contributes to the graph. */
|
||||
export interface ScopeNode {
|
||||
kind: 'step' | 'provider';
|
||||
name: string;
|
||||
@@ -8,10 +9,19 @@ export interface ScopeNode {
|
||||
run: (ctx: any) => any;
|
||||
}
|
||||
|
||||
export interface ScopeApi { add(node: ScopeNode): void }
|
||||
export interface PluginApi { bus: { on: Bus['on'] }; scope: ScopeApi }
|
||||
/** The narrow surface a plugin uses to register nodes into the host graph. */
|
||||
export interface ScopeApi {
|
||||
add(node: ScopeNode): void;
|
||||
}
|
||||
/** The capabilities handed to a plugin: event subscription and node registration only. */
|
||||
export interface PluginApi {
|
||||
bus: { on: Bus['on'] };
|
||||
scope: ScopeApi;
|
||||
}
|
||||
/** A plugin: a function that wires itself up through the provided PluginApi. */
|
||||
export type Plugin = (api: PluginApi) => void;
|
||||
|
||||
/** Runs a plugin against a restricted API, then emits `plugin:mounted`. */
|
||||
export function mountPlugin(plugin: Plugin, bus: Bus, scope: ScopeApi): void {
|
||||
// Hand the plugin ONLY on() and add(). No emit, no other scope. Isolation is structural.
|
||||
const api: PluginApi = { bus: { on: bus.on.bind(bus) }, scope };
|
||||
|
||||
+12
-2
@@ -1,11 +1,21 @@
|
||||
import { channel, type Channel } from './channel';
|
||||
|
||||
/** Registry of named broadcast channels, lazily created and shared by name. */
|
||||
export class Rooms {
|
||||
private readonly hubs = new Map<string, Channel<unknown>>();
|
||||
/** Returns the channel for `name`, creating it on first access. */
|
||||
room<T = unknown>(name: string): Channel<T> {
|
||||
let hub = this.hubs.get(name);
|
||||
if (!hub) { hub = channel<unknown>(); this.hubs.set(name, hub); }
|
||||
|
||||
if (!hub) {
|
||||
hub = channel<unknown>();
|
||||
this.hubs.set(name, hub);
|
||||
}
|
||||
|
||||
return hub as unknown as Channel<T>;
|
||||
}
|
||||
names(): string[] { return [...this.hubs.keys()]; }
|
||||
/** Lists the names of all rooms created so far. */
|
||||
names(): string[] {
|
||||
return [...this.hubs.keys()];
|
||||
}
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
// src/security.ts — pure header computation, no server deps
|
||||
|
||||
/** TLS material for an HTTPS server. */
|
||||
export interface TlsOptions {
|
||||
key: Buffer | string;
|
||||
cert: Buffer | string;
|
||||
ca?: Buffer | string;
|
||||
passphrase?: string;
|
||||
}
|
||||
|
||||
/** CORS policy. `origins` may be a literal, list, `'*'`, or a predicate. */
|
||||
export interface CorsOptions {
|
||||
origins: string | string[] | '*' | ((origin: string) => boolean);
|
||||
methods?: string[];
|
||||
allowedHeaders?: string[];
|
||||
exposedHeaders?: string[];
|
||||
credentials?: boolean;
|
||||
maxAge?: number;
|
||||
}
|
||||
|
||||
/** Security header policy. Each field toggles or configures one response header. */
|
||||
export interface SecurityOptions {
|
||||
hsts?: boolean | { maxAge?: number; includeSubDomains?: boolean; preload?: boolean };
|
||||
frameOptions?: 'SAMEORIGIN' | 'DENY' | false;
|
||||
referrerPolicy?: string | false;
|
||||
noSniff?: boolean;
|
||||
dnsPrefetchControl?: boolean;
|
||||
csp?: string;
|
||||
}
|
||||
|
||||
type Headers = Record<string, string>;
|
||||
const HSTS_DEFAULT_MAXAGE = 15552000; // 180 days
|
||||
|
||||
// scheme "://" host [":" port], or literal "null". Rejects control chars/whitespace.
|
||||
// Control-char ranges (\x00-\x1f\x7f) are intentional: reject control chars in Origin headers.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const ORIGIN_RE = /^(?:null|[a-z][a-z0-9+.-]*:\/\/[^\s/?#\x00-\x1f\x7f]+)$/i;
|
||||
|
||||
/** True if `origin` is a well-formed Origin header value (scheme://host or literal `null`). */
|
||||
export function isValidOrigin(origin: string): boolean {
|
||||
return ORIGIN_RE.test(origin);
|
||||
}
|
||||
|
||||
/** Append `add` to a `Vary` header value, case-insensitively deduplicated. */
|
||||
export function mergeVary(existing: string | undefined, add: string): string {
|
||||
const parts = existing
|
||||
? existing
|
||||
.split(',')
|
||||
.map((segment) => segment.trim())
|
||||
.filter(Boolean)
|
||||
: [];
|
||||
if (!parts.some((part) => part.toLowerCase() === add.toLowerCase())) parts.push(add);
|
||||
return parts.join(', ');
|
||||
}
|
||||
|
||||
/** Build security response headers (HSTS, frame options, CSP, etc.). `secure` gates HSTS. */
|
||||
export function buildSecurityHeaders(opts: boolean | SecurityOptions, secure: boolean): Headers {
|
||||
if (opts === false) return {};
|
||||
const options: SecurityOptions = opts === true ? {} : opts;
|
||||
const headers: Headers = {};
|
||||
if (options.noSniff !== false) headers['x-content-type-options'] = 'nosniff';
|
||||
if (options.frameOptions !== false) headers['x-frame-options'] = options.frameOptions ?? 'SAMEORIGIN';
|
||||
if (options.referrerPolicy !== false) headers['referrer-policy'] = options.referrerPolicy ?? 'no-referrer';
|
||||
if (options.dnsPrefetchControl !== false) headers['x-dns-prefetch-control'] = 'off';
|
||||
if (options.csp) headers['content-security-policy'] = options.csp;
|
||||
|
||||
if (secure && options.hsts !== false) {
|
||||
const hsts = options.hsts && options.hsts !== true ? options.hsts : {};
|
||||
let value = `max-age=${hsts.maxAge ?? HSTS_DEFAULT_MAXAGE}`;
|
||||
if (hsts.includeSubDomains) value += '; includeSubDomains';
|
||||
if (hsts.preload) value += '; preload';
|
||||
headers['strict-transport-security'] = value;
|
||||
}
|
||||
|
||||
return headers;
|
||||
}
|
||||
|
||||
function originAllowed(spec: CorsOptions['origins'], origin: string): boolean {
|
||||
if (spec === '*') return true;
|
||||
if (typeof spec === 'function') return spec(origin);
|
||||
if (Array.isArray(spec)) return spec.includes(origin);
|
||||
return spec === origin;
|
||||
}
|
||||
|
||||
/** Compute CORS response headers for a request. Returns `{}` when the origin is not allowed. */
|
||||
export function resolveCors(
|
||||
opts: CorsOptions,
|
||||
req: { headers: Record<string, string | string[] | undefined> },
|
||||
): Headers {
|
||||
const headers: Headers = {};
|
||||
const rawOrigin = req.headers['origin'];
|
||||
const origin = Array.isArray(rawOrigin) ? rawOrigin[0] : rawOrigin;
|
||||
if (!origin || !isValidOrigin(origin) || !originAllowed(opts.origins, origin)) return headers;
|
||||
|
||||
// credentials => never '*'; echo concrete origin. Also echo when allowlist is dynamic.
|
||||
if (opts.credentials) {
|
||||
headers['access-control-allow-origin'] = origin;
|
||||
headers['access-control-allow-credentials'] = 'true';
|
||||
headers['vary'] = mergeVary(headers['vary'], 'Origin');
|
||||
} else if (opts.origins === '*') {
|
||||
headers['access-control-allow-origin'] = '*';
|
||||
} else {
|
||||
headers['access-control-allow-origin'] = origin;
|
||||
headers['vary'] = mergeVary(headers['vary'], 'Origin');
|
||||
}
|
||||
|
||||
if (opts.exposedHeaders?.length) headers['access-control-expose-headers'] = opts.exposedHeaders.join(', ');
|
||||
return headers;
|
||||
}
|
||||
|
||||
/** Preflight-specific headers (methods/allowed-headers/max-age). Call only for OPTIONS+ACRM. */
|
||||
export function corsPreflightHeaders(
|
||||
opts: CorsOptions,
|
||||
req: { headers: Record<string, string | string[] | undefined> },
|
||||
): Headers {
|
||||
const headers = resolveCors(opts, req);
|
||||
if (!headers['access-control-allow-origin']) return headers; // origin not allowed → bare 204
|
||||
headers['access-control-allow-methods'] = (opts.methods ?? ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']).join(
|
||||
', ',
|
||||
);
|
||||
const requestedHeaders = req.headers['access-control-request-headers'];
|
||||
headers['access-control-allow-headers'] =
|
||||
opts.allowedHeaders?.join(', ') ??
|
||||
(Array.isArray(requestedHeaders) ? requestedHeaders.join(', ') : (requestedHeaders ?? '*'));
|
||||
if (opts.maxAge != null) headers['access-control-max-age'] = String(opts.maxAge);
|
||||
return headers;
|
||||
}
|
||||
+55
-7
@@ -1,26 +1,74 @@
|
||||
import type { StandardIssue } from './standard-schema';
|
||||
|
||||
/**
|
||||
* Error carrying an HTTP status code and optional response body. Base of all signals.
|
||||
* A subclass needing response headers (e.g. `location`, `retry-after`) sets `headers`
|
||||
* rather than requiring a special case in the error renderer.
|
||||
*/
|
||||
export class HttpError extends Error {
|
||||
constructor(readonly status: number, message?: string, readonly body?: unknown) {
|
||||
constructor(
|
||||
readonly status: number,
|
||||
message?: string,
|
||||
readonly body?: unknown,
|
||||
readonly headers?: Record<string, string>,
|
||||
) {
|
||||
super(message ?? `HTTP ${status}`);
|
||||
this.name = new.target.name;
|
||||
}
|
||||
}
|
||||
|
||||
/** 401 Unauthorized. */
|
||||
export class Unauthorized extends HttpError {
|
||||
constructor(message?: string) { super(401, message); }
|
||||
constructor(message?: string) {
|
||||
super(401, message);
|
||||
}
|
||||
}
|
||||
|
||||
/** 404 Not Found. */
|
||||
export class NotFound extends HttpError {
|
||||
constructor(message?: string) { super(404, message); }
|
||||
constructor(message?: string) {
|
||||
super(404, message);
|
||||
}
|
||||
}
|
||||
|
||||
/** 304 Not Modified. */
|
||||
export class NotModified extends HttpError {
|
||||
constructor() { super(304); }
|
||||
constructor() {
|
||||
super(304);
|
||||
}
|
||||
}
|
||||
|
||||
/** 302 redirect to `location`. */
|
||||
export class Redirect extends HttpError {
|
||||
constructor(readonly location: string) { super(302); }
|
||||
constructor(readonly location: string) {
|
||||
super(302, undefined, undefined, { location });
|
||||
}
|
||||
}
|
||||
|
||||
export function isHttpError(e: unknown): e is HttpError {
|
||||
return e instanceof HttpError;
|
||||
/** 422 raised when request input fails Standard Schema validation. */
|
||||
export class ValidationError extends HttpError {
|
||||
constructor(
|
||||
public issues: StandardIssue[],
|
||||
public source: string,
|
||||
) {
|
||||
super(422, 'Validation failed');
|
||||
}
|
||||
}
|
||||
|
||||
/** Thrown when a handler's return value contradicts its route's declared transport (a programming error). */
|
||||
export class TransportMismatchError extends HttpError {
|
||||
constructor(transport: string, got: 'stream' | 'value', req?: { method?: string; url?: string }) {
|
||||
const where = req?.method && req?.url ? ` (${req.method} ${req.url})` : '';
|
||||
const expected = got === 'stream' ? 'return a value' : 'return an AsyncIterable';
|
||||
const fix =
|
||||
got === 'stream'
|
||||
? 'buffered routes (@Get/@Head/@Post/@Put/@Patch/@Delete/@Options) must return a value — to stream, declare @Sse, @Stream, or @Ws'
|
||||
: 'streaming routes (@Sse/@Ws) must return an AsyncIterable (e.g. an async generator or channel())';
|
||||
super(500, `Transport '${transport}'${where} must ${expected}, but the handler returned a ${got}. ${fix}.`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Type guard: true if `error` is an {@link HttpError}. */
|
||||
export function isHttpError(error: unknown): error is HttpError {
|
||||
return error instanceof HttpError;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// src/standard-schema.ts — vendored Standard Schema (~standard) types + helpers. No imports.
|
||||
|
||||
/** Standard Schema v1 interface (spec.standardschema.dev): a validator under the `~standard` key. */
|
||||
export interface StandardSchemaV1<Input = unknown, Output = Input> {
|
||||
readonly '~standard': {
|
||||
readonly version: 1;
|
||||
readonly vendor: string;
|
||||
validate(value: unknown): StandardResult<Output> | Promise<StandardResult<Output>>;
|
||||
readonly types?: { readonly input: Input; readonly output: Output };
|
||||
};
|
||||
}
|
||||
|
||||
/** Validation outcome: either a parsed `value` or a list of `issues`. */
|
||||
export type StandardResult<T> =
|
||||
{ readonly value: T; readonly issues?: undefined } | { readonly issues: ReadonlyArray<StandardIssue> };
|
||||
|
||||
/** A single validation issue with a message and optional path to the offending field. */
|
||||
export interface StandardIssue {
|
||||
readonly message: string;
|
||||
readonly path?: ReadonlyArray<PropertyKey | { readonly key: PropertyKey }>;
|
||||
}
|
||||
|
||||
/** Type guard: true if `value` implements Standard Schema v1 (has a callable `~standard.validate`). */
|
||||
export function isStandardSchema(value: unknown): value is StandardSchemaV1 {
|
||||
return (
|
||||
typeof value === 'object' &&
|
||||
value !== null &&
|
||||
'~standard' in value &&
|
||||
typeof (value as { ['~standard']?: { validate?: unknown } })['~standard']?.validate === 'function'
|
||||
);
|
||||
}
|
||||
|
||||
/** Render an issue's path as a dotted string (e.g. `user.email`); empty if pathless. */
|
||||
export function flattenPath(issue: StandardIssue): string {
|
||||
if (!issue.path) return '';
|
||||
return issue.path
|
||||
.map((segment) => (typeof segment === 'object' && segment !== null && 'key' in segment ? segment.key : segment))
|
||||
.map((key) => String(key))
|
||||
.join('.');
|
||||
}
|
||||
+50
-6
@@ -1,21 +1,65 @@
|
||||
import { isHttpError, Redirect } from './signals';
|
||||
import { isHttpError, ValidationError } from './signals';
|
||||
import type { TransformerFn } from './metadata';
|
||||
import { flattenPath } from './standard-schema';
|
||||
|
||||
/** A ready-to-send HTTP response. */
|
||||
export interface ErrorResponse {
|
||||
status: number;
|
||||
headers: Record<string, string>;
|
||||
body: string;
|
||||
}
|
||||
|
||||
/** The request a {@link ErrorRenderer} is given, to inspect (e.g. `headers.accept`) while rendering. */
|
||||
export interface ErrorRequest {
|
||||
method: string;
|
||||
url: string;
|
||||
headers: Record<string, string | string[] | undefined>;
|
||||
}
|
||||
|
||||
/**
|
||||
* User hook to render errors however you like (HTML, custom JSON, RFC 7807, …).
|
||||
* Return a response to take over, or `undefined`/`void` to fall back to the default JSON.
|
||||
*/
|
||||
export type ErrorRenderer = (error: unknown, req: ErrorRequest) => ErrorResponse | undefined | void;
|
||||
|
||||
/** Default transformer: serialize a handler's return value as a JSON `200` response. */
|
||||
export const JsonTransformer: TransformerFn = (value) => ({
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(value),
|
||||
});
|
||||
|
||||
export function errorToResponse(e: unknown): { status: number; headers: Record<string, string>; body: string } {
|
||||
if (isHttpError(e)) {
|
||||
const headers: Record<string, string> = { 'content-type': 'application/json' };
|
||||
if (e instanceof Redirect) headers.location = e.location;
|
||||
return { status: e.status, headers, body: JSON.stringify({ error: e.message }) };
|
||||
/**
|
||||
* Map a thrown value to a JSON error response (422 for validation, `HttpError` status, else 500).
|
||||
* An `HttpError` carrying a `body` renders that payload instead of the default `{ error: message }`.
|
||||
*/
|
||||
export function errorToResponse(error: unknown): ErrorResponse {
|
||||
if (error instanceof ValidationError) {
|
||||
return {
|
||||
status: 422,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
error: 'Validation failed',
|
||||
source: error.source,
|
||||
issues: error.issues.map((issue) => ({ path: flattenPath(issue), message: issue.message })),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
if (isHttpError(error)) {
|
||||
const headers = { 'content-type': 'application/json', ...error.headers };
|
||||
const payload = error.body !== undefined ? error.body : { error: error.message };
|
||||
return { status: error.status, headers, body: JSON.stringify(payload) };
|
||||
}
|
||||
|
||||
return {
|
||||
status: 500,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ error: 'Internal Server Error' }),
|
||||
};
|
||||
}
|
||||
|
||||
/** Render an error through the optional user {@link ErrorRenderer}, falling back to {@link errorToResponse}. */
|
||||
export function renderError(error: unknown, req: ErrorRequest, onError?: ErrorRenderer): ErrorResponse {
|
||||
return onError?.(error, req) ?? errorToResponse(error);
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
// src/views.ts — HTML views: built-in templating, content-type map, and boot-time builders.
|
||||
// fs/path are lazy-required inside functions so the barrel stays edge-loadable (workerd has no filesystem).
|
||||
|
||||
import type { TransformerFn } from './metadata';
|
||||
import type { HtmlMeta } from './metadata';
|
||||
|
||||
/** Escape the five HTML-significant characters so interpolated data can't inject markup. */
|
||||
export function escapeHtml(s: string): string {
|
||||
const map: Record<string, string> = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
|
||||
return s.replace(/[&<>"']/g, (c) => map[c]);
|
||||
}
|
||||
|
||||
function stringify(v: unknown): string {
|
||||
return v === null || v === undefined ? '' : String(v);
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimal built-in template engine: `{{ key }}` interpolates HTML-escaped, `{{{ key }}}` raw,
|
||||
* `{{ a.b }}` walks nested keys, a missing key renders empty. No loops/conditionals/partials.
|
||||
*/
|
||||
export function render(source: string, data: unknown): string {
|
||||
const lookup = (key: string): unknown =>
|
||||
key.split('.').reduce<any>((obj, k) => (obj === null || obj === undefined ? undefined : obj[k]), data);
|
||||
return source
|
||||
.replace(/\{\{\{\s*([\w.]+)\s*\}\}\}/g, (_, key) => stringify(lookup(key)))
|
||||
.replace(/\{\{\s*([\w.]+)\s*\}\}/g, (_, key) => escapeHtml(stringify(lookup(key))));
|
||||
}
|
||||
|
||||
const CONTENT_TYPES: Record<string, string> = {
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
'.css': 'text/css; charset=utf-8',
|
||||
'.js': 'text/javascript; charset=utf-8',
|
||||
'.mjs': 'text/javascript; charset=utf-8',
|
||||
'.json': 'application/json; charset=utf-8',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.png': 'image/png',
|
||||
'.jpg': 'image/jpeg',
|
||||
'.jpeg': 'image/jpeg',
|
||||
'.gif': 'image/gif',
|
||||
'.webp': 'image/webp',
|
||||
'.ico': 'image/x-icon',
|
||||
'.woff2': 'font/woff2',
|
||||
'.txt': 'text/plain; charset=utf-8',
|
||||
};
|
||||
|
||||
/** Content-type for a file extension (case-insensitive, leading dot); unknown → `application/octet-stream`. */
|
||||
export function contentTypeFor(ext: string): string {
|
||||
return CONTENT_TYPES[ext.toLowerCase()] ?? 'application/octet-stream';
|
||||
}
|
||||
|
||||
const HTML_HEADERS = { 'content-type': 'text/html; charset=utf-8' } as const;
|
||||
|
||||
/** Boot-time context for building `@Html` transformers: the views base dir and an optional BYO engine. */
|
||||
export interface ViewsContext {
|
||||
views?: string;
|
||||
viewEngine?: (source: string, data: unknown) => string;
|
||||
}
|
||||
|
||||
/** Reads a view file at boot (lazy fs). Relative paths resolve against `views` (default cwd); absolute as-is.
|
||||
* node:fs/node:path are loaded lazily so importing the barrel stays edge/workerd-safe
|
||||
* (workerd's nodejs_compat provides no filesystem). This path only runs for path/template `@Html` modes. */
|
||||
function readViewFile(views: string | undefined, path: string): string {
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const nodePath = require('node:path') as typeof import('node:path');
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const fs = require('node:fs') as typeof import('node:fs');
|
||||
const base = views ?? process.cwd();
|
||||
const full = nodePath.isAbsolute(path) ? path : nodePath.resolve(base, path);
|
||||
|
||||
try {
|
||||
return fs.readFileSync(full, 'utf8');
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`@Html('${path}') could not read '${full}' — on a runtime without a filesystem (edge), return a string from @Html instead. (${(err as Error).message})`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** A static-file hit: the raw bytes and the content-type to send. */
|
||||
export interface StaticHit {
|
||||
body: Buffer;
|
||||
contentType: string;
|
||||
}
|
||||
|
||||
/** Resolves a URL path to a static file under a fixed root, or `undefined` for a miss. */
|
||||
export type StaticResolver = (urlPath: string) => Promise<StaticHit | undefined>;
|
||||
|
||||
/**
|
||||
* Builds a static-file resolver rooted at `root` (`true` → `./public`). Requires a filesystem: throws at
|
||||
* boot on a runtime without one (edge). Path-traversal-safe — a resolved path outside the root is a miss.
|
||||
*/
|
||||
export function buildStaticResolver(root: string | true): StaticResolver {
|
||||
let fs: typeof import('node:fs');
|
||||
let nodePath: typeof import('node:path');
|
||||
|
||||
try {
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
fs = require('node:fs');
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
nodePath = require('node:path');
|
||||
} catch {
|
||||
throw new Error(
|
||||
'`static` needs a filesystem and is unavailable on this runtime (edge). Remove it or serve assets from a CDN.',
|
||||
);
|
||||
}
|
||||
|
||||
const abs = nodePath.resolve(process.cwd(), root === true ? 'public' : root);
|
||||
|
||||
return async (urlPath) => {
|
||||
let rel: string;
|
||||
|
||||
try {
|
||||
rel = decodeURIComponent(urlPath.split('?')[0]);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (rel === '' || rel.endsWith('/')) rel += 'index.html';
|
||||
const full = nodePath.resolve(abs, '.' + (rel.startsWith('/') ? rel : '/' + rel));
|
||||
if (full !== abs && !full.startsWith(abs + nodePath.sep)) return undefined; // traversal guard
|
||||
|
||||
try {
|
||||
const stat = await fs.promises.stat(full);
|
||||
const target = stat.isDirectory() ? nodePath.join(full, 'index.html') : full;
|
||||
const body = await fs.promises.readFile(target);
|
||||
return { body, contentType: contentTypeFor(nodePath.extname(target)) };
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** Turns `@Html` metadata into a response transformer at boot. String mode is fs-free; path/template modes read+cache the file. */
|
||||
export function buildHtmlTransformer(meta: HtmlMeta, ctx: ViewsContext): TransformerFn {
|
||||
if (!meta.path) {
|
||||
return (value) => ({ status: 200, headers: { ...HTML_HEADERS }, body: String(value) });
|
||||
}
|
||||
|
||||
const source = readViewFile(ctx.views, meta.path);
|
||||
|
||||
if (meta.template) {
|
||||
const engine = ctx.viewEngine ?? render;
|
||||
return (value) => ({ status: 200, headers: { ...HTML_HEADERS }, body: engine(source, value) });
|
||||
}
|
||||
|
||||
return () => ({ status: 200, headers: { ...HTML_HEADERS }, body: source });
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createApp, Route, Ws, Module, ctx, Step, needs } from '../src/index';
|
||||
import { channel } from '../src/channel';
|
||||
import type { WsSocket, WsRequest } from '../src/http/ws-core';
|
||||
|
||||
@Route('/rt')
|
||||
class Rt {
|
||||
@Ws('/echo')
|
||||
echo(@ctx() { inbound }: any) {
|
||||
return (async function* () {
|
||||
for await (const msg of inbound) yield `echo:${msg}`;
|
||||
})();
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Rt] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
|
||||
@Step({ provides: 'tag' })
|
||||
class Tagger {
|
||||
run() {
|
||||
return { tag: 't' };
|
||||
}
|
||||
}
|
||||
@Route('/tagged')
|
||||
class TaggedCtl {
|
||||
@Ws('/echo')
|
||||
echo(@needs('tag') tag: string, @ctx() { inbound }: any) {
|
||||
return (async function* () {
|
||||
for await (const msg of inbound) yield `${tag}:${msg}`;
|
||||
})();
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', steps: [Tagger], controllers: [TaggedCtl] })
|
||||
class Tagged {}
|
||||
|
||||
function fakeSocket() {
|
||||
const inbound = channel<unknown>();
|
||||
const ac = new AbortController();
|
||||
const sent: string[] = [];
|
||||
const socket: WsSocket = {
|
||||
inbound,
|
||||
abort: ac.signal,
|
||||
isOpen: true,
|
||||
send: (d) => sent.push(d),
|
||||
close: () => ac.abort(),
|
||||
terminate: () => ac.abort(),
|
||||
};
|
||||
return { socket, inbound, sent };
|
||||
}
|
||||
|
||||
describe('app.upgrade', () => {
|
||||
it('routes a matching ws path through the graph', async () => {
|
||||
const { socket, inbound, sent } = fakeSocket();
|
||||
const req: WsRequest = { url: '/rt/echo', headers: {}, protocol: 'http', ip: '' };
|
||||
const run = app.upgrade(req, socket);
|
||||
// let the handler's async generator start subscribing to `inbound` (channel is fan-out:
|
||||
// push before subscription is lost) before pushing — a macrotask flushes every pending
|
||||
// microtask in the upgrade/boot chain first, so this is deterministic, not a sleep-and-hope.
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
inbound.push('hi');
|
||||
inbound.close();
|
||||
await run;
|
||||
expect(sent).toEqual(['echo:hi']);
|
||||
});
|
||||
|
||||
it('emits request:step:enter/leave for ws steps, like HTTP routes do', async () => {
|
||||
const seen: string[] = [];
|
||||
const logger = (api: any) => {
|
||||
api.bus.on('request:step:enter', (p: any) => seen.push(`enter:${p.name}`));
|
||||
api.bus.on('request:step:leave', (p: any) => seen.push(`leave:${p.name}`));
|
||||
};
|
||||
const wsApp = createApp({ modules: [Tagged], plugins: [logger] });
|
||||
const { socket, inbound, sent } = fakeSocket();
|
||||
const req: WsRequest = { url: '/tagged/echo', headers: {}, protocol: 'http', ip: '' };
|
||||
const run = wsApp.upgrade(req, socket);
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
inbound.push('hi');
|
||||
inbound.close();
|
||||
await run;
|
||||
|
||||
expect(sent).toEqual(['t:hi']);
|
||||
expect(seen).toEqual(['enter:tag', 'leave:tag']);
|
||||
});
|
||||
|
||||
it('closes 1008 on an unknown ws path', async () => {
|
||||
const { socket } = fakeSocket();
|
||||
let closedCode: number | undefined;
|
||||
socket.close = (c) => {
|
||||
closedCode = c;
|
||||
};
|
||||
const req: WsRequest = { url: '/rt/nope', headers: {}, protocol: 'http', ip: '' };
|
||||
await app.upgrade(req, socket);
|
||||
expect(closedCode).toBe(1008);
|
||||
});
|
||||
});
|
||||
+341
-58
@@ -1,13 +1,17 @@
|
||||
import 'reflect-metadata';
|
||||
import { describe, expect, it, test, vi } from 'vitest';
|
||||
import { Provider, Step, Route, Get, Module, Transformer } from '../src/metadata';
|
||||
import { Provider, Step, Route, Get, Post, Module, Transformer } from '../src/metadata';
|
||||
import { JsonTransformer } from '../src/transformers';
|
||||
import { Unauthorized } from '../src/signals';
|
||||
import { createApp } from '../src/app';
|
||||
import { needs, param, query } from '../src/params';
|
||||
import { needs, param, query, body } from '../src/params';
|
||||
|
||||
@Provider({ provides: 'db' })
|
||||
class Db { provide() { return { db: { find: (t: string) => (t === 'good' ? { id: 'u1' } : null) } }; } }
|
||||
class Db {
|
||||
provide() {
|
||||
return { db: { find: (t: string) => (t === 'good' ? { id: 'u1' } : null) } };
|
||||
}
|
||||
}
|
||||
|
||||
@Step({ provides: 'user', needs: ['db', 'req'] })
|
||||
class Auth {
|
||||
@@ -22,7 +26,9 @@ class Auth {
|
||||
class UserCtl {
|
||||
@Get('/:id')
|
||||
@Transformer(JsonTransformer)
|
||||
getUser(@needs('user') user: any, @param('id') id: string) { return { id, user }; }
|
||||
getUser(@needs('user') user: any, @param('id') id: string) {
|
||||
return { id, user };
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/api', providers: [Db], steps: [Auth], controllers: [UserCtl] })
|
||||
@@ -34,6 +40,20 @@ test('inspect lists the ordered chain with origins', () => {
|
||||
expect(lines.map((l) => `${l.kind}:${l.name}`)).toEqual(['provider:db', 'step:user', 'handler:getUser']);
|
||||
});
|
||||
|
||||
test('ready() is a no-op on a non-mesh app, so one protocol works for both', async () => {
|
||||
// The point: code holding an `App` should not have to know whether it is a mesh app.
|
||||
// `await app.ready(); app.graph()` is uniform — here it changes nothing and boots nothing.
|
||||
const app = createApp({ modules: [ApiModule] });
|
||||
const booted: string[] = [];
|
||||
app.bus.on('boot:provider:start', (p) => booted.push(p.name));
|
||||
|
||||
const before = app.graph().nodes.length;
|
||||
await app.ready();
|
||||
|
||||
expect(app.graph().nodes.length).toBe(before);
|
||||
expect(booted).toEqual([]);
|
||||
});
|
||||
|
||||
test('a logger plugin observes step:enter without mutating the chain', async () => {
|
||||
const seen: string[] = [];
|
||||
const logger = (api: any) => api.bus.on('request:step:enter', (p: any) => seen.push(p.name));
|
||||
@@ -54,7 +74,11 @@ test('a logger plugin observes step:enter without mutating the chain', async ()
|
||||
|
||||
test('required provider failure aborts boot', () => {
|
||||
@Provider({ provides: 'broken' })
|
||||
class Broken { provide() { throw new Error('cannot connect'); } }
|
||||
class Broken {
|
||||
provide() {
|
||||
throw new Error('cannot connect');
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/x', providers: [Broken], steps: [], controllers: [] })
|
||||
class BrokenModule {}
|
||||
|
||||
@@ -65,15 +89,27 @@ test('required provider failure aborts boot', () => {
|
||||
test('optional provider failure warns but does not abort boot', async () => {
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
@Provider({ provides: 'cache', optional: true })
|
||||
class FlakyCache { provide() { throw new Error('cache down'); } }
|
||||
class FlakyCache {
|
||||
provide() {
|
||||
throw new Error('cache down');
|
||||
}
|
||||
}
|
||||
@Route('/ping')
|
||||
class PingCtl { @Get('/') ping() { return { ok: true }; } }
|
||||
class PingCtl {
|
||||
@Get('/') ping() {
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/sys', providers: [FlakyCache], steps: [], controllers: [PingCtl] })
|
||||
class SysModule {}
|
||||
|
||||
const app = createApp({ modules: [SysModule] });
|
||||
expect(app.degraded()).toEqual([]); // nothing degraded until boot runs
|
||||
const server = await app.listen(0); // must NOT throw
|
||||
expect(warn).toHaveBeenCalledWith(expect.stringContaining("optional provider 'cache' failed"));
|
||||
// boot ends with a summary of everything running degraded, and it is queryable on the app
|
||||
expect(warn).toHaveBeenCalledWith(expect.stringContaining('started with 1 degraded optional provider(s): cache'));
|
||||
expect(app.degraded()).toEqual(['cache']);
|
||||
server.close();
|
||||
warn.mockRestore();
|
||||
});
|
||||
@@ -82,7 +118,9 @@ test('handler receives @query value through a live request', async () => {
|
||||
@Route('/search')
|
||||
class SearchCtl {
|
||||
@Get('/')
|
||||
run(@query('q') q: string) { return { q }; }
|
||||
run(@query('q') q: string) {
|
||||
return { q };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/s', providers: [], steps: [], controllers: [SearchCtl] })
|
||||
class SearchModule {}
|
||||
@@ -99,19 +137,31 @@ test('boot fails when a handler needs something nothing provides', () => {
|
||||
@Route('/things')
|
||||
class ThingCtl {
|
||||
@Get('/')
|
||||
list(@needs('missing') _m: any) { return []; }
|
||||
list(@needs('missing') _m: any) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/t', providers: [], steps: [], controllers: [ThingCtl] })
|
||||
class ThingModule {}
|
||||
|
||||
expect(() => createApp({ modules: [ThingModule] }))
|
||||
.toThrow(/handler 'list' needs 'missing'/);
|
||||
expect(() => createApp({ modules: [ThingModule] })).toThrow(/handler 'list' needs 'missing'/);
|
||||
});
|
||||
|
||||
it('boot error for a misspelled @needs suggests the closest token', () => {
|
||||
@Step({ provides: 'user', needs: [] }) class Auth { run() { return { user: 1 }; } }
|
||||
@Route('/u') class Ctl { @Get('/x') x(@needs('usr') u: any) { return { u }; } }
|
||||
@Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] }) class M {}
|
||||
@Step({ provides: 'user', needs: [] })
|
||||
class Auth {
|
||||
run() {
|
||||
return { user: 1 };
|
||||
}
|
||||
}
|
||||
@Route('/u')
|
||||
class Ctl {
|
||||
@Get('/x') x(@needs('usr') u: any) {
|
||||
return { u };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] })
|
||||
class M {}
|
||||
expect(() => createApp({ modules: [M] })).toThrow(/did you mean 'user'\?/);
|
||||
});
|
||||
|
||||
@@ -124,10 +174,14 @@ describe('app streaming wiring', () => {
|
||||
@Route('/')
|
||||
class Ctl {
|
||||
@Sse('/ticks') ticks() {
|
||||
return (async function* () { yield { t: 1 }; yield { t: 2 }; })();
|
||||
return (async function* () {
|
||||
yield { t: 1 };
|
||||
yield { t: 2 };
|
||||
})();
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] }) class M {}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
const server = await app.listen(0);
|
||||
const addr = server.address() as import('net').AddressInfo;
|
||||
@@ -143,11 +197,15 @@ describe('app streaming wiring', () => {
|
||||
class Ctl {
|
||||
@Ws('/echo') echo(@inbound() inc: AsyncIterable<string>) {
|
||||
const out = channel<string>();
|
||||
(async () => { for await (const m of inc) out.push(`re:${m}`); out.close(); })();
|
||||
(async () => {
|
||||
for await (const m of inc) out.push(`re:${m}`);
|
||||
out.close();
|
||||
})();
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] }) class M {}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
const server = await app.listen(0);
|
||||
const addr = server.address() as import('net').AddressInfo;
|
||||
@@ -157,7 +215,8 @@ describe('app streaming wiring', () => {
|
||||
const got = new Promise<string>((r) => client.on('message', (d: Buffer) => r(d.toString())));
|
||||
client.send('yo');
|
||||
expect(await got).toBe('re:yo');
|
||||
client.close(); server.close();
|
||||
client.close();
|
||||
server.close();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -165,13 +224,23 @@ describe('per-route subgraph slicing', () => {
|
||||
it('a route that does not @needs a step does not run it', async () => {
|
||||
const ran: string[] = [];
|
||||
@Step({ provides: 'tracked', needs: [] })
|
||||
class Tracked { run() { ran.push('tracked'); return { tracked: true }; } }
|
||||
class Tracked {
|
||||
run() {
|
||||
ran.push('tracked');
|
||||
return { tracked: true };
|
||||
}
|
||||
}
|
||||
@Route('/')
|
||||
class Ctl {
|
||||
@Get('/needs') needs(@needs('tracked') t: any) { return { t }; }
|
||||
@Get('/free') free() { return { ok: true }; }
|
||||
@Get('/needs') needs(@needs('tracked') t: any) {
|
||||
return { t };
|
||||
}
|
||||
@Module({ mountpoint: '/', steps: [Tracked], controllers: [Ctl] }) class M {}
|
||||
@Get('/free') free() {
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', steps: [Tracked], controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
const server = await app.listen(0);
|
||||
const port = (server.address() as any).port;
|
||||
@@ -187,10 +256,25 @@ describe('per-route subgraph slicing', () => {
|
||||
it('a side-effect step (provides: []) added by a plugin runs unconditionally', async () => {
|
||||
// NB: @Step always provides exactly one token (always sliceable). provides:[] only arises via a plugin's scope.add.
|
||||
const ran: string[] = [];
|
||||
const observer = (api: any) => api.scope.add({ kind: 'step', name: 'obs', needs: [], provides: [], run: () => { ran.push('obs'); return {}; } });
|
||||
const observer = (api: any) =>
|
||||
api.scope.add({
|
||||
kind: 'step',
|
||||
name: 'obs',
|
||||
needs: [],
|
||||
provides: [],
|
||||
run: () => {
|
||||
ran.push('obs');
|
||||
return {};
|
||||
},
|
||||
});
|
||||
@Route('/')
|
||||
class Ctl { @Get('/free') free() { return { ok: true }; } }
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] }) class M {}
|
||||
class Ctl {
|
||||
@Get('/free') free() {
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M], plugins: [observer] });
|
||||
const server = await app.listen(0);
|
||||
const port = (server.address() as any).port;
|
||||
@@ -201,12 +285,31 @@ describe('per-route subgraph slicing', () => {
|
||||
|
||||
it('an always-run observer step receives its declared needs even when the route does not need them', async () => {
|
||||
let seen: any;
|
||||
const observer = (api: any) => api.scope.add({ kind: 'step', name: 'audit', needs: ['user'], provides: [], run: (ctx: any) => { seen = ctx.user; return {}; } });
|
||||
const observer = (api: any) =>
|
||||
api.scope.add({
|
||||
kind: 'step',
|
||||
name: 'audit',
|
||||
needs: ['user'],
|
||||
provides: [],
|
||||
run: (ctx: any) => {
|
||||
seen = ctx.user;
|
||||
return {};
|
||||
},
|
||||
});
|
||||
@Step({ provides: 'user', needs: [] })
|
||||
class Auth { run() { return { user: { id: 'u1' } }; } }
|
||||
class Auth {
|
||||
run() {
|
||||
return { user: { id: 'u1' } };
|
||||
}
|
||||
}
|
||||
@Route('/')
|
||||
class Ctl { @Get('/free') free() { return { ok: true }; } } // does NOT @needs('user')
|
||||
@Module({ mountpoint: '/', steps: [Auth], controllers: [Ctl] }) class M {}
|
||||
class Ctl {
|
||||
@Get('/free') free() {
|
||||
return { ok: true };
|
||||
}
|
||||
} // does NOT @needs('user')
|
||||
@Module({ mountpoint: '/', steps: [Auth], controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M], plugins: [observer] });
|
||||
const server = await app.listen(0);
|
||||
const port = (server.address() as any).port;
|
||||
@@ -221,10 +324,26 @@ import { toMermaid as renderMermaid } from '../src/graph-viz';
|
||||
|
||||
describe('app.graph / explain', () => {
|
||||
it('graph() returns nodes (with origin/needs/provides) and routes with their sliced chain', async () => {
|
||||
@Provider({ provides: 'db' }) class Db { provide() { return { db: 1 }; } }
|
||||
@Step({ provides: 'user', needs: ['db'] }) class Auth { run() { return { user: 1 }; } }
|
||||
@Route('/u') class Ctl { @Get('/:id') get(@needs('user') u: any) { return { u }; } }
|
||||
@Module({ mountpoint: '/api', providers: [Db], steps: [Auth], controllers: [Ctl] }) class M {}
|
||||
@Provider({ provides: 'db' })
|
||||
class Db {
|
||||
provide() {
|
||||
return { db: 1 };
|
||||
}
|
||||
}
|
||||
@Step({ provides: 'user', needs: ['db'] })
|
||||
class Auth {
|
||||
run() {
|
||||
return { user: 1 };
|
||||
}
|
||||
}
|
||||
@Route('/u')
|
||||
class Ctl {
|
||||
@Get('/:id') get(@needs('user') u: any) {
|
||||
return { u };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', providers: [Db], steps: [Auth], controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
const g = app.graph();
|
||||
expect(g.nodes.find((n) => n.name === 'db')).toMatchObject({ kind: 'provider', origin: 'module:M' });
|
||||
@@ -235,9 +354,20 @@ describe('app.graph / explain', () => {
|
||||
});
|
||||
|
||||
it('explain() returns the rich chain with origin and a handler entry', async () => {
|
||||
@Step({ provides: 'user', needs: [] }) class Auth { run() { return { user: 1 }; } }
|
||||
@Route('/u') class Ctl { @Get('/me') me(@needs('user') u: any) { return { u }; } }
|
||||
@Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] }) class M {}
|
||||
@Step({ provides: 'user', needs: [] })
|
||||
class Auth {
|
||||
run() {
|
||||
return { user: 1 };
|
||||
}
|
||||
}
|
||||
@Route('/u')
|
||||
class Ctl {
|
||||
@Get('/me') me(@needs('user') u: any) {
|
||||
return { u };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
const e = app.explain('/api/u/me');
|
||||
expect(e).toMatchObject({ pattern: '/api/u/me', method: 'GET', transport: 'buffer' });
|
||||
@@ -249,34 +379,79 @@ describe('app.graph / explain', () => {
|
||||
describe('devGraph endpoint', () => {
|
||||
const portOf = (s: any) => (s.address() as any).port;
|
||||
it('serves /__graph__ as HTML when devGraph:true', async () => {
|
||||
@Route('/u') class Ctl { @Get('/me') me() { return { ok: 1 }; } }
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] }) class M {}
|
||||
@Route('/u')
|
||||
class Ctl {
|
||||
@Get('/me') me() {
|
||||
return { ok: 1 };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M], devGraph: true });
|
||||
const s = await app.listen(0);
|
||||
const html = await fetch(`http://127.0.0.1:${portOf(s)}/__graph__`).then((r) => r.text());
|
||||
expect(html).toContain('class="mermaid"');
|
||||
expect(html).toContain('flowchart');
|
||||
expect(html).toContain('cytoscape');
|
||||
expect(html).toContain('/api/u/me');
|
||||
const mmd = await fetch(`http://127.0.0.1:${portOf(s)}/__graph__`, { headers: { accept: 'text/plain' } });
|
||||
expect(mmd.headers.get('content-type')).toContain('text/plain');
|
||||
expect(await mmd.text()).toContain('flowchart');
|
||||
s.close();
|
||||
});
|
||||
it('does NOT mount /__graph__ without devGraph', async () => {
|
||||
@Route('/u') class Ctl { @Get('/me') me() { return { ok: 1 }; } }
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] }) class M {}
|
||||
@Route('/u')
|
||||
class Ctl {
|
||||
@Get('/me') me() {
|
||||
return { ok: 1 };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
const s = await app.listen(0);
|
||||
const res = await fetch(`http://127.0.0.1:${portOf(s)}/__graph__`);
|
||||
expect(res.status).toBe(404);
|
||||
s.close();
|
||||
});
|
||||
|
||||
it('serves /__graph__ and /__openapi__ over app.fetch too (runtime-agnostic dev tools)', async () => {
|
||||
@Route('/u')
|
||||
class Ctl {
|
||||
@Get('/me') me() {
|
||||
return { ok: 1 };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M], devGraph: true, devOpenapi: true });
|
||||
|
||||
const graph = await app.fetch(new Request('http://x/__graph__'));
|
||||
expect(graph.status).toBe(200);
|
||||
expect(await graph.text()).toContain('cytoscape');
|
||||
|
||||
const openapi = await app.fetch(new Request('http://x/__openapi__'));
|
||||
expect(openapi.status).toBe(200);
|
||||
expect(((await openapi.json()) as { openapi: string }).openapi).toBe('3.1.0');
|
||||
|
||||
// still absent when the flags are off, on the fetch path too
|
||||
const off = createApp({ modules: [M] });
|
||||
expect((await off.fetch(new Request('http://x/__graph__'))).status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('graceful shutdown', () => {
|
||||
it('app.close() stops accepting and resolves, even with an SSE stream open', async () => {
|
||||
@Route('/')
|
||||
class Ctl { @Sse('/ticks') ticks() { return (async function* () { yield { t: 1 }; await new Promise((r) => setTimeout(r, 1000)); yield { t: 2 }; })(); } }
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] }) class M {}
|
||||
class Ctl {
|
||||
@Sse('/ticks') ticks() {
|
||||
return (async function* () {
|
||||
yield { t: 1 };
|
||||
await new Promise((r) => setTimeout(r, 1000));
|
||||
yield { t: 2 };
|
||||
})();
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
const server = await app.listen(0);
|
||||
const port = (server.address() as any).port;
|
||||
@@ -294,26 +469,54 @@ describe('graceful shutdown', () => {
|
||||
describe('overrides', () => {
|
||||
const portOf = (s: any) => (s.address() as any).port;
|
||||
it('overrides a provider token with a plain value (wrapped as a merge object)', async () => {
|
||||
@Provider({ provides: 'db' }) class Db { provide() { return { db: { real: true } }; } }
|
||||
@Route('/u') class Ctl { @Get('/x') x(@needs('db') db: any) { return { db }; } }
|
||||
@Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] }) class M {}
|
||||
@Provider({ provides: 'db' })
|
||||
class Db {
|
||||
provide() {
|
||||
return { db: { real: true } };
|
||||
}
|
||||
}
|
||||
@Route('/u')
|
||||
class Ctl {
|
||||
@Get('/x') x(@needs('db') db: any) {
|
||||
return { db };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M], overrides: { db: { fake: true } } });
|
||||
const s = await app.listen(0);
|
||||
expect(await fetch(`http://127.0.0.1:${portOf(s)}/api/u/x`).then((r) => r.json())).toEqual({ db: { fake: true } });
|
||||
s.close();
|
||||
});
|
||||
it('overrides with a function runner', async () => {
|
||||
@Provider({ provides: 'db' }) class Db { provide() { return { db: 'real' }; } }
|
||||
@Route('/u') class Ctl { @Get('/x') x(@needs('db') db: any) { return { db }; } }
|
||||
@Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] }) class M {}
|
||||
@Provider({ provides: 'db' })
|
||||
class Db {
|
||||
provide() {
|
||||
return { db: 'real' };
|
||||
}
|
||||
}
|
||||
@Route('/u')
|
||||
class Ctl {
|
||||
@Get('/x') x(@needs('db') db: any) {
|
||||
return { db };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M], overrides: { db: () => ({ db: 'fn' }) } });
|
||||
const s = await app.listen(0);
|
||||
expect(await fetch(`http://127.0.0.1:${portOf(s)}/api/u/x`).then((r) => r.json())).toEqual({ db: 'fn' });
|
||||
s.close();
|
||||
});
|
||||
it('rejects an override for an unknown token', async () => {
|
||||
@Route('/u') class Ctl { @Get('/x') x() { return { ok: 1 }; } }
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] }) class M {}
|
||||
@Route('/u')
|
||||
class Ctl {
|
||||
@Get('/x') x() {
|
||||
return { ok: 1 };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M], overrides: { nope: 1 } });
|
||||
await expect(app.listen(0)).rejects.toThrow(/unknown token 'nope'/);
|
||||
});
|
||||
@@ -321,8 +524,14 @@ describe('overrides', () => {
|
||||
|
||||
describe('rooms auto-provide', () => {
|
||||
it('injects a built-in rooms instance resolvable via @needs("rooms")', async () => {
|
||||
@Route('/r') class Ctl { @Get('/x') x(@needs('rooms') rooms: Rooms) { return { ok: rooms instanceof Rooms }; } }
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] }) class M {}
|
||||
@Route('/r')
|
||||
class Ctl {
|
||||
@Get('/x') x(@needs('rooms') rooms: Rooms) {
|
||||
return { ok: rooms instanceof Rooms };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
const s = await app.listen(0);
|
||||
const port = (s.address() as any).port;
|
||||
@@ -330,9 +539,83 @@ describe('rooms auto-provide', () => {
|
||||
s.close();
|
||||
});
|
||||
it('a user-declared rooms provider wins (no duplicate-name throw)', () => {
|
||||
@Provider({ provides: 'rooms' }) class MyRooms { provide() { return { rooms: { custom: true } }; } }
|
||||
@Route('/r') class Ctl { @Get('/x') x(@needs('rooms') rooms: any) { return rooms; } }
|
||||
@Module({ mountpoint: '/api', providers: [MyRooms], controllers: [Ctl] }) class M {}
|
||||
@Provider({ provides: 'rooms' })
|
||||
class MyRooms {
|
||||
provide() {
|
||||
return { rooms: { custom: true } };
|
||||
}
|
||||
}
|
||||
@Route('/r')
|
||||
class Ctl {
|
||||
@Get('/x') x(@needs('rooms') rooms: any) {
|
||||
return rooms;
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', providers: [MyRooms], controllers: [Ctl] })
|
||||
class M {}
|
||||
expect(() => createApp({ modules: [M] })).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
test('per-route maxBodyBytes overrides the server default', async () => {
|
||||
@Route('/up')
|
||||
class C {
|
||||
@Post('/small', { maxBodyBytes: 10 }) small(@body() _b: unknown) {
|
||||
return { ok: true };
|
||||
}
|
||||
@Post('/big') big(@body() _b: unknown) {
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', providers: [], steps: [], controllers: [C] })
|
||||
class M {}
|
||||
|
||||
const app = createApp({ modules: [M], limits: { maxBodyBytes: 1000 } });
|
||||
const server = await app.listen(0);
|
||||
const port = (server.address() as any).port;
|
||||
const payload = JSON.stringify({ x: 'aaaaaaaaaaaaaaaaaaaa' }); // ~30 bytes, over the route's 10-byte cap
|
||||
const opts = { method: 'POST', headers: { 'content-type': 'application/json' }, body: payload };
|
||||
|
||||
const tight = await fetch(`http://127.0.0.1:${port}/up/small`, opts);
|
||||
expect(tight.status).toBe(413); // per-route cap of 10 bytes
|
||||
const loose = await fetch(`http://127.0.0.1:${port}/up/big`, opts);
|
||||
expect(loose.status).toBe(200); // falls back to the server's 1000-byte limit
|
||||
|
||||
server.close();
|
||||
});
|
||||
|
||||
describe('route table validation', () => {
|
||||
it('rejects routes with the same method and effective pattern', () => {
|
||||
@Route('/users')
|
||||
class DuplicateCtl {
|
||||
@Get('/:id') byId() {
|
||||
return {};
|
||||
}
|
||||
@Get('/:name') byName() {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [DuplicateCtl] })
|
||||
class DuplicateModule {}
|
||||
|
||||
expect(() => createApp({ modules: [DuplicateModule] })).toThrow(
|
||||
/ambiguous route GET.*\/api\/users\/:name.*DuplicateCtl\.byName.*DuplicateCtl\.byId/,
|
||||
);
|
||||
});
|
||||
|
||||
it('allows the same effective pattern under different methods', () => {
|
||||
@Route('/users')
|
||||
class MethodsCtl {
|
||||
@Get('/:id') get() {
|
||||
return {};
|
||||
}
|
||||
@Post('/:name') post() {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [MethodsCtl] })
|
||||
class MethodsModule {}
|
||||
|
||||
expect(() => createApp({ modules: [MethodsModule] })).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { aggregate } from '../bench/stats';
|
||||
import { renderMarkdown } from '../bench/render';
|
||||
|
||||
describe('aggregate', () => {
|
||||
it('median, stddev, cv, min/max over run req/s', () => {
|
||||
const a = aggregate([100, 110, 120, 130, 140]);
|
||||
expect(a.median).toBe(120);
|
||||
expect(a.min).toBe(100);
|
||||
expect(a.max).toBe(140);
|
||||
expect(a.stddev).toBeGreaterThan(0);
|
||||
expect(a.cv).toBeCloseTo(a.stddev / a.mean, 6);
|
||||
});
|
||||
});
|
||||
|
||||
describe('renderMarkdown', () => {
|
||||
const data = {
|
||||
env: {
|
||||
date: '2026-07-06',
|
||||
commit: 'abc123',
|
||||
node: 'v18.19.0',
|
||||
os: 'darwin',
|
||||
cpu: 'M1 (8 cores)',
|
||||
ram: '16 GB',
|
||||
pinned: false,
|
||||
},
|
||||
config: { conns: 100, duration: 10, runs: 5, warmup: 1, pipelining: 1 },
|
||||
scenarios: [
|
||||
{
|
||||
title: 'JSON hello (overhead)',
|
||||
name: 'hello',
|
||||
approximation: false,
|
||||
rows: [
|
||||
{
|
||||
framework: 'fastify',
|
||||
reqSec: { median: 50000, min: 49000, max: 51000, stddev: 700, cv: 0.014 },
|
||||
p50: 1.5,
|
||||
p99: 4,
|
||||
p999: 9,
|
||||
},
|
||||
{
|
||||
framework: 'green-tea',
|
||||
reqSec: { median: 42000, min: 41000, max: 43000, stddev: 600, cv: 0.014 },
|
||||
p50: 1.9,
|
||||
p99: 5,
|
||||
p999: 11,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
stepScaling: [
|
||||
{ path: '/steps/0', steps: 0, reqSec: 45000 },
|
||||
{ path: '/steps/3', steps: 3, reqSec: 40000 },
|
||||
],
|
||||
secureCost: [
|
||||
{ label: 'security:false (parity)', reqSec: 45000 },
|
||||
{ label: 'security:true (default)', reqSec: 43000 },
|
||||
],
|
||||
};
|
||||
it('renders env header, a per-scenario table with a row per framework, and the micro-bench sections', () => {
|
||||
const md = renderMarkdown(data as any);
|
||||
expect(md).toContain('# green-tea Benchmarks');
|
||||
expect(md).toContain('abc123'); // commit
|
||||
expect(md).toContain('single-box'); // contention caveat
|
||||
expect(md).toContain('JSON hello (overhead)');
|
||||
expect(md).toContain('fastify');
|
||||
expect(md).toContain('green-tea');
|
||||
expect(md).toMatch(/req\/s/i);
|
||||
expect(md).toContain('p99');
|
||||
expect(md).toContain('Step-scaling');
|
||||
expect(md).toContain('secure-by-default');
|
||||
expect(md).toContain('approximation'); // methodology mentions the pipeline approximation
|
||||
});
|
||||
it('sorts each scenario rows by median req/s descending', () => {
|
||||
const md = renderMarkdown(data as any);
|
||||
expect(md.indexOf('fastify')).toBeLessThan(md.indexOf('green-tea')); // fastify (50k) before green-tea (42k)
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
// Real Bun integration test for mesh: a teapot exporting its scopes and a teacup consuming
|
||||
// them, both under the actual Bun runtime, driven entirely through serveBun.
|
||||
//
|
||||
// Bun's ws lifecycle differs from Deno's — its socket events land on a server-level handler
|
||||
// rather than the socket — so the control channel reaching app.upgrade here is a distinct
|
||||
// path from the Deno test, not a duplicate of it.
|
||||
//
|
||||
// Run with: npm run test:bun
|
||||
import 'reflect-metadata';
|
||||
import { test, expect } from 'bun:test';
|
||||
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts';
|
||||
import { serveBun } from '../../src/bun.ts';
|
||||
|
||||
const SECRET = 's3cr3t';
|
||||
|
||||
@Provider({ provides: 'config', export: true })
|
||||
class Config {
|
||||
provide() {
|
||||
return { config: { region: 'mx', runtime: 'bun' } };
|
||||
}
|
||||
}
|
||||
@Step({ provides: 'auth', needs: [], export: true })
|
||||
class Auth {
|
||||
run(ctx: any) {
|
||||
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
|
||||
class TeapotModule {}
|
||||
|
||||
@Route('/local')
|
||||
class LocalCtl {
|
||||
@Get('/who')
|
||||
who(@needs('config') config: any, @needs('auth') auth: any) {
|
||||
return { config, auth };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
|
||||
class TeacupModule {}
|
||||
|
||||
const controlUrl = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`;
|
||||
|
||||
test('mesh on Bun: teacup resolves a Bun teapot through the graph', async () => {
|
||||
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||
const tServer = serveBun(teapot, { port: 0 });
|
||||
|
||||
const teacup = createApp({
|
||||
modules: [TeacupModule],
|
||||
experimental: true,
|
||||
mesh: { teapots: [{ url: controlUrl(tServer.port), secret: SECRET }] },
|
||||
});
|
||||
const cServer = serveBun(teacup, { port: 0 });
|
||||
|
||||
try {
|
||||
const res = await fetch(`http://127.0.0.1:${cServer.port}/api/local/who`, { headers: { 'x-token': 'abc' } });
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({
|
||||
config: { region: 'mx', runtime: 'bun' },
|
||||
auth: { token: 'abc' },
|
||||
});
|
||||
} finally {
|
||||
await teacup.close();
|
||||
cServer.stop(true);
|
||||
tServer.stop(true);
|
||||
}
|
||||
});
|
||||
|
||||
test('mesh on Bun: a teapot refuses a bad secret over its control channel', async () => {
|
||||
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||
const tServer = serveBun(teapot, { port: 0 });
|
||||
|
||||
const teacup = createApp({
|
||||
modules: [TeacupModule],
|
||||
experimental: true,
|
||||
mesh: { teapots: [{ url: controlUrl(tServer.port), secret: 'WRONG' }], timeoutMs: 1000 },
|
||||
});
|
||||
|
||||
try {
|
||||
await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow(/mesh/);
|
||||
} finally {
|
||||
await teacup.close();
|
||||
tServer.stop(true);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
// Real Bun integration test for serveBun: boots an app under the actual Bun runtime
|
||||
// and round-trips both HTTP (app.fetch) and WebSocket (Bun's server-level websocket
|
||||
// handler -> app.upgrade).
|
||||
//
|
||||
// Run with: npm run test:bun (or: bun test test/bun/)
|
||||
import 'reflect-metadata';
|
||||
import { test, expect } from 'bun:test';
|
||||
import { createApp, Route, Get, Ws, ctx, Module } from '../../src/index.ts';
|
||||
import { serveBun } from '../../src/bun.ts';
|
||||
|
||||
@Route('/rt')
|
||||
class Rt {
|
||||
@Get('/hello')
|
||||
hello() {
|
||||
return { ok: true };
|
||||
}
|
||||
@Ws('/echo')
|
||||
echo(@ctx() { inbound }: any) {
|
||||
return (async function* () {
|
||||
for await (const msg of inbound) yield `echo:${msg}`;
|
||||
})();
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Rt] })
|
||||
class M {}
|
||||
|
||||
test('serveBun: HTTP + WebSocket round-trip', async () => {
|
||||
const app = createApp({ modules: [M] });
|
||||
const server = serveBun(app, { port: 0 });
|
||||
const port = server.port;
|
||||
try {
|
||||
const httpRes = await fetch(`http://127.0.0.1:${port}/rt/hello`);
|
||||
expect(httpRes.status).toBe(200);
|
||||
expect((await httpRes.json()).ok).toBe(true);
|
||||
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}/rt/echo`);
|
||||
const got = await new Promise<string>((resolve, reject) => {
|
||||
ws.onopen = () => ws.send('hi');
|
||||
ws.onmessage = (e) => {
|
||||
resolve(String(e.data));
|
||||
ws.close();
|
||||
};
|
||||
ws.onerror = () => reject(new Error('ws error'));
|
||||
});
|
||||
expect(got).toBe('echo:hi');
|
||||
} finally {
|
||||
server.stop(true);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import { afterEach, expect, it, vi } from 'vitest';
|
||||
import type { App } from '../src/app/types';
|
||||
import { serveDeno } from '../src/deno';
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('snapshots connection metadata before Deno invalidates the upgraded request', async () => {
|
||||
let upgraded = false;
|
||||
let handler: ((request: Request, info: unknown) => Response | Promise<Response>) | undefined;
|
||||
const socket = {
|
||||
readyState: 1,
|
||||
binaryType: '',
|
||||
send: vi.fn(),
|
||||
close: vi.fn(),
|
||||
addEventListener: vi.fn(),
|
||||
};
|
||||
|
||||
vi.stubGlobal('Deno', {
|
||||
serve: (_options: unknown, next: typeof handler) => {
|
||||
handler = next;
|
||||
return { finished: Promise.resolve(), shutdown: vi.fn() };
|
||||
},
|
||||
upgradeWebSocket: () => {
|
||||
upgraded = true;
|
||||
return { socket, response: new Response() };
|
||||
},
|
||||
});
|
||||
|
||||
const upgrade = vi.fn().mockResolvedValue(undefined);
|
||||
serveDeno({ upgrade } as unknown as App);
|
||||
const info = {
|
||||
get remoteAddr() {
|
||||
if (upgraded) throw new TypeError('Request closed');
|
||||
return { hostname: '127.0.0.1', port: 1234, transport: 'tcp' };
|
||||
},
|
||||
};
|
||||
const request = new Request('http://localhost/socket?token=x', {
|
||||
headers: { upgrade: 'websocket', 'x-test': 'yes' },
|
||||
});
|
||||
|
||||
expect(() => handler!(request, info)).not.toThrow();
|
||||
await vi.waitFor(() =>
|
||||
expect(upgrade).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ url: '/socket?token=x', ip: '127.0.0.1' }),
|
||||
expect.any(Object),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,170 @@
|
||||
// Cross-runtime mesh: a Node peer and a Deno peer, in separate processes, talking over the
|
||||
// wire protocol. This is the test the whole cross-runtime effort exists for.
|
||||
//
|
||||
// Deno<->Deno and Node<->Node passing prove each runtime works with itself; neither proves a
|
||||
// Node teapot can serve a Deno teacup, which is the shape mesh actually deploys in once it
|
||||
// spans runtimes. The two sides use genuinely different code here — Node serves through the
|
||||
// `ws` package (WebSocketServer + nodeSocket) and connects with it too; Deno uses its global
|
||||
// WebSocket both ways — so only a real cross-process run exercises the pairing.
|
||||
//
|
||||
// Run with: npm run test:deno (needs --allow-run to spawn the Node peer)
|
||||
import 'npm:reflect-metadata';
|
||||
import { assertEquals, assertStringIncludes } from 'jsr:@std/assert';
|
||||
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts';
|
||||
|
||||
const SECRET = 's3cr3t';
|
||||
const NODE_PEER = 'test/interop/_node-peer.ts';
|
||||
|
||||
@Provider({ provides: 'config', export: true })
|
||||
class Config {
|
||||
provide() {
|
||||
return { config: { region: 'mx', runtime: 'deno' } };
|
||||
}
|
||||
}
|
||||
@Step({ provides: 'auth', needs: [], export: true })
|
||||
class Auth {
|
||||
run(ctx: any) {
|
||||
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
|
||||
class TeapotModule {}
|
||||
|
||||
@Route('/local')
|
||||
class LocalCtl {
|
||||
@Get('/who')
|
||||
who(@needs('config') config: any, @needs('auth') auth: any) {
|
||||
return { config, auth };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
|
||||
class TeacupModule {}
|
||||
|
||||
const controlUrl = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`;
|
||||
|
||||
/** Spawns the Node peer under tsx, streaming its stdout lines. */
|
||||
function spawnNodePeer(args: string[]) {
|
||||
const child = new Deno.Command('npx', {
|
||||
args: ['tsx', NODE_PEER, ...args],
|
||||
env: { ...Deno.env.toObject(), MESH_SECRET: SECRET },
|
||||
stdout: 'piped',
|
||||
stderr: 'piped',
|
||||
}).spawn();
|
||||
|
||||
return child;
|
||||
}
|
||||
|
||||
/** Reads stdout until a JSON line parses, or the peer dies / we run out of patience. */
|
||||
async function firstJsonLine(child: Deno.ChildProcess, timeoutMs = 30_000): Promise<any> {
|
||||
const reader = child.stdout.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
|
||||
try {
|
||||
while (Date.now() < deadline) {
|
||||
const { value, done } = await reader.read();
|
||||
if (done) break;
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
|
||||
for (const line of buffer.split('\n')) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed.startsWith('{')) continue;
|
||||
try {
|
||||
return JSON.parse(trimmed);
|
||||
} catch {
|
||||
/* partial line; keep reading */
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
|
||||
throw new Error(`node peer produced no JSON line within ${timeoutMs}ms`);
|
||||
}
|
||||
|
||||
async function kill(child: Deno.ChildProcess): Promise<void> {
|
||||
try {
|
||||
child.kill('SIGKILL');
|
||||
} catch {
|
||||
/* already gone */
|
||||
}
|
||||
await child.status;
|
||||
try {
|
||||
await child.stdout.cancel();
|
||||
await child.stderr.cancel();
|
||||
} catch {
|
||||
/* already released */
|
||||
}
|
||||
}
|
||||
|
||||
Deno.test('interop: a Deno teacup consumes a Node teapot', async () => {
|
||||
const node = spawnNodePeer(['teapot']);
|
||||
const { port } = await firstJsonLine(node);
|
||||
|
||||
const teacup = createApp({
|
||||
modules: [TeacupModule],
|
||||
experimental: true,
|
||||
mesh: { teapots: [{ url: controlUrl(port), secret: SECRET }], timeoutMs: 5000 },
|
||||
});
|
||||
|
||||
try {
|
||||
const res = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } }));
|
||||
assertEquals(res.status, 200);
|
||||
// the config came from the Node process: proof the scope crossed the runtime boundary
|
||||
assertEquals(await res.json(), {
|
||||
config: { region: 'mx', runtime: 'node' },
|
||||
auth: { token: 'abc' },
|
||||
});
|
||||
} finally {
|
||||
await teacup.close();
|
||||
await kill(node);
|
||||
}
|
||||
});
|
||||
|
||||
Deno.test('interop: a Node teacup consumes a Deno teapot', async () => {
|
||||
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||
let port = 0;
|
||||
const { serveDeno } = await import('../../src/deno.ts');
|
||||
const server = serveDeno(teapot, {
|
||||
port: 0,
|
||||
onListen: (addr) => {
|
||||
port = addr.port;
|
||||
},
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
|
||||
const node = spawnNodePeer(['teacup', controlUrl(port)]);
|
||||
|
||||
try {
|
||||
const result = await firstJsonLine(node);
|
||||
assertEquals(result.ok, true);
|
||||
// the Node peer resolved a scope served by Deno's app.upgrade control channel
|
||||
assertEquals(result.body.config, { region: 'mx', runtime: 'deno' });
|
||||
assertEquals(result.body.auth, { token: 'abc' });
|
||||
} finally {
|
||||
await kill(node);
|
||||
await server.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
Deno.test('interop: a version-skewed peer is refused across runtimes', async () => {
|
||||
const node = spawnNodePeer(['teapot']);
|
||||
const { port } = await firstJsonLine(node);
|
||||
|
||||
try {
|
||||
// hand-rolled peer speaking a future protocol: the teapot must refuse before the secret
|
||||
const ws = new WebSocket(controlUrl(port));
|
||||
const closed = await new Promise<{ code: number; reason: string }>((resolve, reject) => {
|
||||
ws.onopen = () => ws.send(JSON.stringify({ type: 'hello', v: 999, secret: SECRET }));
|
||||
ws.onclose = (e) => resolve({ code: e.code, reason: e.reason });
|
||||
ws.onerror = () => reject(new Error('ws error'));
|
||||
});
|
||||
|
||||
assertEquals(closed.code, 1008);
|
||||
assertStringIncludes(closed.reason, '999');
|
||||
} finally {
|
||||
await kill(node);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
// Real Deno integration test for mesh: a teapot exporting its scopes and a teacup consuming
|
||||
// them, both under the actual Deno runtime, driven entirely through serveDeno.
|
||||
//
|
||||
// This is the test that makes "mesh runs off Node" a fact rather than an intention. It covers,
|
||||
// in one round-trip, everything that used to be Node-only:
|
||||
// - the teacup's WebSocket client is Deno's global (no `ws` package here at all)
|
||||
// - the teapot's control channel is served via app.upgrade (Deno has no server.on('upgrade'))
|
||||
// - the graph boots on the first request; `listen()` is never called and cannot be
|
||||
// - node:crypto's timingSafeEqual + Buffer resolve under Deno's node-compat
|
||||
//
|
||||
// Run with: npm run test:deno
|
||||
// `--no-check`: see the note in ws.test.ts — Deno type-checks the whole reachable graph,
|
||||
// including Node-only modules this test never executes. tsc covers those.
|
||||
import 'npm:reflect-metadata';
|
||||
import { assertEquals, assertStringIncludes } from 'jsr:@std/assert';
|
||||
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts';
|
||||
import { serveDeno } from '../../src/deno.ts';
|
||||
|
||||
const SECRET = 's3cr3t';
|
||||
|
||||
@Provider({ provides: 'config', export: true })
|
||||
class Config {
|
||||
provide() {
|
||||
return { config: { region: 'mx', runtime: 'deno' } };
|
||||
}
|
||||
}
|
||||
@Step({ provides: 'auth', needs: [], export: true })
|
||||
class Auth {
|
||||
run(ctx: any) {
|
||||
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
|
||||
class TeapotModule {}
|
||||
|
||||
@Route('/local')
|
||||
class LocalCtl {
|
||||
@Get('/who')
|
||||
who(@needs('config') config: any, @needs('auth') auth: any) {
|
||||
return { config, auth };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
|
||||
class TeacupModule {}
|
||||
|
||||
/** Starts an app on Deno and resolves once its port is known. */
|
||||
async function serve(app: ReturnType<typeof createApp>) {
|
||||
let port = 0;
|
||||
const server = serveDeno(app, {
|
||||
port: 0,
|
||||
onListen: (addr) => {
|
||||
port = addr.port;
|
||||
},
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
return { server, port };
|
||||
}
|
||||
|
||||
const controlUrl = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`;
|
||||
|
||||
Deno.test('mesh on Deno: teacup resolves a Deno teapot through the graph', async () => {
|
||||
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||
const t = await serve(teapot);
|
||||
|
||||
const teacup = createApp({
|
||||
modules: [TeacupModule],
|
||||
experimental: true,
|
||||
mesh: { teapots: [{ url: controlUrl(t.port), secret: SECRET }] },
|
||||
});
|
||||
const c = await serve(teacup);
|
||||
|
||||
try {
|
||||
const res = await fetch(`http://127.0.0.1:${c.port}/api/local/who`, { headers: { 'x-token': 'abc' } });
|
||||
assertEquals(res.status, 200);
|
||||
assertEquals(await res.json(), {
|
||||
config: { region: 'mx', runtime: 'deno' },
|
||||
auth: { token: 'abc' },
|
||||
});
|
||||
} finally {
|
||||
await teacup.close();
|
||||
await c.server.shutdown();
|
||||
await t.server.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
Deno.test('mesh on Deno: a teapot refuses a bad secret over its control channel', async () => {
|
||||
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||
const t = await serve(teapot);
|
||||
|
||||
const teacup = createApp({
|
||||
modules: [TeacupModule],
|
||||
experimental: true,
|
||||
mesh: { teapots: [{ url: controlUrl(t.port), secret: 'WRONG' }], timeoutMs: 1000 },
|
||||
});
|
||||
|
||||
try {
|
||||
let message = '';
|
||||
try {
|
||||
await teacup.fetch(new Request('http://x/api/local/who'));
|
||||
} catch (err) {
|
||||
message = String((err as Error).message);
|
||||
}
|
||||
assertStringIncludes(message, 'mesh');
|
||||
} finally {
|
||||
await teacup.close();
|
||||
await t.server.shutdown();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
// Real Deno integration test for serveDeno: boots an app under the actual Deno runtime
|
||||
// and round-trips both HTTP (app.fetch) and WebSocket (Deno.upgradeWebSocket -> app.upgrade).
|
||||
//
|
||||
// Run with: npm run test:deno (or: deno test --allow-net --allow-read --no-check test/deno/)
|
||||
//
|
||||
// `--no-check`: the barrel (`src/index.ts`) re-exports types from Node-only modules
|
||||
// (e.g. `src/http/*`) that reference ambient Node globals like `Buffer`. Those modules
|
||||
// aren't executed under Deno (this test only exercises `serveDeno`'s fetch/WebSocket
|
||||
// path), but Deno's checker still type-checks the whole reachable graph and has no
|
||||
// ambient `Buffer` type without a full `@types/node` setup. Node-side static typing for
|
||||
// those modules is already covered by `npm run typecheck` (tsc); this test's job is to
|
||||
// prove Deno *runtime* behavior of the adapter, not re-typecheck Node-only internals.
|
||||
import 'npm:reflect-metadata';
|
||||
import { assertEquals } from 'jsr:@std/assert';
|
||||
import { createApp, Route, Ws, Get, Module, ctx } from '../../src/index.ts';
|
||||
import { serveDeno } from '../../src/deno.ts';
|
||||
|
||||
@Route('/rt')
|
||||
class Rt {
|
||||
@Get('/hello')
|
||||
hello() {
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
@Ws('/echo')
|
||||
echo(@ctx() { inbound }: any) {
|
||||
return (async function* () {
|
||||
for await (const msg of inbound) yield `echo:${msg}`;
|
||||
})();
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/', controllers: [Rt] })
|
||||
class M {}
|
||||
|
||||
Deno.test('serveDeno: HTTP + WebSocket round-trip through the graph', async () => {
|
||||
const app = createApp({ modules: [M] });
|
||||
|
||||
let port = 0;
|
||||
const server = serveDeno(app, {
|
||||
port: 0,
|
||||
onListen: (addr) => {
|
||||
port = addr.port;
|
||||
},
|
||||
});
|
||||
|
||||
// Let onListen fire before we try to connect.
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
|
||||
try {
|
||||
const httpRes = await fetch(`http://127.0.0.1:${port}/rt/hello`);
|
||||
assertEquals(httpRes.status, 200);
|
||||
assertEquals((await httpRes.json()).ok, true);
|
||||
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}/rt/echo`);
|
||||
try {
|
||||
const got = await new Promise<string>((resolve, reject) => {
|
||||
ws.onopen = () => ws.send('hi');
|
||||
ws.onmessage = (e) => resolve(String(e.data));
|
||||
ws.onerror = () => reject(new Error('ws error'));
|
||||
});
|
||||
assertEquals(got, 'echo:hi');
|
||||
} finally {
|
||||
ws.close();
|
||||
// Give the close frame a moment to complete the handshake so no socket is leaked.
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
}
|
||||
} finally {
|
||||
await server.shutdown();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
// Real Miniflare (workerd) integration test for edgeHandler: bundles test/edge/worker.ts
|
||||
// for the Cloudflare Workers runtime and boots it in the actual workerd engine (via the
|
||||
// `miniflare` npm package — no CF account/deploy needed), then round-trips HTTP + WS
|
||||
// through the real graph.
|
||||
//
|
||||
// Run with: npm run test:edge
|
||||
//
|
||||
// NODEJS_COMPAT: workerd's `nodejs_compat` genuinely does NOT implement `node:http`/
|
||||
// `node:https` (confirmed in isolation: `node:crypto`, `node:stream`, `node:net`, `node:tls`,
|
||||
// `node:events`, `node:util`, `node:buffer` all load fine under the same flags/compat date;
|
||||
// only `http`/`https` fail with "Uncaught Error: No such module 'node:http'" at worker LOAD
|
||||
// time) — a real platform gap, not a bundler misconfiguration. The barrel used to statically
|
||||
// VALUE-import `http`/`https` for the Node `listen()` path even though `edgeHandler` never
|
||||
// touches them, which broke worker load with no shim. The fix (see src/http/server.ts,
|
||||
// src/app/index.ts, and the other src/http/*.ts files) converts every `http`/`https` import
|
||||
// to `import type` (zero runtime code) and lazy-`require()`s them only inside
|
||||
// `createHttpServer`, which the edge path never calls. That means the real barrel now loads
|
||||
// on workerd with no test-time stub — this run exercises it as-is.
|
||||
import { strict as assert } from 'node:assert';
|
||||
import { build } from 'esbuild';
|
||||
import { Miniflare } from 'miniflare';
|
||||
|
||||
const BUNDLE = 'test/edge/_worker.mjs';
|
||||
|
||||
async function main() {
|
||||
// Bundle the worker for workerd: ESM, Node builtins left external + aliased to node:*
|
||||
// so workerd's nodejs_compat provides them (not esbuild). `http`/`https` are no longer
|
||||
// imported as VALUES by the barrel at module-eval time (see comment above) — they're now
|
||||
// `import type` (erased) plus a lazy `require()` reached only from `createHttpServer`,
|
||||
// which `edgeHandler` never calls. esbuild still needs a resolution for that bare
|
||||
// `require('http')`/`require('https')` text even though it's dead code on this path, so
|
||||
// they're marked external here (left unresolved, exactly like the `node:*` builtins) rather
|
||||
// than stubbed — no fake implementation is provided, and the real barrel is what's tested.
|
||||
await build({
|
||||
entryPoints: ['test/edge/worker.ts'],
|
||||
bundle: true,
|
||||
format: 'esm',
|
||||
outfile: BUNDLE,
|
||||
platform: 'browser', // workerd is not node; keep esbuild from injecting node shims
|
||||
target: 'esnext',
|
||||
// Leave Node builtins for workerd's nodejs_compat to resolve; http/https are external
|
||||
// too (unresolved, never called by edgeHandler) since workerd has no node:http/https.
|
||||
external: ['node:*', 'http', 'https'],
|
||||
alias: {
|
||||
crypto: 'node:crypto',
|
||||
stream: 'node:stream',
|
||||
zlib: 'node:zlib',
|
||||
buffer: 'node:buffer',
|
||||
events: 'node:events',
|
||||
net: 'node:net',
|
||||
tls: 'node:tls',
|
||||
util: 'node:util',
|
||||
},
|
||||
});
|
||||
|
||||
const mf = new Miniflare({
|
||||
modules: true,
|
||||
scriptPath: BUNDLE,
|
||||
compatibilityDate: '2024-11-01',
|
||||
compatibilityFlags: ['nodejs_compat'],
|
||||
});
|
||||
|
||||
try {
|
||||
// HTTP
|
||||
const httpRes = await mf.dispatchFetch('http://localhost/rt/hello');
|
||||
assert.equal(httpRes.status, 200);
|
||||
assert.deepEqual(await httpRes.json(), { ok: true });
|
||||
|
||||
// WebSocket
|
||||
const wsRes = await mf.dispatchFetch('http://localhost/rt/echo', {
|
||||
headers: { Upgrade: 'websocket' },
|
||||
});
|
||||
assert.equal(wsRes.status, 101);
|
||||
const ws = wsRes.webSocket;
|
||||
assert.ok(ws, 'expected a client webSocket on the 101 response');
|
||||
ws.accept();
|
||||
const got = await new Promise<string>((resolve, reject) => {
|
||||
ws.addEventListener('message', (e: { data: unknown }) => {
|
||||
resolve(String(e.data));
|
||||
ws.close();
|
||||
});
|
||||
ws.addEventListener('error', () => reject(new Error('ws error')));
|
||||
ws.send('hi');
|
||||
});
|
||||
assert.equal(got, 'echo:hi');
|
||||
|
||||
console.log('edge (workerd via miniflare): HTTP 200 + WS echo:hi — PASS');
|
||||
} finally {
|
||||
await mf.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
// Worker entry for the real workerd (Miniflare) integration test.
|
||||
// Mirrors test/deno/ws.test.ts's graph so HTTP + WebSocket behavior is proven
|
||||
// identically across runtimes. Run via `npm run test:edge` (see test/edge/run.ts).
|
||||
import { createApp, Route, Get, Ws, ctx, Module } from '../../src/index';
|
||||
import { edgeHandler } from '../../src/edge';
|
||||
|
||||
@Route('/rt')
|
||||
class Rt {
|
||||
@Get('/hello')
|
||||
hello() {
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
@Ws('/echo')
|
||||
echo(@ctx() { inbound }: any) {
|
||||
return (async function* () {
|
||||
for await (const msg of inbound) yield `echo:${msg}`;
|
||||
})();
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/', controllers: [Rt] })
|
||||
class M {}
|
||||
|
||||
const app = createApp({ modules: [M] });
|
||||
|
||||
export default { fetch: edgeHandler(app) };
|
||||
@@ -0,0 +1,82 @@
|
||||
import 'reflect-metadata';
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createApp } from '../src/app';
|
||||
import { Route, Get, Module } from '../src/metadata';
|
||||
import { HttpError, Unauthorized, isHttpError } from '../src/signals';
|
||||
import type { ErrorRenderer } from '../src/transformers';
|
||||
|
||||
// Renders every error as HTML, reading the status off HttpError when present.
|
||||
const htmlErrors: ErrorRenderer = (error) => ({
|
||||
status: isHttpError(error) ? error.status : 500,
|
||||
headers: { 'content-type': 'text/html' },
|
||||
body: `<h1>${isHttpError(error) ? error.status : 500}</h1>`,
|
||||
});
|
||||
|
||||
@Route('/x')
|
||||
class Ctl {
|
||||
@Get('/boom') boom() {
|
||||
throw new Unauthorized('nope');
|
||||
}
|
||||
@Get('/ok') ok() {
|
||||
return { ok: true };
|
||||
}
|
||||
@Get('/teapot') teapot() {
|
||||
throw new HttpError(418, 'short and stout', { code: 'TEA', reason: 'short and stout' });
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
|
||||
async function serve(onError?: ErrorRenderer) {
|
||||
const app = createApp({ modules: [M], onError });
|
||||
const server = await app.listen(0);
|
||||
const port = (server.address() as any).port;
|
||||
return { server, base: `http://127.0.0.1:${port}` };
|
||||
}
|
||||
|
||||
describe('onError renderer', () => {
|
||||
it('renders a handler-thrown error through the hook (HTML, right status)', async () => {
|
||||
const { server, base } = await serve(htmlErrors);
|
||||
const res = await fetch(`${base}/x/boom`);
|
||||
expect(res.status).toBe(401);
|
||||
expect(res.headers.get('content-type')).toBe('text/html');
|
||||
expect(await res.text()).toBe('<h1>401</h1>');
|
||||
server.close();
|
||||
});
|
||||
|
||||
it('renders infra errors too — a no-route 404 goes through the hook', async () => {
|
||||
const { server, base } = await serve(htmlErrors);
|
||||
const res = await fetch(`${base}/nope`);
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.headers.get('content-type')).toBe('text/html');
|
||||
expect(await res.text()).toBe('<h1>404</h1>');
|
||||
server.close();
|
||||
});
|
||||
|
||||
it('falls back to the default JSON when the hook returns undefined', async () => {
|
||||
const { server, base } = await serve(() => undefined);
|
||||
const res = await fetch(`${base}/x/boom`);
|
||||
expect(res.status).toBe(401);
|
||||
expect(res.headers.get('content-type')).toBe('application/json');
|
||||
expect(await res.json()).toEqual({ error: 'nope' });
|
||||
server.close();
|
||||
});
|
||||
|
||||
it('with no hook, behavior is unchanged (default JSON 404)', async () => {
|
||||
const { server, base } = await serve();
|
||||
const res = await fetch(`${base}/nope`);
|
||||
expect(res.status).toBe(404);
|
||||
expect(await res.json()).toEqual({ error: 'Not Found' });
|
||||
server.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe('HttpError body', () => {
|
||||
it('an HttpError carrying a body renders that payload instead of { error: message }', async () => {
|
||||
const { server, base } = await serve();
|
||||
const res = await fetch(`${base}/x/teapot`);
|
||||
expect(res.status).toBe(418);
|
||||
expect(await res.json()).toEqual({ code: 'TEA', reason: 'short and stout' });
|
||||
server.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,147 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createApp, Provider, Route, Get, Post, Module, needs, body, ctx } from '../src/index';
|
||||
|
||||
@Provider({ provides: 'store' })
|
||||
class Store {
|
||||
provide() {
|
||||
return { store: { hi: 'ok' } };
|
||||
}
|
||||
}
|
||||
@Route('/api')
|
||||
class Ctl {
|
||||
@Get('/hello') hello(@needs('store') s: any) {
|
||||
return { store: s.hi };
|
||||
}
|
||||
@Post('/echo') echo(@body() b: any) {
|
||||
return { got: b };
|
||||
}
|
||||
@Post('/tiny', { maxBodyBytes: 10 }) tiny(@body() b: any) {
|
||||
return { got: b };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', providers: [Store], controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
|
||||
@Route('/mesh')
|
||||
class MeshCtl {
|
||||
@Get('/ping') ping() {
|
||||
return { pong: true };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [MeshCtl] })
|
||||
class MeshModule {}
|
||||
|
||||
describe('app.fetch', () => {
|
||||
it('handles GET and returns JSON 200', async () => {
|
||||
const res = await app.fetch(new Request('http://x/api/hello'));
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({ store: 'ok' });
|
||||
});
|
||||
it('parses a POST body', async () => {
|
||||
const res = await app.fetch(
|
||||
new Request('http://x/api/echo', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ a: 1 }),
|
||||
}),
|
||||
);
|
||||
expect(await res.json()).toEqual({ got: { a: 1 } });
|
||||
});
|
||||
it('404s an unknown route', async () => {
|
||||
const res = await app.fetch(new Request('http://x/nope'));
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
it('sets secure-by-default headers', async () => {
|
||||
const res = await app.fetch(new Request('http://x/api/hello'));
|
||||
expect(res.headers.get('x-content-type-options')).toBe('nosniff');
|
||||
});
|
||||
|
||||
it('a 413 (oversized body) still carries the injected security headers', async () => {
|
||||
const res = await app.fetch(
|
||||
new Request('http://x/api/tiny', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ x: 'well over ten bytes' }),
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(413);
|
||||
expect(res.headers.get('x-content-type-options')).toBe('nosniff');
|
||||
expect(res.headers.get('x-frame-options')).toBe('SAMEORIGIN');
|
||||
});
|
||||
|
||||
it('a 400 (invalid JSON) still carries the injected security headers', async () => {
|
||||
const res = await app.fetch(
|
||||
new Request('http://x/api/echo', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: '{not json',
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.headers.get('x-content-type-options')).toBe('nosniff');
|
||||
});
|
||||
});
|
||||
|
||||
@Route('/ip')
|
||||
class IpCtl {
|
||||
@Get('/whoami') whoami(@ctx() c: any) {
|
||||
return { ip: c.ip };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [IpCtl] })
|
||||
class IpModule {}
|
||||
|
||||
describe('app.fetch trustProxy gates x-forwarded-for', () => {
|
||||
it('honors x-forwarded-for (first hop) when trustProxy is true', async () => {
|
||||
const trustingApp = createApp({ modules: [IpModule], trustProxy: true });
|
||||
const res = await trustingApp.fetch(
|
||||
new Request('http://x/ip/whoami', { headers: { 'x-forwarded-for': '9.9.9.9, 1.1.1.1' } }),
|
||||
);
|
||||
expect(await res.json()).toEqual({ ip: '9.9.9.9' });
|
||||
});
|
||||
|
||||
it('ignores x-forwarded-for when trustProxy is off (default)', async () => {
|
||||
const untrustingApp = createApp({ modules: [IpModule] });
|
||||
const res = await untrustingApp.fetch(
|
||||
new Request('http://x/ip/whoami', { headers: { 'x-forwarded-for': '9.9.9.9, 1.1.1.1' } }),
|
||||
);
|
||||
expect(await res.json()).toEqual({ ip: '' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('app.fetch on a mesh app', () => {
|
||||
// Previously this asserted fetch() *threw* until listen() ran, which made mesh Node-only:
|
||||
// Deno/Bun/edge serve through app.fetch and can never call listen() (it builds an http.Server).
|
||||
// The boot gate now finalizes the mesh graph on first use, whoever triggers it.
|
||||
it('serves without ever calling listen()', async () => {
|
||||
const meshApp = createApp({ modules: [MeshModule], experimental: true, mesh: { secret: 's3cr3t' } });
|
||||
|
||||
const res = await meshApp.fetch(new Request('http://x/api/mesh/ping'));
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({ pong: true });
|
||||
await meshApp.close();
|
||||
});
|
||||
|
||||
it('does not re-boot when listen() follows a fetch', async () => {
|
||||
const meshApp = createApp({ modules: [MeshModule], experimental: true, mesh: { secret: 's3cr3t' } });
|
||||
let booted = 0;
|
||||
meshApp.bus.on('boot:provider:start', () => {
|
||||
booted += 1;
|
||||
});
|
||||
|
||||
await meshApp.fetch(new Request('http://x/api/mesh/ping'));
|
||||
const bootsAfterFetch = booted;
|
||||
const server = await meshApp.listen(0);
|
||||
|
||||
try {
|
||||
const res = await meshApp.fetch(new Request('http://x/api/mesh/ping'));
|
||||
expect(res.status).toBe(200);
|
||||
// listen() shares fetch's memoized gate: provider factories must not run twice
|
||||
expect(booted).toBe(bootsAfterFetch);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
Vendored
+19
@@ -0,0 +1,19 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDJTCCAg2gAwIBAgIUK+VdG3SgV5CP0vc6Yg0JETvNuHYwDQYJKoZIhvcNAQEL
|
||||
BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTI2MDcwNjIzNTcwOVoXDTM2MDcw
|
||||
MzIzNTcwOVowFDESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEF
|
||||
AAOCAQ8AMIIBCgKCAQEAud6rNrdOg8RgXNb1Kw/94JgUvrVm/5dmaq81/TwHeeRc
|
||||
1AIzj3rJk8KM/ZyHr8FtY0BUMrvun29hQO4F0kV7EOBu8jk/vmu+QscCjwIjpG3U
|
||||
BidYqa7dQay2R8RJVn4knr0bi6/IYYCrUZY+NTHRGbX9saX7DaLePSivmKfO4bsp
|
||||
2TpOkYWCqACeEs0XqIGvsOo7XpX5CYllr5uXz3iqP2P8/FUWXYC/NtwWXuL5Gefj
|
||||
4ltmyx7z0cFpQ9bOu6/z7VvMMHi3tM+HWHKZF29H/q8MeIThp1LWwD4GcSBV+idI
|
||||
fo3waL0utB0xHMZj2Jt9SA11NnyrDyIj7ShuO1BeOQIDAQABo28wbTAdBgNVHQ4E
|
||||
FgQU9sWqlq9NwCrJSgrOvJhNNBFzg90wHwYDVR0jBBgwFoAU9sWqlq9NwCrJSgrO
|
||||
vJhNNBFzg90wDwYDVR0TAQH/BAUwAwEB/zAaBgNVHREEEzARgglsb2NhbGhvc3SH
|
||||
BH8AAAEwDQYJKoZIhvcNAQELBQADggEBAKgkHesXrvwiucQi/0cVFvt3KH/OGfif
|
||||
gqNJvuVxnMPMMWe74ANcd5eOF9YDMjrxEfd2jMKtP0F0EXevLnI94ugQ5FRMJaIp
|
||||
laj2On0rNhxVt+nSWSP4mqj0Sp1lIRGzqz46+vnKZnydM4Q8kgzfwwQeXTMrOgMa
|
||||
ppxWNg+6gnDz1wEvO66M3eLxyaVMO8CFbzs1vahUANMi1lwa8BZiwRx5jhcIFOlh
|
||||
e4gdHPIFQcomuJX75LRry+OEnFOmHGyK1eYs8sT9D9F+TmJHVA51qvp3v7KRdxBS
|
||||
wGWh9ghqzXnyfyCkQgpxJfLJgAMR5j91IGXpSJg5D1ISXyLeqooCyw8=
|
||||
-----END CERTIFICATE-----
|
||||
Vendored
+28
@@ -0,0 +1,28 @@
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC53qs2t06DxGBc
|
||||
1vUrD/3gmBS+tWb/l2ZqrzX9PAd55FzUAjOPesmTwoz9nIevwW1jQFQyu+6fb2FA
|
||||
7gXSRXsQ4G7yOT++a75CxwKPAiOkbdQGJ1iprt1BrLZHxElWfiSevRuLr8hhgKtR
|
||||
lj41MdEZtf2xpfsNot49KK+Yp87huynZOk6RhYKoAJ4SzReoga+w6jtelfkJiWWv
|
||||
m5fPeKo/Y/z8VRZdgL823BZe4vkZ5+PiW2bLHvPRwWlD1s67r/PtW8wweLe0z4dY
|
||||
cpkXb0f+rwx4hOGnUtbAPgZxIFX6J0h+jfBovS60HTEcxmPYm31IDXU2fKsPIiPt
|
||||
KG47UF45AgMBAAECggEAASvLkTLFTPQRNbHesGivd+QKvhXcrNpqboclPwUgY0P3
|
||||
/Wz4dVxicJV5TRrDScKdUBKxGnMP1+jRfcwndLxJKswjNCWosWgyi29UueEbUjdP
|
||||
7pb+X8P73bn7GbIn/SJv1CE1uc2qefTKf4nZC/2WR0Qb3FaYTEJyWy51BsWd5Sha
|
||||
4XfUzHBldJdZcELCBtwQFJWnqpc1qlnn4Uj9nmD+n7q5t54jqaa67qDhqDScU4DH
|
||||
nguXuH+Cb1zWGsKfoOc//jGWZKX3FJ6nKLHhh4QxxJa/A0VIoqf2lHDfKiJNUqMl
|
||||
BLq78MiFD1SnPXp/024EtEpC5KAS9oSHRusEmDbgAQKBgQDy6j5h9fgI5Bnxjv+E
|
||||
+ASagBSYN4+mszHvZVXtXAl8OZVXkHUKoaco5IPe4/Ysg7WTPVAQAggtbqq/QE15
|
||||
S1sQZyPBmr2ewqQHKNJHMsB0u9AlXOHK3DHVq3+6kM7RGeuuWDvycsM2KHV9pUtA
|
||||
rIg1aMc9NGMkCsaQT2lJeyTOOQKBgQDD4cgK0a4XCot3fW4FaofDUE69TDJwk0Me
|
||||
IneH0BpK3iuSqS/mqjH8ZV6Z5lNVopUGGObnwLtEHZX8q2jakBPa7mCYnulnAsO9
|
||||
WTEZ5oHoN3Gr8O7WJW4LoOOIeci8qPiz58CazhBjK+Qa6/C+rRN0u5hbG3zTEAoS
|
||||
vsjMDYgQAQKBgC8P1OAzwEcwshoLo1OGnZW1RMgs04bvZrhDwL8Iusm3ekiJszNJ
|
||||
GFKi2y2eqr37En2hPlarnhv3OdttwNTEFbN62AGVUjFk8lR0wzCKE6FKFcx3T0N3
|
||||
H6yO2mMx1O/L/s47R/nz5AAlHIYoNQklpAn878Ta1m5QLCIfUH2s/vd5AoGBAL01
|
||||
9i6FNj2pgOiOL11p9vQyOaze0oYtqZKNRprY6NzS2JIVfWC5nAkqvgO5GVxJ7Ntz
|
||||
6G+KmxmD3qKvzFv6+kLrKkGiluBbKkpXwnc7UtbF37Zvx7TxeOggpEjrIn0iVwIo
|
||||
5cJjNC8ncXKT3/u/YWDL6LJwzdVu09whkAKTO5ABAoGBANGHFvW/LCn0R24Xk2lF
|
||||
tFXsj2M5TqjqEeAa37doHPsUx2Bvp/YTpkA6sRKzlHcfyEC/gUKjNaEjIil5836P
|
||||
qjd7abz8xF7STS+9SzGDBEbjKk/IRrBjcYEh9x6kGWqnN6w4wXHsoZyMi/zSP/OG
|
||||
KPTzBQvDzHuVu5n+/a7izTeb
|
||||
-----END PRIVATE KEY-----
|
||||
Loaded 100 of 170 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user