Compare commits
165
Commits
b0b0b1388d
...
e068426582
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e068426582 | ||
|
|
8bd2a3f61c | ||
|
|
96d863d402 | ||
|
|
33df70730b | ||
|
|
5fc37a2df7 | ||
|
|
2a84331022 | ||
|
|
91fe8f8aff | ||
|
|
3a4cd5a7ce | ||
|
|
642ef109b2 | ||
|
|
4081106813 | ||
|
|
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 | ||
|
|
e38d972566 | ||
|
|
c39eb667ac | ||
|
|
0c29c76a8a | ||
|
|
8335ff2875 | ||
|
|
3842271c4d | ||
|
|
9050a7e5d9 | ||
|
|
6171e5e6bd | ||
|
|
2bbc43505e | ||
|
|
07b6b57611 | ||
|
|
9d8088d0a9 | ||
|
|
cc0044ba6a | ||
|
|
73cd874cae | ||
|
|
f5136e35d0 | ||
|
|
d67a4080dd | ||
|
|
8f3aef9edc | ||
|
|
a25c9752a2 | ||
|
|
9a5f54a4b3 | ||
|
|
df01bbfc41 | ||
|
|
68caca2cc1 | ||
|
|
ddca3fd74b | ||
|
|
a327352ba0 | ||
|
|
86cb473012 | ||
|
|
774d807e96 | ||
|
|
8b43a15609 | ||
|
|
e8c1ed9bc8 | ||
|
|
44e77d4bb4 | ||
|
|
e702de187d | ||
|
|
e8a63e8d41 | ||
|
|
a1e8f73e64 | ||
|
|
f151da4bd7 | ||
|
|
1174d14754 | ||
|
|
c4f220f431 | ||
|
|
9f963792f0 | ||
|
|
ec1214e9e5 | ||
|
|
31f91ee61f | ||
|
|
a4fb19210e | ||
|
|
e365cee3bf | ||
|
|
b58db71405 | ||
|
|
04688ab621 | ||
|
|
abc4603050 | ||
|
|
8aac7f24bd | ||
|
|
0eaefd0053 | ||
|
|
fdbba5f06d | ||
|
|
732e1eb636 | ||
|
|
a94a987a35 | ||
|
|
a3dad32384 | ||
|
|
f96d349c74 | ||
|
|
35c60c44c3 |
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
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
name: CI
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [develop, main]
|
||||||
|
pull_request:
|
||||||
|
branches: [develop, main]
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: '18'
|
||||||
|
- run: npm ci
|
||||||
|
- 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
|
||||||
@@ -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,26 @@
|
|||||||
|
name: Release → npmjs
|
||||||
|
|
||||||
|
# Production publish. Runs on GITHUB ONLY, on a version tag (`v*`). Publishes the stable
|
||||||
|
# package (version from package.json) to the public npmjs registry under `latest`.
|
||||||
|
# The tag arrives via the promote workflow; the version should be stable (no prerelease)
|
||||||
|
# before tagging.
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags: ['v*']
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
publish-prod:
|
||||||
|
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'
|
||||||
|
registry-url: 'https://registry.npmjs.org'
|
||||||
|
- run: npm ci
|
||||||
|
# `npm publish` runs prepublishOnly (lint + complexity + typecheck + test + build) first.
|
||||||
|
- name: Publish to npmjs
|
||||||
|
env:
|
||||||
|
NODE_AUTH_TOKEN: ${{ secrets.NPM_AUTH }}
|
||||||
|
run: npm publish --access public
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
name: Stage → Verdaccio
|
||||||
|
|
||||||
|
# Staging publish. Runs on GITEA ONLY (the `if` guards against GitHub), on every merge
|
||||||
|
# to main. Publishes the package as-is — version comes from package.json (a prerelease
|
||||||
|
# like 26.7.1-stg.N) — to the internal Verdaccio under the `stg` dist-tag. Verdaccio
|
||||||
|
# allows overwrite, so re-publishing the same version is a no-op-ish refresh.
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
|
||||||
|
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
|
||||||
|
# `npm publish` runs prepublishOnly (lint + complexity + typecheck + test + build)
|
||||||
|
# as its own gate before anything leaves the machine.
|
||||||
|
- name: Publish to Verdaccio
|
||||||
|
env:
|
||||||
|
NODE_AUTH_TOKEN: ${{ secrets.NPM_AUTH }}
|
||||||
|
run: |
|
||||||
|
npm config set //npm.svc.zoit.services/:_authToken "$NODE_AUTH_TOKEN"
|
||||||
|
npm publish --registry https://npm.svc.zoit.services --tag stg
|
||||||
@@ -10,3 +10,10 @@ coverage/
|
|||||||
# Env
|
# Env
|
||||||
.env
|
.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.
|
||||||
+133
@@ -0,0 +1,133 @@
|
|||||||
|
# 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.MM.PATCH`.
|
||||||
|
|
||||||
|
## [Unreleased]
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **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 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 the route 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
|
||||||
|
- 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`/`@Post`/`@Put`/`@Patch`/`@Delete`) 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://git.svc.zoit.services/Green-Tea/core/compare/26.7.0-beta.0...develop
|
||||||
|
[26.7.0-beta.0]: https://git.svc.zoit.services/Green-Tea/core/releases/tag/26.7.0-beta.0
|
||||||
@@ -1,18 +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`.
|
<p align="center"><b>A zen, opinionated, type-safe framework.</b></p>
|
||||||
|
|
||||||
## Why
|
<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>
|
||||||
|
|
||||||
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:
|
`@green-tea/core` — **beta**, RC-track. One runtime dependency: `reflect-metadata`. Two optional peers you install only if you use them: `ws` (WebSocket / mesh) and `busboy` (multipart uploads).
|
||||||
|
|
||||||
- **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".
|
```bash
|
||||||
- **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`.
|
npm install @green-tea/core reflect-metadata
|
||||||
- **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.
|
# optional, only if you use them:
|
||||||
- **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.
|
npm install ws # WebSocket routes (@Ws) and mesh
|
||||||
- **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.
|
npm install busboy # multipart/form-data file uploads
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## The idea
|
||||||
|
|
||||||
|
Most frameworks make you keep the whole request in your head: which middleware ran, whether `req.user` exists by now, what order things fire in, which plugin quietly deleted your body parser. That mental bookkeeping is where bugs live.
|
||||||
|
|
||||||
|
green-tea puts the request on the page instead. You declare what each step **needs** and **produces**; the framework computes the order, type-checks the wiring, and can print the whole thing. A route runs only the steps its handler actually depends on. Boot fails loudly when a dependency is missing, so you never serve `undefined`.
|
||||||
|
|
||||||
|
Less to hold in your head. That's the tea.
|
||||||
|
|
||||||
|
## 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.** Return an `AsyncIterable` and the transport streams it — SSE, ndjson, or a WebSocket duplex — with backpressure and cleanup handled. *Why it matters:* no separate gateway, adapter, or library to bolt on.
|
||||||
|
- **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 |
|
||||||
|
| *(plain return)* | server → client | SSE or ndjson by `Accept` | programmatic streaming over `fetch` |
|
||||||
|
|
||||||
|
The primitive never changes — it's always an `AsyncIterable`. What changes is **direction and framing**, and you declare which. That's the difference between each iterable green-tea hands you:
|
||||||
|
|
||||||
|
- **`@Sse` / plain return** — you return **one** iterable: the *outbound* stream. Each `yield` becomes an SSE event, or an ndjson line.
|
||||||
|
- **`@Ws` (duplex)** — **two** iterables. `@inbound()` gives you the client's *incoming* messages to consume; the one you **return** is the *outbound* stream to the client. `@abort()` hands you an `AbortSignal` for teardown.
|
||||||
|
- **`@Stream`** — you write the handler once; the client's request decides whether it arrives as SSE, ndjson, or a WebSocket. No branching in your code.
|
||||||
|
|
||||||
|
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.
|
||||||
|
- **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 shows up as the app grows: more dependencies, real-time, and more than one machine.
|
||||||
|
|
||||||
|
| | Express | Fastify | NestJS | expressive-tea | **green-tea** |
|
||||||
|
|---|---|---|---|---|---|
|
||||||
|
| **Pipeline model** | positional `app.use()` | hooks + encapsulated plugins | DI + interceptors/guards | decorators on Express + boot stages | **explicit dependency graph (topo-sorted)** |
|
||||||
|
| **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 |
|
||||||
|
| **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`, `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 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
|
## Quick look
|
||||||
|
|
||||||
@@ -52,7 +164,7 @@ class UserController {
|
|||||||
class ApiModule {}
|
class ApiModule {}
|
||||||
|
|
||||||
const app = createApp({ modules: [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);
|
app.listen(3000);
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -69,32 +181,76 @@ The handler signature declares exactly what it wants — in any order, nothing m
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `@needs('user')` | a graph-produced value (boot-validated) | `('key')` |
|
| `@needs('user')` | a graph-produced value (boot-validated) | `('key')` |
|
||||||
| `@ctx()` | the whole accumulated context | `()` |
|
| `@ctx()` | the whole accumulated context | `()` |
|
||||||
| `@param(...)` | route params | `()` · `('id')` · `(['a','b'])` |
|
| `@param(...)` | route params | `()` · `('id')` · `('id', schema)` |
|
||||||
| `@query(...)` | parsed query string | `()` · `('q')` · `(['a','b'])` |
|
| `@query(...)` | parsed query string | `()` · `('q')` · `(['a','b'])` · `(schema)` |
|
||||||
| `@body(...)` | parsed JSON body | `()` · `('field')` · `(['a','b'])` |
|
| `@body(...)` | parsed body (JSON / urlencoded / multipart) | `()` · `('field')` · `(schema)` |
|
||||||
| `@headers(...)` | request headers | `()` · `('authorization')` · `(['a','b'])` |
|
| `@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. On `listen()` the app prints a one-line summary of what's running degraded, and the list is queryable via `app.degraded()`. Routes that actually need a degraded provider fail at request time, not at boot. This is deliberate (graceful degradation); wire an alert off `app.degraded()` or the `boot:provider:fail` bus event in production so a degraded start is never silent.
|
||||||
|
|
||||||
|
## Routing
|
||||||
|
|
||||||
|
Patterns match by segment: static, `:param` (one segment), and a trailing `:name*` **catch-all** that captures the rest of the path — slashes included — into `params.name`. When more than one route matches, the **most specific wins** (static ▸ `:param` ▸ catch-all), independent of registration order. A path that exists under a *different* method returns **`405` with an `Allow` header**, not `404`.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
@Get('/files/:path*') // /files/img/2026/logo.png → params.path = "img/2026/logo.png"
|
||||||
|
```
|
||||||
|
|
||||||
|
**Not yet** (post-beta, on the roadmap): regex / typed param constraints like `:id(\d+)`, and route matching is a linear scan — fine for typical route tables, but a radix-tree matcher for very large ones isn't built.
|
||||||
|
|
||||||
## Two layers
|
## 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.
|
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.
|
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.
|
||||||
|
|
||||||
|
**Node only.** Runs on Node ≥ 18. Deno / Bun / edge runtimes (over web-standard `Request`/`Response`) are on the roadmap, not built — only `src/http/` is runtime-specific today.
|
||||||
|
|
||||||
|
**mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet.
|
||||||
|
|
||||||
|
## Docs & development
|
||||||
|
|
||||||
|
- **[Quickstart](./docs/quickstart.md)** — install + concrete examples (routes/DI, `flow`, validation, uploads, SSE, WebSocket, mesh, plugins).
|
||||||
|
- **[Architecture](./docs/architecture.md)** — the mental map (layers, request lifecycle, mesh) as diagrams.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm install
|
npm install
|
||||||
npm test # vitest
|
npm test # vitest
|
||||||
npm run typecheck # tsc --noEmit (includes the compile-time-guarantee type test)
|
npm run typecheck # tsc --noEmit (includes the compile-time-guarantee type test)
|
||||||
npm run build # emit dist/
|
npm run build # emit dist/
|
||||||
|
npm run bench # regenerate BENCHMARKS.md
|
||||||
```
|
```
|
||||||
|
|
||||||
## Roadmap
|
## Roadmap
|
||||||
|
|
||||||
- **streams** — native WebSocket/SSE + reactive streams (steps that open an observed channel).
|
- ✅ **transport security** — native TLS/wss, CORS, secure-by-default headers, `trustProxy`.
|
||||||
- **mesh** — `teapot`/`teacup`: distributed scopes over a persistent channel with auto-registration. Model: a BEAM/OTP-style cluster, *not* microservices. The core's `resolve()` is already async + transport-agnostic to allow this without a rewrite.
|
- ✅ **request I/O** — JSON / urlencoded / multipart uploads, size limits, graceful shutdown, Standard Schema validation.
|
||||||
- official plugins (cors, body parsers, auth) — structurally unable to sabotage the global pipeline.
|
- ✅ **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.
|
||||||
|
- **next** — API freeze + first published release, mesh sub-specs (discovery, load-balancing, failover), runtime adapters (Deno / Bun / edge over web-standard `Request`/`Response`), official plugins.
|
||||||
|
|
||||||
|
## Versioning
|
||||||
|
|
||||||
|
green-tea uses **calendar versioning**: `YY.M.PATCH` (e.g. `26.7.0` = the first release cut in July 2026, patch 0). The month is **not** zero-padded — npm treats versions as semver, which forbids leading zeros. A version tells you *when* it shipped, not how many breaking changes preceded it — those are always called out in the [CHANGELOG](./CHANGELOG.md).
|
||||||
|
|
||||||
|
**While in beta**, releases carry a `-beta.N` pre-release suffix on the calendar version (e.g. `26.7.0-beta.0`) and publish under the npm `beta` dist-tag — so a plain `npm install @green-tea/core` won't pick one up until the first stable calendar release. The API can still change between betas.
|
||||||
|
|
||||||
## License
|
## 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,51 @@
|
|||||||
|
{
|
||||||
|
"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.4",
|
||||||
|
"npm:@nestjs/common@^11.1.27",
|
||||||
|
"npm:@nestjs/core@^11.1.27",
|
||||||
|
"npm:@nestjs/platform-express@^11.1.27",
|
||||||
|
"npm:@nestjs/platform-fastify@^11.1.27",
|
||||||
|
"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:eslint@^9.39.4",
|
||||||
|
"npm:express@^5.2.1",
|
||||||
|
"npm:fastify@^5.10.0",
|
||||||
|
"npm:graphql@^16.9.0",
|
||||||
|
"npm:prettier@^3.9.4",
|
||||||
|
"npm:reflect-metadata@0.2.2",
|
||||||
|
"npm:rxjs@^7.8.2",
|
||||||
|
"npm:tsup@^8.5.1",
|
||||||
|
"npm:tsx@^4.23.0",
|
||||||
|
"npm:typescript-eslint@^8.63.0",
|
||||||
|
"npm:typescript@^5.5.0",
|
||||||
|
"npm:vitest@2",
|
||||||
|
"npm:ws@^8.21.0"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
# 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,522 @@
|
|||||||
|
# green-tea — Quickstart
|
||||||
|
|
||||||
|
A type-safe HTTP framework where the request/boot pipeline is an explicit **dependency
|
||||||
|
graph**. You declare what you need; the framework computes the order, validates it at boot,
|
||||||
|
and can extend the graph over time (streams) and across machines (mesh).
|
||||||
|
|
||||||
|
See [architecture.md](./architecture.md) for the mental map.
|
||||||
|
|
||||||
|
## Install
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install @green-tea/core reflect-metadata
|
||||||
|
# ws is an OPTIONAL peer dependency — only needed for WebSocket / mesh on Node:
|
||||||
|
npm install ws # optional
|
||||||
|
```
|
||||||
|
|
||||||
|
`tsconfig.json` must enable decorator metadata:
|
||||||
|
|
||||||
|
```jsonc
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"experimentalDecorators": true,
|
||||||
|
"emitDecoratorMetadata": true,
|
||||||
|
"target": "es2017",
|
||||||
|
"module": "commonjs"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Import `reflect-metadata` once at your entrypoint.
|
||||||
|
|
||||||
|
## 1. A route with dependency injection
|
||||||
|
|
||||||
|
A **provider** is an app-scope singleton. A **step** runs per request and transforms the
|
||||||
|
context. A handler's **argument decorators are its dependency declaration** — ask for what
|
||||||
|
you want, in any order. If you `@needs` a token nothing produces, you get a **boot error**,
|
||||||
|
not an `undefined` at runtime.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import 'reflect-metadata';
|
||||||
|
import { createApp, Provider, Step, Route, Get, Module, Unauthorized, needs, param } from '@green-tea/core';
|
||||||
|
|
||||||
|
@Provider({ provides: 'db' })
|
||||||
|
class Database {
|
||||||
|
provide() { return { db: { find: (id: string) => ({ id, name: 'Diego' }) } }; }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Step({ provides: 'user', needs: ['db', 'req'] })
|
||||||
|
class Authenticate {
|
||||||
|
run(ctx: any) {
|
||||||
|
const user = ctx.db.find(ctx.req.headers['x-token']);
|
||||||
|
if (!user) throw new Unauthorized('bad token'); // throw = short-circuit the pipeline
|
||||||
|
return { user }; // return = continue, merge into ctx
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Route('/users')
|
||||||
|
class UserController {
|
||||||
|
@Get('/:id')
|
||||||
|
getUser(@needs('user') user: any, @param('id') id: string) {
|
||||||
|
return { requested: id, you: user }; // auto-serialized as JSON
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Module({ mountpoint: '/api', providers: [Database], steps: [Authenticate], controllers: [UserController] })
|
||||||
|
class ApiModule {}
|
||||||
|
|
||||||
|
const app = createApp({ modules: [ApiModule] });
|
||||||
|
await app.listen(3000);
|
||||||
|
// GET /api/users/9 (header x-token) → { "requested": "9", "you": { "id": "...", "name": "Diego" } }
|
||||||
|
|
||||||
|
await app.close(); // graceful shutdown: drains in-flight requests, closes streams + mesh links
|
||||||
|
```
|
||||||
|
|
||||||
|
> **Per-route execution (important).** Each route runs **only the providers/steps in the transitive
|
||||||
|
> closure of its handler's `@needs`** — nothing else. A route that doesn't `@needs('user')` does **not**
|
||||||
|
> run the `Authenticate` step. This means a cross-cutting *enforcement* step (e.g. auth that throws 401)
|
||||||
|
> only protects routes that actually `@needs` its token. To run something on **every** route regardless
|
||||||
|
> of needs (logging, audit, a global guard), add it as a **plugin step** via `scope.add({ ..., provides: [] })` —
|
||||||
|
> steps that produce nothing run unconditionally. Don't rely on a token-providing step to guard routes
|
||||||
|
> that don't declare it.
|
||||||
|
|
||||||
|
### Argument decorators
|
||||||
|
|
||||||
|
| Decorator | Reads from | Adds a graph dependency? |
|
||||||
|
|---|---|---|
|
||||||
|
| `@needs('user')` | a value produced by a provider/step | **yes** (boot-validated) |
|
||||||
|
| `@ctx()` | the whole accumulated context | no |
|
||||||
|
| `@param('id')` | route params | no |
|
||||||
|
| `@query('q')` | parsed query string | no |
|
||||||
|
| `@body()` | parsed JSON body | no |
|
||||||
|
| `@headers('x')` | request headers | no |
|
||||||
|
| `@inbound()` | the incoming WS message channel | no (WS only) |
|
||||||
|
| `@abort()` | an `AbortSignal` that fires on disconnect | no (stream/WS) |
|
||||||
|
|
||||||
|
Each envelope decorator has three forms: `@query()` (whole object), `@query('q')` (one key),
|
||||||
|
`@query(['q','date'])` (subset).
|
||||||
|
|
||||||
|
## 2. Compile-time guarantee with `flow`
|
||||||
|
|
||||||
|
The decorator layer validates the graph at boot. The functional core `flow` validates it in
|
||||||
|
the **type checker**:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { flow } from '@green-tea/core';
|
||||||
|
|
||||||
|
const pipeline = flow()
|
||||||
|
.step('db', () => ({ find: (id: string) => id }))
|
||||||
|
.step('user', (ctx) => ctx.db.find('u1')); // referencing a missing 'db' would not compile
|
||||||
|
```
|
||||||
|
|
||||||
|
## 3. Streaming — SSE
|
||||||
|
|
||||||
|
Return an `AsyncIterable` and the pipeline streams it (the transformer is bypassed; the
|
||||||
|
transport frames it, handles backpressure, and cleans up on disconnect).
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Route, Sse } from '@green-tea/core';
|
||||||
|
|
||||||
|
@Route('/feed')
|
||||||
|
class FeedController {
|
||||||
|
@Sse('/ticks')
|
||||||
|
ticks() {
|
||||||
|
return (async function* () {
|
||||||
|
for (let n = 1; n <= 3; n++) yield { tick: n };
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// GET /feed/ticks (Accept: text/event-stream)
|
||||||
|
// data: {"tick":1}
|
||||||
|
// data: {"tick":2}
|
||||||
|
// data: {"tick":3}
|
||||||
|
```
|
||||||
|
|
||||||
|
`@Stream(path)` negotiates the transport by header (`Accept: text/event-stream` → SSE,
|
||||||
|
`Upgrade: websocket` → WS, else ndjson chunked).
|
||||||
|
|
||||||
|
## 4. Streaming — WebSocket duplex
|
||||||
|
|
||||||
|
A WS handler receives the **inbound** channel and returns the **outbound** channel — a step
|
||||||
|
that consumes one channel and produces another.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Route, Ws, inbound, channel } from '@green-tea/core';
|
||||||
|
|
||||||
|
@Route('/chat')
|
||||||
|
class ChatController {
|
||||||
|
@Ws('/echo')
|
||||||
|
echo(@inbound() incoming: AsyncIterable<string>) {
|
||||||
|
const out = channel<string>();
|
||||||
|
(async () => {
|
||||||
|
for await (const msg of incoming) out.push(`echo: ${msg}`);
|
||||||
|
out.close();
|
||||||
|
})();
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`channel<T>()` is a multicast `AsyncIterable` with `push` / `close` / `fail` and an optional
|
||||||
|
bounded buffer (`channel({ buffer: 100 })`, drop-oldest).
|
||||||
|
|
||||||
|
## 5. Mesh — distributed dependency injection
|
||||||
|
|
||||||
|
A **teacup** can depend on a token that physically lives on a **teapot**. Exports are
|
||||||
|
opt-in (`export: true`) and the control channel is gated by a shared secret.
|
||||||
|
|
||||||
|
> ⚠️ **mesh is alpha** — its API and wire protocol may change. It's gated behind `experimental: true`;
|
||||||
|
> `createApp` throws if you pass `mesh` without it. Don't ship it to production yet.
|
||||||
|
|
||||||
|
**Node A — teapot (exposes `config`, `auth`, and a route):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
@Provider({ provides: 'config', export: true })
|
||||||
|
class Config { provide() { return { config: { region: 'mx', tier: 'pro' } }; } }
|
||||||
|
|
||||||
|
@Step({ provides: 'auth', needs: [], export: true })
|
||||||
|
class Auth { run(ctx: any) { return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; } }
|
||||||
|
|
||||||
|
@Route('/svc')
|
||||||
|
class Svc { @Get('/ping', { export: true }) ping() { return { pong: true }; } }
|
||||||
|
|
||||||
|
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth], controllers: [Svc] })
|
||||||
|
class TeapotModule {}
|
||||||
|
|
||||||
|
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'shh' } });
|
||||||
|
await teapot.listen(3002);
|
||||||
|
```
|
||||||
|
|
||||||
|
**Node B — teacup (uses `config` + `auth` with no local providers):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
@Route('/local')
|
||||||
|
class LocalCtl {
|
||||||
|
@Get('/who')
|
||||||
|
who(@needs('config') config: any, @needs('auth') auth: any) {
|
||||||
|
return { config, auth }; // both resolved by RPC to the teapot
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
|
||||||
|
class TeacupModule {}
|
||||||
|
|
||||||
|
const teacup = createApp({
|
||||||
|
modules: [TeacupModule],
|
||||||
|
experimental: true,
|
||||||
|
mesh: { teapots: [{ url: 'ws://A-host:3002/__mesh__/control', secret: 'shh' }] },
|
||||||
|
});
|
||||||
|
await teacup.listen(3003);
|
||||||
|
// GET B:3003/api/local/who (x-token: abc)
|
||||||
|
// → { "config": { "region": "mx", "tier": "pro" }, "auth": { "token": "abc" } }
|
||||||
|
```
|
||||||
|
|
||||||
|
`@needs('config' | 'auth')` validates at boot because the teapot announced them in its
|
||||||
|
manifest on connect. A provider export is app-scope (resolved once, cached); a step export is
|
||||||
|
request-scope (RPC per request, carrying the request envelope).
|
||||||
|
|
||||||
|
> Skeleton limitations (by design): no discovery, load-balancing, or failover yet; app-scope
|
||||||
|
> remote values are not reconciled on reconnect; the request envelope omits `req.url`.
|
||||||
|
|
||||||
|
## 6. Plugins & observability
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const logger = (api: any) => {
|
||||||
|
api.bus.on('request:step:enter', (p: any) => console.log(`→ ${p.name}`));
|
||||||
|
api.bus.on('stream:open', (p: any) => console.log(`stream open ${p.name}`));
|
||||||
|
api.bus.on('mesh:rpc:error', (p: any) => console.error('mesh rpc failed', p.error));
|
||||||
|
};
|
||||||
|
|
||||||
|
const app = createApp({ modules: [ApiModule], plugins: [logger] });
|
||||||
|
```
|
||||||
|
|
||||||
|
Lifecycle events: `boot:provider:*`, `request:step:*`, `stream:open|close|error`,
|
||||||
|
`mesh:connect|disconnect|rpc:error`, `plugin:mounted`.
|
||||||
|
|
||||||
|
## 7. Transport security
|
||||||
|
|
||||||
|
Four `createApp` options cover TLS, proxying, CORS, and response headers.
|
||||||
|
|
||||||
|
### TLS (native https/wss)
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { readFileSync } from 'fs';
|
||||||
|
|
||||||
|
const app = createApp({
|
||||||
|
modules: [App],
|
||||||
|
tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') },
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
When `tls` is set the server serves https, and WebSocket upgrades become wss on the same
|
||||||
|
port — no other changes.
|
||||||
|
|
||||||
|
### `trustProxy`
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const app = createApp({ modules: [App], trustProxy: true });
|
||||||
|
```
|
||||||
|
|
||||||
|
Behind a reverse proxy, reads `X-Forwarded-Proto` / `X-Forwarded-For` to populate
|
||||||
|
`ctx.protocol` (`'http' | 'https'`) and `ctx.ip` (read via `@ctx()`). Off by default —
|
||||||
|
forwarded headers are ignored (and spoofable) until you opt in. It trusts the immediate hop
|
||||||
|
unconditionally; there's no CIDR allowlist yet.
|
||||||
|
|
||||||
|
### CORS
|
||||||
|
|
||||||
|
Off unless `origins` is set.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const app = createApp({
|
||||||
|
modules: [App],
|
||||||
|
cors: { origins: 'https://app.example.com', credentials: true },
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
`origins` accepts `string | string[] | '*' | (origin) => boolean`. A preflight `OPTIONS`
|
||||||
|
request (with `Access-Control-Request-Method`) is auto-answered with 204.
|
||||||
|
|
||||||
|
- With `credentials: true`, the server never sends `Access-Control-Allow-Origin: *` — it
|
||||||
|
echoes the concrete allowed origin (or blocks the request).
|
||||||
|
- **Security warning:** `origins: '*'` together with `credentials: true` reflects *any*
|
||||||
|
origin with credentials attached — the classic reflect-any foot-gun. Only combine them if
|
||||||
|
you truly intend an open credentialed API; prefer an explicit allowlist.
|
||||||
|
|
||||||
|
### `security` (headers, ON by default)
|
||||||
|
|
||||||
|
Applied to every HTTP response. Disable everything with `security: false`, or override
|
||||||
|
individual headers with an options object.
|
||||||
|
|
||||||
|
| Header | Default |
|
||||||
|
|---|---|
|
||||||
|
| `X-Content-Type-Options` | `nosniff` |
|
||||||
|
| `X-Frame-Options` | `SAMEORIGIN` |
|
||||||
|
| `Referrer-Policy` | `no-referrer` |
|
||||||
|
| `X-DNS-Prefetch-Control` | `off` |
|
||||||
|
| `Strict-Transport-Security` | `max-age=15552000` (180d) — **only when the connection is secure** (native TLS, or `trustProxy` + `X-Forwarded-Proto: https`); no `includeSubDomains`/`preload` |
|
||||||
|
| `Content-Security-Policy` | not set — pass `security: { csp: "..." }` |
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const app = createApp({ modules: [App], security: { csp: "default-src 'self'" } });
|
||||||
|
```
|
||||||
|
|
||||||
|
**Scope caveat:** `security` and `cors` headers apply to HTTP responses; they do not apply
|
||||||
|
to the WebSocket handshake (101/upgrade) response.
|
||||||
|
|
||||||
|
### Defaults
|
||||||
|
|
||||||
|
| Option | Default |
|
||||||
|
|---|---|
|
||||||
|
| `tls` | off (plain http/ws) |
|
||||||
|
| `trustProxy` | off |
|
||||||
|
| `cors` | off (same-origin only) |
|
||||||
|
| `security` | ON (HSTS only when the connection is secure) |
|
||||||
|
|
||||||
|
## 8. File uploads / multipart
|
||||||
|
|
||||||
|
> Multipart parsing uses the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency — install it with `npm i busboy`. A `multipart/form-data` request to a server without busboy installed returns `501`. (JSON and urlencoded need nothing extra.)
|
||||||
|
|
||||||
|
A request with `Content-Type: multipart/form-data` makes `@body()` resolve to `{ fields, files }`
|
||||||
|
instead of a plain object:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Route, Post, body } from '@green-tea/core';
|
||||||
|
import type { MultipartBody } from '@green-tea/core';
|
||||||
|
|
||||||
|
@Route('/profile')
|
||||||
|
class ProfileController {
|
||||||
|
@Post('/avatar')
|
||||||
|
upload(@body() form: MultipartBody) {
|
||||||
|
const name = form.fields.name; // string | string[]
|
||||||
|
const avatar = form.files.avatar; // UploadedFile | UploadedFile[]
|
||||||
|
return { name, size: Array.isArray(avatar) ? undefined : avatar?.size };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`UploadedFile` is `{ filename, contentType, data: Buffer, size }` — the whole file is buffered
|
||||||
|
in memory, no temp files.
|
||||||
|
|
||||||
|
> **Access note (asymmetry).** For multipart, `@body('title')` returns `undefined` — the value
|
||||||
|
> lives at `body.fields.title`, not `body.title`, unlike JSON/urlencoded where `@body('title')`
|
||||||
|
> picks the value directly. Use `@body()` and read `.fields`/`.files`, or key into the envelope
|
||||||
|
> itself with `@body('fields')` / `@body('files')`.
|
||||||
|
|
||||||
|
### Repeated fields — `bodyDuplicates`
|
||||||
|
|
||||||
|
By default, a repeated field name keeps the **last** value (`'last'`, matching urlencoded).
|
||||||
|
Set `bodyDuplicates: 'array'` on `createApp` to accumulate repeats into a `string[]` instead —
|
||||||
|
this applies to **both** urlencoded and multipart text fields:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const app = createApp({ modules: [ApiModule], bodyDuplicates: 'array' });
|
||||||
|
```
|
||||||
|
|
||||||
|
Files under a repeated field name always become an array (`UploadedFile[]`), regardless of
|
||||||
|
`bodyDuplicates`.
|
||||||
|
|
||||||
|
### Per-endpoint override
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
@Post('/upload', { duplicates: 'array' })
|
||||||
|
upload(@body() form: MultipartBody) { /* ... */ }
|
||||||
|
```
|
||||||
|
|
||||||
|
Precedence: route `duplicates` → app `bodyDuplicates` → `'last'`.
|
||||||
|
|
||||||
|
### Limits
|
||||||
|
|
||||||
|
Uploaded files are held in memory, so they're bounded by the same `maxBodyBytes` limit as any
|
||||||
|
other request body (over the limit → 413). `maxParts` (default `1000`) caps the number of
|
||||||
|
multipart parts per request:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const app = createApp({ modules: [ApiModule], limits: { maxParts: 500 } });
|
||||||
|
```
|
||||||
|
|
||||||
|
A malformed multipart body (bad boundary, missing headers, truncated part) → 400.
|
||||||
|
|
||||||
|
## 9. Validation
|
||||||
|
|
||||||
|
`@body`, `@query`, `@headers`, and `@param` accept an optional **Standard Schema**
|
||||||
|
(the [`~standard` interface](https://standardschema.dev) shared by zod, valibot, arktype,
|
||||||
|
and others). green-tea's core has **zero runtime dependency** on any of them — bring
|
||||||
|
whichever validator you already use:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { Route, Post, body } from '@green-tea/core';
|
||||||
|
|
||||||
|
const CreateUser = z.object({ email: z.string().email() });
|
||||||
|
|
||||||
|
@Route('/users')
|
||||||
|
class UserController {
|
||||||
|
@Post('/')
|
||||||
|
create(@body(CreateUser) user: { email: string }) {
|
||||||
|
return { created: user.email };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The value the handler receives is the schema's **parsed/coerced output**, not the raw
|
||||||
|
input — `ctx.body` (via `@ctx()` or a `@needs`-fed step) stays exactly what the transport
|
||||||
|
parsed. Query strings are always strings on the wire, so a schema is often the coercion
|
||||||
|
point:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const ListQuery = z.object({ page: z.coerce.number() });
|
||||||
|
|
||||||
|
@Get('/list')
|
||||||
|
list(@query(ListQuery) q: { page: number }) {
|
||||||
|
return { page: q.page, isNum: typeof q.page === 'number' }; // GET /list?page=2 → true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
> **Access shape (asymmetry).** `@param('id', Schema)` takes the key in slot 1 and the schema
|
||||||
|
> in slot 2 — `@param` always needs a name to say which route param it binds. `@body(Schema)`,
|
||||||
|
> `@query(Schema)`, and `@headers(Schema)` take the schema as their only argument, validating
|
||||||
|
> the whole parsed object (all of `body`/`query`/`headers`).
|
||||||
|
|
||||||
|
A failing schema short-circuits the request with **422**:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "error": "Validation failed", "source": "body", "issues": [{ "path": "email", "message": "Invalid email" }] }
|
||||||
|
```
|
||||||
|
|
||||||
|
`source` is which envelope failed (`'body' | 'query' | 'params' | 'headers'`); `issues` is
|
||||||
|
the schema's issues flattened to `{ path, message }` (`path` is dot-joined).
|
||||||
|
|
||||||
|
**Caveats:**
|
||||||
|
- **Fail-fast.** Arguments validate in order; the **first** failing one throws — later args in
|
||||||
|
the same handler are not checked in that request.
|
||||||
|
- **Steps see raw input.** Only the resolved handler argument is coerced/validated; a `@Step`
|
||||||
|
reading the same data via `ctx.body`/`ctx.query`/etc. always sees the untouched value.
|
||||||
|
- **A throwing schema is a 500, not a 422.** The Standard Schema contract says `validate()`
|
||||||
|
returns `{ issues }` on failure — it isn't supposed to throw. If it does anyway, that
|
||||||
|
propagates as an uncaught error (→ 500), since it signals a bug in the schema, not user input.
|
||||||
|
- **Async schemas are awaited** — `validate()` returning a `Promise` works transparently.
|
||||||
|
|
||||||
|
**Not covered yet:** response/output validation, validating a `@Step`'s own inputs, and
|
||||||
|
mesh remote-route validation are all out of scope for this feature.
|
||||||
|
|
||||||
|
## Inspect & test the graph
|
||||||
|
|
||||||
|
### Visualize with Mermaid
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
console.log(app.toMermaid()); // flowchart diagram of all nodes and routes
|
||||||
|
```
|
||||||
|
|
||||||
|
Enable a live `GET /__graph__` endpoint (renders HTML with Mermaid, or plain-text with `Accept: text/plain`):
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const app = createApp({ modules: [ApiModule], devGraph: true });
|
||||||
|
// GET /__graph__ → HTML viewer
|
||||||
|
// GET /__graph__ (text/plain) → raw Mermaid source
|
||||||
|
```
|
||||||
|
|
||||||
|
### Explain a route
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const e = app.explain('/api/users/:id');
|
||||||
|
// { pattern, method, transport, chain: [{ name, kind, origin, needs, provides }, ...] }
|
||||||
|
console.log(e.chain.map((n) => `${n.kind}:${n.name}`));
|
||||||
|
// → ['provider:db', 'step:user', 'handler:getUser']
|
||||||
|
```
|
||||||
|
|
||||||
|
### Override tokens in tests
|
||||||
|
|
||||||
|
Swap any provider or step token with a test double at construction time — no monkey-patching:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const app = createApp({
|
||||||
|
modules: [ApiModule],
|
||||||
|
overrides: {
|
||||||
|
db: { find: () => ({ id: 'test-user' }) }, // plain object — wrapped as { db: value }
|
||||||
|
user: () => ({ user: { id: 'stub' } }), // function runner
|
||||||
|
},
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
Overrides replace only the named token's runner; the rest of the graph is untouched.
|
||||||
|
|
||||||
|
## Runnable examples
|
||||||
|
|
||||||
|
The `example/` directory holds end-to-end apps you can `node`-run and read top to bottom.
|
||||||
|
|
||||||
|
### CRUD — methods, query, JSON & urlencoded body
|
||||||
|
|
||||||
|
`@Get/@Post/@Put/@Patch/@Delete` over a provider-backed store. Filter via `@query('done')`,
|
||||||
|
read the payload via `@body()` — the same handler accepts both `application/json` and
|
||||||
|
`application/x-www-form-urlencoded` (the transport parses each into a plain object). Missing
|
||||||
|
rows throw `NotFound` (→ 404).
|
||||||
|
|
||||||
|
See [`example/crud.ts`](../example/crud.ts).
|
||||||
|
|
||||||
|
### Chat — rooms + handshake auth
|
||||||
|
|
||||||
|
A `@Step` reads `?token=` and `provides: 'user'`, throwing `Unauthorized` on a missing token —
|
||||||
|
which closes the socket with code **4401** (`4000 + status`). The `@Ws` handler pumps the
|
||||||
|
`@inbound()` channel into `rooms.room(name)` and returns that same room as its outbound channel,
|
||||||
|
so every joined socket multicasts to the others. `rooms` is the built-in shared `Rooms`
|
||||||
|
primitive (one instance app-wide).
|
||||||
|
|
||||||
|
See [`example/chat.ts`](../example/chat.ts).
|
||||||
|
|
||||||
|
### GraphQL — query/mutation over POST, subscription over SSE
|
||||||
|
|
||||||
|
A schema built programmatically with `graphql` (a dev/example dependency — the core has no
|
||||||
|
runtime dep on it). `POST /graphql` runs queries and mutations through `graphql()`. The
|
||||||
|
`mutation` pushes each new message into `rooms.room('messages')`; the `@Sse('/stream')` route
|
||||||
|
calls `subscribe()` whose source **is** that room, guards the result with `isAsyncIterable`,
|
||||||
|
and returns it — the framework streams each `ExecutionResult` as an SSE `data:` frame. This is
|
||||||
|
the tie between GraphQL, green-tea streams, and the `rooms` primitive.
|
||||||
|
|
||||||
|
See [`example/graphql.ts`](../example/graphql.ts) — `npm install graphql` first.
|
||||||
|
|
||||||
|
## The one rule to remember
|
||||||
|
|
||||||
|
```
|
||||||
|
return a VALUE → buffered response (transformer → JSON)
|
||||||
|
return an AsyncIterable → stream (SSE / WS)
|
||||||
|
@needs a remote token → RPC to a teapot (mesh)
|
||||||
|
```
|
||||||
@@ -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' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { createApp, Step, Route, Ws, Module, Unauthorized, param, needs, inbound, Rooms } from '../src/index';
|
||||||
|
|
||||||
|
@Step({ provides: 'user', needs: [] })
|
||||||
|
class Authenticate {
|
||||||
|
run(ctx: any) {
|
||||||
|
const token = ctx.query?.token; // steps read ctx directly (no @query on steps)
|
||||||
|
if (!token) throw new Unauthorized('token required');
|
||||||
|
return { user: { id: String(token) } };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Route('/chat')
|
||||||
|
class ChatController {
|
||||||
|
@Ws('/:room')
|
||||||
|
join(@param('room') room: string, @needs('user') user: any, @needs('rooms') rooms: Rooms, @inbound() incoming: AsyncIterable<string>) {
|
||||||
|
const hub = rooms.room<string>(room);
|
||||||
|
(async () => { for await (const msg of incoming) hub.push(`${user.id}: ${msg}`); })().catch(() => {}); // fire-and-forget pump
|
||||||
|
return hub; // broadcast as the outbound channel
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Module({ mountpoint: '/', steps: [Authenticate], controllers: [ChatController] })
|
||||||
|
class ChatModule {}
|
||||||
|
|
||||||
|
export const app = createApp({ modules: [ChatModule] });
|
||||||
|
|
||||||
|
if (require.main === module) {
|
||||||
|
app.listen(4100).then(() => console.log('chat on ws://localhost:4100/chat/:room?token=...'));
|
||||||
|
}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
import {
|
||||||
|
createApp, Provider, Route,
|
||||||
|
Get, Post, Put, Patch, Delete,
|
||||||
|
Module, needs, param, query, body, NotFound,
|
||||||
|
} from '../src/index';
|
||||||
|
|
||||||
|
interface Todo { id: string; title: string; done: boolean }
|
||||||
|
|
||||||
|
interface Store {
|
||||||
|
todos: Map<string, Todo>;
|
||||||
|
next(): string;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Provider({ provides: 'store' })
|
||||||
|
class TodoStore {
|
||||||
|
private counter = 0;
|
||||||
|
private readonly todos: Map<string, Todo> = new Map();
|
||||||
|
|
||||||
|
provide(): { store: Store } {
|
||||||
|
const store: Store = {
|
||||||
|
todos: this.todos,
|
||||||
|
next: () => String(++this.counter),
|
||||||
|
};
|
||||||
|
return { store };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Route('/todos')
|
||||||
|
class TodoController {
|
||||||
|
@Get('/')
|
||||||
|
list(@needs('store') store: Store, @query('done') done: string | undefined): Todo[] {
|
||||||
|
const all = [...store.todos.values()];
|
||||||
|
if (done !== undefined) {
|
||||||
|
const flag = done === 'true';
|
||||||
|
return all.filter((t) => t.done === flag);
|
||||||
|
}
|
||||||
|
return all;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('/:id')
|
||||||
|
get(@needs('store') store: Store, @param('id') id: string): Todo {
|
||||||
|
const todo = store.todos.get(id);
|
||||||
|
if (!todo) throw new NotFound(`todo ${id} not found`);
|
||||||
|
return todo;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('/')
|
||||||
|
create(@needs('store') store: Store, @body() data: Record<string, unknown>): Todo {
|
||||||
|
const id = store.next();
|
||||||
|
const todo: Todo = { id, title: String(data.title ?? ''), done: false };
|
||||||
|
store.todos.set(id, todo);
|
||||||
|
return todo;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Put('/:id')
|
||||||
|
replace(@needs('store') store: Store, @param('id') id: string, @body() data: Record<string, unknown>): Todo {
|
||||||
|
if (!store.todos.has(id)) throw new NotFound(`todo ${id} not found`);
|
||||||
|
const todo: Todo = { id, title: String(data.title ?? ''), done: Boolean(data.done ?? false) };
|
||||||
|
store.todos.set(id, todo);
|
||||||
|
return todo;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch('/:id')
|
||||||
|
merge(@needs('store') store: Store, @param('id') id: string, @body() data: Record<string, unknown>): Todo {
|
||||||
|
const todo = store.todos.get(id);
|
||||||
|
if (!todo) throw new NotFound(`todo ${id} not found`);
|
||||||
|
const updated: Todo = {
|
||||||
|
id,
|
||||||
|
title: 'title' in data ? String(data.title) : todo.title,
|
||||||
|
done: 'done' in data ? Boolean(data.done) : todo.done,
|
||||||
|
};
|
||||||
|
store.todos.set(id, updated);
|
||||||
|
return updated;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete('/:id')
|
||||||
|
remove(@needs('store') store: Store, @param('id') id: string): { deleted: string } {
|
||||||
|
if (!store.todos.has(id)) throw new NotFound(`todo ${id} not found`);
|
||||||
|
store.todos.delete(id);
|
||||||
|
return { deleted: id };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Module({ mountpoint: '/api', providers: [TodoStore], controllers: [TodoController] })
|
||||||
|
class TodoModule {}
|
||||||
|
|
||||||
|
export const app = createApp({ modules: [TodoModule] });
|
||||||
|
|
||||||
|
if (require.main === module) {
|
||||||
|
app.listen(3300).then(() => console.log('green-tea crud on http://localhost:3300'));
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { GraphQLSchema, GraphQLObjectType, GraphQLString, GraphQLList, GraphQLNonNull, graphql, subscribe, parse } from 'graphql';
|
||||||
|
import { createApp, Route, Post, Sse, Module, body, needs, isAsyncIterable, Rooms } from '../src/index';
|
||||||
|
|
||||||
|
interface Message { text: string }
|
||||||
|
const store: Message[] = [];
|
||||||
|
const MessageType = new GraphQLObjectType({ name: 'Message', fields: { text: { type: GraphQLString } } });
|
||||||
|
|
||||||
|
function buildSchema(rooms: Rooms): GraphQLSchema {
|
||||||
|
return new GraphQLSchema({
|
||||||
|
query: new GraphQLObjectType({ name: 'Query', fields: {
|
||||||
|
messages: { type: new GraphQLList(MessageType), resolve: () => store },
|
||||||
|
} }),
|
||||||
|
mutation: new GraphQLObjectType({ name: 'Mutation', fields: {
|
||||||
|
postMessage: { type: MessageType, args: { text: { type: new GraphQLNonNull(GraphQLString) } },
|
||||||
|
resolve: (_root, { text }: { text: string }) => { const m = { text }; store.push(m); rooms.room('messages').push(m); return m; } },
|
||||||
|
} }),
|
||||||
|
subscription: new GraphQLObjectType({ name: 'Subscription', fields: {
|
||||||
|
messageAdded: { type: MessageType,
|
||||||
|
subscribe: () => rooms.room<Message>('messages'), // Channel is the AsyncIterable source
|
||||||
|
resolve: (payload: Message) => payload },
|
||||||
|
} }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Route('/graphql')
|
||||||
|
class GraphQLController {
|
||||||
|
@Post('')
|
||||||
|
async run(@body() input: any, @needs('rooms') rooms: Rooms) {
|
||||||
|
return graphql({ schema: buildSchema(rooms), source: input?.query ?? '', variableValues: input?.variables });
|
||||||
|
}
|
||||||
|
|
||||||
|
@Sse('/stream')
|
||||||
|
async stream(@needs('rooms') rooms: Rooms) {
|
||||||
|
const result = await subscribe({ schema: buildSchema(rooms), document: parse('subscription { messageAdded { text } }') });
|
||||||
|
if (!isAsyncIterable(result)) throw new Error('subscription failed'); // subscribe() returns a single ExecutionResult on error
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Module({ mountpoint: '/', controllers: [GraphQLController] })
|
||||||
|
class GraphQLModule {}
|
||||||
|
|
||||||
|
export const app = createApp({ modules: [GraphQLModule] });
|
||||||
|
|
||||||
|
if (require.main === module) {
|
||||||
|
app.listen(4200).then(() => console.log('graphql on http://localhost:4200/graphql'));
|
||||||
|
}
|
||||||
+84
-1
@@ -1,4 +1,4 @@
|
|||||||
import { createApp, Provider, Step, Route, Get, Module, Transformer, JsonTransformer, Unauthorized, Plugin, needs, param } from '../src/index';
|
import { createApp, Provider, Step, Route, Get, Module, Transformer, JsonTransformer, Unauthorized, Plugin, needs, param, Sse, Ws, inbound, channel, MESH_CONTROL_PATH } from '../src/index';
|
||||||
|
|
||||||
interface User { id: string; name: string }
|
interface User { id: string; name: string }
|
||||||
|
|
||||||
@@ -37,7 +37,90 @@ const logger: Plugin = (api) => {
|
|||||||
|
|
||||||
export const app = createApp({ modules: [ApiModule], plugins: [logger] });
|
export const app = createApp({ modules: [ApiModule], plugins: [logger] });
|
||||||
|
|
||||||
|
@Route('/feed')
|
||||||
|
class FeedController {
|
||||||
|
@Sse('/ticks')
|
||||||
|
ticks() {
|
||||||
|
return (async function* () {
|
||||||
|
for (let n = 1; n <= 3; n++) yield { tick: n };
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Module({ mountpoint: '/', controllers: [FeedController, ChatController] })
|
||||||
|
class StreamModule {}
|
||||||
|
|
||||||
|
export const streamApp = createApp({ modules: [StreamModule] });
|
||||||
|
|
||||||
if (require.main === module) {
|
if (require.main === module) {
|
||||||
console.log('chain for /api/users/:id ->', app.inspect('/api/users/:id'));
|
console.log('chain for /api/users/:id ->', app.inspect('/api/users/:id'));
|
||||||
|
console.log('graph:\n' + app.toMermaid());
|
||||||
|
console.log('explain /api/users/:id:', app.explain('/api/users/:id'));
|
||||||
app.listen(3000).then(() => console.log('green-tea on http://localhost:3000'));
|
app.listen(3000).then(() => console.log('green-tea on http://localhost:3000'));
|
||||||
|
streamApp.listen(3001).then(() => console.log('green-tea streams on http://localhost:3001'));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Mesh Demo (teapot / teacup) ───────────────────────────────────────────
|
||||||
|
|
||||||
|
@Provider({ provides: 'config', export: true })
|
||||||
|
class ConfigProvider {
|
||||||
|
provide() {
|
||||||
|
return { config: { env: 'demo' } };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Step({ provides: 'auth', needs: [], export: true })
|
||||||
|
class AuthStep {
|
||||||
|
run(ctx: { headers?: Record<string, string | string[] | undefined> }) {
|
||||||
|
const tok = ctx.headers?.['x-token'];
|
||||||
|
return { auth: Array.isArray(tok) ? tok[0] ?? 'anonymous' : tok ?? 'anonymous' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Route('/svc')
|
||||||
|
class PingController {
|
||||||
|
@Get('/ping', { export: true })
|
||||||
|
ping(@needs('config') config: { env: string }, @needs('auth') auth: string) {
|
||||||
|
return { pong: true, config, auth };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Module({ mountpoint: '/mesh', providers: [ConfigProvider], steps: [AuthStep], controllers: [PingController] })
|
||||||
|
class TeapotModule {}
|
||||||
|
|
||||||
|
export const teapotApp = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'demo-secret' } });
|
||||||
|
|
||||||
|
@Route('/remote')
|
||||||
|
class TeacupController {
|
||||||
|
@Get('/status')
|
||||||
|
status(@needs('config') config: { env: string }, @needs('auth') auth: string) {
|
||||||
|
return { via: 'teacup', config, auth };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Module({ mountpoint: '/', controllers: [TeacupController] })
|
||||||
|
class TeacupModule {}
|
||||||
|
|
||||||
|
if (require.main === module) {
|
||||||
|
teapotApp.listen(3002).then(() => {
|
||||||
|
console.log('teapot on http://localhost:3002');
|
||||||
|
const teacupApp = createApp({
|
||||||
|
modules: [TeacupModule],
|
||||||
|
mesh: { teapots: [{ url: `ws://127.0.0.1:3002${MESH_CONTROL_PATH}`, secret: 'demo-secret' }] },
|
||||||
|
});
|
||||||
|
teacupApp.listen(3003).then(() => console.log('teacup on http://localhost:3003'));
|
||||||
|
});
|
||||||
}
|
}
|
||||||
Generated
+7348
-3
File diff suppressed because it is too large.
Load diff
+128
-7
@@ -1,23 +1,144 @@
|
|||||||
{
|
{
|
||||||
"name": "@green-tea/core",
|
"name": "@green-tea/core",
|
||||||
"version": "0.0.0",
|
"version": "26.7.0-beta.0",
|
||||||
"description": "Declarative, type-safe HTTP framework. The pipeline is a graph, not a middleware chain.",
|
"description": "A zen, opinionated, type-safe framework — your API is a graph, not a middleware chain.",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"author": "green-tea contributors",
|
||||||
|
"keywords": [
|
||||||
|
"http",
|
||||||
|
"framework",
|
||||||
|
"typescript",
|
||||||
|
"dependency-injection",
|
||||||
|
"decorators",
|
||||||
|
"dependency-graph",
|
||||||
|
"sse",
|
||||||
|
"websocket",
|
||||||
|
"streaming",
|
||||||
|
"node"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"publishConfig": {
|
||||||
|
"access": "public"
|
||||||
|
},
|
||||||
"type": "commonjs",
|
"type": "commonjs",
|
||||||
"main": "dist/index.js",
|
"main": "./dist/index.js",
|
||||||
"types": "dist/index.d.ts",
|
"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": {
|
"scripts": {
|
||||||
"build": "tsc -p tsconfig.json",
|
"build": "tsup",
|
||||||
"test": "vitest run",
|
"test": "vitest run",
|
||||||
"test:dev": "vitest",
|
"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": {
|
"dependencies": {
|
||||||
"reflect-metadata": "0.2.2"
|
"reflect-metadata": "0.2.2"
|
||||||
},
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"busboy": "^1.6.0",
|
||||||
|
"ws": "^8.18.0"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"busboy": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"ws": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@eslint/js": "^9.39.4",
|
||||||
|
"@nestjs/common": "^11.1.27",
|
||||||
|
"@nestjs/core": "^11.1.27",
|
||||||
|
"@nestjs/platform-express": "^11.1.27",
|
||||||
|
"@nestjs/platform-fastify": "^11.1.27",
|
||||||
|
"@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.4",
|
||||||
|
"express": "^5.2.1",
|
||||||
|
"fastify": "^5.10.0",
|
||||||
|
"graphql": "^16.9.0",
|
||||||
|
"miniflare": "^4.20260708.1",
|
||||||
|
"prettier": "^3.9.4",
|
||||||
|
"rxjs": "^7.8.2",
|
||||||
|
"tsup": "^8.5.1",
|
||||||
|
"tsx": "^4.23.0",
|
||||||
"typescript": "^5.5.0",
|
"typescript": "^5.5.0",
|
||||||
|
"typescript-eslint": "^8.63.0",
|
||||||
"vitest": "^2.0.0",
|
"vitest": "^2.0.0",
|
||||||
"@types/node": "^18.19.0"
|
"ws": "^8.21.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
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}`);
|
||||||
-181
@@ -1,181 +0,0 @@
|
|||||||
import http from 'http';
|
|
||||||
import { Bus } from './bus';
|
|
||||||
import { Container } from './container';
|
|
||||||
import { topoSort, GraphNode } from './graph';
|
|
||||||
import { runPipeline, PipelineStep } from './pipeline';
|
|
||||||
import { createHttpServer, RouteDef } from './http';
|
|
||||||
import { JsonTransformer } from './transformers';
|
|
||||||
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from './plugin';
|
|
||||||
import {
|
|
||||||
Ctor, getModuleMeta, getProviderMeta, getStepMeta, getRoutes, getTransformer, joinPath,
|
|
||||||
} from './metadata';
|
|
||||||
import { getArgs, getHandlerNeeds, resolveArgs } from './params';
|
|
||||||
|
|
||||||
export interface InspectLine { name: string; kind: 'provider' | 'step' | 'handler'; origin: string }
|
|
||||||
export interface App {
|
|
||||||
listen(port: number): Promise<http.Server>;
|
|
||||||
inspect(routePath: string): InspectLine[];
|
|
||||||
bus: Bus;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface RoutePlan {
|
|
||||||
pattern: string;
|
|
||||||
origin: string;
|
|
||||||
providers: GraphNode[];
|
|
||||||
steps: GraphNode[];
|
|
||||||
handlerName: string;
|
|
||||||
needs: string[];
|
|
||||||
run: (ctx: any) => unknown;
|
|
||||||
transformer: typeof JsonTransformer;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[] }): App {
|
|
||||||
const bus = new Bus();
|
|
||||||
const container = new Container();
|
|
||||||
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[] = [];
|
|
||||||
|
|
||||||
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 });
|
|
||||||
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 });
|
|
||||||
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);
|
|
||||||
routePlans.push({
|
|
||||||
pattern: joinPath(m.mountpoint, route.path),
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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.
|
|
||||||
const seedKeys = ['req', 'params'];
|
|
||||||
const ordered = topoSort([...providerNodes, ...stepNodes], seedKeys);
|
|
||||||
const orderedProviders = ordered.filter((n) => providerNodes.includes(n));
|
|
||||||
const orderedSteps = ordered.filter((n) => stepNodes.includes(n));
|
|
||||||
for (const plan of routePlans) { plan.providers = orderedProviders; plan.steps = orderedSteps; }
|
|
||||||
|
|
||||||
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']);
|
|
||||||
for (const plan of routePlans) {
|
|
||||||
for (const need of plan.needs) {
|
|
||||||
if (!allowed.has(need)) {
|
|
||||||
throw new Error(`handler '${plan.handlerName}' needs '${need}' but nothing provides it`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const inspect = (routePath: string): InspectLine[] => {
|
|
||||||
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 listen = async (port: number): Promise<http.Server> => {
|
|
||||||
// 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}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const routeDefs: RouteDef[] = routePlans.map((plan) => ({
|
|
||||||
method: 'GET',
|
|
||||||
pattern: plan.pattern,
|
|
||||||
handler: async (req) => {
|
|
||||||
// build app-scoped seed by spreading each provider's resolved value into context
|
|
||||||
// providers follow the same merge convention as steps: return { token: value }
|
|
||||||
const provided: Record<string, unknown> = {};
|
|
||||||
for (const p of plan.providers) {
|
|
||||||
if (container.has(p.name)) {
|
|
||||||
const resolved = (await container.resolve(p.name)) as Record<string, unknown>;
|
|
||||||
Object.assign(provided, resolved);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const steps: 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 };
|
|
||||||
});
|
|
||||||
return runPipeline({
|
|
||||||
steps, handler: plan.run, transformer: plan.transformer, bus,
|
|
||||||
seed: { ...provided, req, params: req.params, query: req.query, body: req.body, headers: req.headers },
|
|
||||||
});
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
|
|
||||||
const server = createHttpServer(routeDefs);
|
|
||||||
await new Promise<void>((resolve) => server.listen(port, resolve));
|
|
||||||
return server;
|
|
||||||
};
|
|
||||||
|
|
||||||
return { listen, inspect, 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;
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,973 @@
|
|||||||
|
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';
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
registry.routePlans.push({
|
||||||
|
pattern,
|
||||||
|
method: route.method,
|
||||||
|
transport: route.transport,
|
||||||
|
origin,
|
||||||
|
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,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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/PUT/PATCH/DELETE)`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
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, string>(); // "METHOD /pattern" -> the teapot that exported it
|
||||||
|
|
||||||
|
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 key = `${route.method} ${route.pattern}`;
|
||||||
|
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: route '${key}' is exported by more than one teapot (${owner} and ${teapot.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, teapot.url);
|
||||||
|
|
||||||
|
// 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 && plan.pattern === route.pattern)) {
|
||||||
|
console.warn(
|
||||||
|
`[green-tea] mesh: route '${key}' 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,97 @@
|
|||||||
|
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;
|
||||||
|
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
-10
@@ -1,8 +1,20 @@
|
|||||||
|
/** Names of every lifecycle event the framework emits over the {@link Bus}. */
|
||||||
export type LifecycleEvent =
|
export type LifecycleEvent =
|
||||||
| 'boot:provider:start' | 'boot:provider:ok' | 'boot:provider:fail'
|
| 'boot:provider:start'
|
||||||
| 'request:step:enter' | 'request:step:leave' | 'request:step:error'
|
| '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';
|
| 'plugin:mounted';
|
||||||
|
|
||||||
|
/** Data carried by a lifecycle event: the subject's name plus optional scope, error and timing. */
|
||||||
export interface EventPayload {
|
export interface EventPayload {
|
||||||
name: string;
|
name: string;
|
||||||
scope?: string;
|
scope?: string;
|
||||||
@@ -10,19 +22,26 @@ export interface EventPayload {
|
|||||||
durationMs?: number;
|
durationMs?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** In-process pub/sub for framework lifecycle events; observer failures are swallowed so they never break the pipeline. */
|
||||||
export class Bus {
|
export class Bus {
|
||||||
private readonly listeners = new Map<LifecycleEvent, Set<(p: EventPayload) => void>>();
|
private readonly listeners = new Map<LifecycleEvent, Set<(p: EventPayload) => void>>();
|
||||||
|
|
||||||
on(event: LifecycleEvent, fn: (p: EventPayload) => void): () => void {
|
/** Subscribe `listener` to `event`; returns an unsubscribe function. */
|
||||||
const set = this.listeners.get(event) ?? new Set();
|
on(event: LifecycleEvent, listener: (p: EventPayload) => void): () => void {
|
||||||
set.add(fn);
|
const listenerSet = this.listeners.get(event) ?? new Set();
|
||||||
this.listeners.set(event, set);
|
listenerSet.add(listener);
|
||||||
return () => set.delete(fn);
|
this.listeners.set(event, listenerSet);
|
||||||
|
return () => listenerSet.delete(listener);
|
||||||
}
|
}
|
||||||
|
|
||||||
emit(event: LifecycleEvent, p: EventPayload): void {
|
/** Dispatch `payload` to every listener of `event`; a throwing listener is isolated and does not affect the others. */
|
||||||
for (const fn of this.listeners.get(event) ?? []) {
|
emit(event: LifecycleEvent, payload: EventPayload): void {
|
||||||
try { fn(p); } catch { /* observers must never break the pipeline */ }
|
for (const listener of this.listeners.get(event) ?? []) {
|
||||||
|
try {
|
||||||
|
listener(payload);
|
||||||
|
} catch {
|
||||||
|
/* observers must never break the pipeline */
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+121
@@ -0,0 +1,121 @@
|
|||||||
|
/**
|
||||||
|
* 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;
|
||||||
|
fail(err: unknown): void;
|
||||||
|
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(value: T, cap: number): void;
|
||||||
|
end(): void;
|
||||||
|
fail(err: unknown): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function newSub<T>(onReturn: () => void): Sub<T> {
|
||||||
|
const queue: T[] = [];
|
||||||
|
let pending: { resolve: (r: IteratorResult<T>) => void; reject: (e: unknown) => void } | null = null;
|
||||||
|
let ended = false;
|
||||||
|
let failure: { err: unknown } | null = null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
push(value, cap) {
|
||||||
|
if (ended) return;
|
||||||
|
|
||||||
|
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 waiter = pending;
|
||||||
|
pending = null;
|
||||||
|
waiter.resolve({ value: undefined as never, done: true });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
fail(err) {
|
||||||
|
if (ended) return;
|
||||||
|
ended = true;
|
||||||
|
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(): Promise<IteratorResult<T>> {
|
||||||
|
ended = true;
|
||||||
|
onReturn();
|
||||||
|
return Promise.resolve({ value: undefined as never, done: true });
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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>>();
|
||||||
|
let done = false;
|
||||||
|
let closedFlag = false;
|
||||||
|
|
||||||
|
return {
|
||||||
|
get closed() {
|
||||||
|
return closedFlag;
|
||||||
|
},
|
||||||
|
push(value) {
|
||||||
|
if (done) return;
|
||||||
|
for (const sub of subs) sub.push(value, cap);
|
||||||
|
},
|
||||||
|
close() {
|
||||||
|
if (done) return;
|
||||||
|
done = true;
|
||||||
|
closedFlag = true;
|
||||||
|
for (const sub of subs) sub.end();
|
||||||
|
subs.clear();
|
||||||
|
},
|
||||||
|
fail(err) {
|
||||||
|
if (done) return;
|
||||||
|
done = true;
|
||||||
|
closedFlag = true;
|
||||||
|
for (const sub of subs) sub.fail(err);
|
||||||
|
subs.clear();
|
||||||
|
},
|
||||||
|
[Symbol.asyncIterator](): AsyncIterator<T> {
|
||||||
|
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';
|
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>;
|
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 {
|
export class Container {
|
||||||
private readonly bindings = new Map<string, Binding>();
|
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 {
|
register(token: string, scope: Scope, factory: Factory): void {
|
||||||
this.bindings.set(token, { scope, factory });
|
this.bindings.set(token, { scope, factory });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Whether `token` currently has a binding. */
|
||||||
has(token: string): boolean {
|
has(token: string): boolean {
|
||||||
return this.bindings.has(token);
|
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
|
// ponytail: app-scope memoizes; request-scope always re-runs. resolve is async
|
||||||
// so a future remote transport (mesh) slots in without changing callers.
|
// so a future remote transport (mesh) slots in without changing callers.
|
||||||
async resolve(token: string, ctx: Record<string, unknown> = {}): Promise<unknown> {
|
async resolve(token: string, ctx: Record<string, unknown> = {}): Promise<unknown> {
|
||||||
const b = this.bindings.get(token);
|
const binding = this.bindings.get(token);
|
||||||
if (!b) throw new Error(`unknown token: ${token}`);
|
if (!binding) throw new Error(`unknown token: ${token}`);
|
||||||
if (b.scope === 'app' && b.resolved) return b.cached;
|
if (binding.scope === 'app' && binding.resolved) return binding.cached;
|
||||||
const value = await b.factory(ctx);
|
const value = await binding.factory(ctx);
|
||||||
if (b.scope === 'app') { b.cached = value; b.resolved = true; }
|
|
||||||
|
if (binding.scope === 'app') {
|
||||||
|
binding.cached = value;
|
||||||
|
binding.resolved = true;
|
||||||
|
}
|
||||||
|
|
||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+47
@@ -0,0 +1,47 @@
|
|||||||
|
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') {
|
||||||
|
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, toWsRequest(request, info.remoteAddr.hostname), 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);
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
/**
|
||||||
|
* 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;
|
||||||
|
encodeError(err: unknown): string | Buffer | null;
|
||||||
|
ping?(): string;
|
||||||
|
}
|
||||||
|
|
||||||
|
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: 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: 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>;
|
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> {
|
export interface CompiledFlow<Seed, Acc> {
|
||||||
steps: { name: string; fn: StepFn<any, any> }[];
|
steps: { name: string; fn: StepFn<any, any> }[];
|
||||||
handler: (ctx: Acc) => unknown;
|
handler: (ctx: Acc) => unknown;
|
||||||
run(seed: Seed): Promise<unknown>;
|
run(seed: Seed): Promise<unknown>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Immutable builder that chains typed steps, each widening the accumulated context type. */
|
||||||
export class Flow<Seed, Acc> {
|
export class Flow<Seed, Acc> {
|
||||||
constructor(private readonly steps: { name: string; fn: StepFn<any, any> }[] = []) {}
|
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> {
|
step<Out>(name: string, fn: StepFn<Acc, Out>): Flow<Seed, Acc & Out> {
|
||||||
return new Flow<Seed, Acc & Out>([...this.steps, { name, fn }]);
|
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> {
|
handle(handler: (ctx: Acc) => unknown): CompiledFlow<Seed, Acc> {
|
||||||
const steps = this.steps;
|
const steps = this.steps;
|
||||||
return {
|
return {
|
||||||
@@ -20,16 +25,19 @@ export class Flow<Seed, Acc> {
|
|||||||
handler,
|
handler,
|
||||||
async run(seed: Seed): Promise<unknown> {
|
async run(seed: Seed): Promise<unknown> {
|
||||||
let ctx: any = { ...seed };
|
let ctx: any = { ...seed };
|
||||||
for (const s of steps) {
|
|
||||||
const out = await s.fn(ctx);
|
for (const step of steps) {
|
||||||
ctx = { ...ctx, ...out };
|
const output = await step.fn(ctx);
|
||||||
|
ctx = { ...ctx, ...output };
|
||||||
}
|
}
|
||||||
|
|
||||||
return handler(ctx);
|
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> {
|
export function flow<Seed extends object>(): Flow<Seed, Seed> {
|
||||||
return new Flow<Seed, Seed>();
|
return new Flow<Seed, Seed>();
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,238 @@
|
|||||||
|
/** 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[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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((node) => node.name));
|
||||||
|
const out: string[] = ['flowchart LR'];
|
||||||
|
|
||||||
|
for (const node of view.nodes) {
|
||||||
|
out.push(
|
||||||
|
node.kind === 'provider' ? ` ${nid(node.name)}(["${node.name}"])` : ` ${nid(node.name)}["${node.name}"]`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
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((node) => node.name));
|
||||||
|
const out: string[] = ['digraph green_tea {', ' rankdir=LR;'];
|
||||||
|
|
||||||
|
for (const node of view.nodes) {
|
||||||
|
out.push(` "${node.name}" [shape=${node.kind === 'provider' ? 'ellipse' : 'box'}];`);
|
||||||
|
}
|
||||||
|
|
||||||
|
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 link of route.chain) if (known.has(link)) out.push(` "${link}" -> "${label}";`);
|
||||||
|
}
|
||||||
|
|
||||||
|
out.push('}');
|
||||||
|
return out.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>`;
|
||||||
|
}
|
||||||
+73
-15
@@ -1,3 +1,40 @@
|
|||||||
|
function levenshtein(a: string, b: string): number {
|
||||||
|
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 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 {
|
export interface GraphNode {
|
||||||
name: string;
|
name: string;
|
||||||
needs: string[];
|
needs: string[];
|
||||||
@@ -5,15 +42,16 @@ export interface GraphNode {
|
|||||||
origin: string;
|
origin: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Orders nodes so every dependency precedes its dependents; throws on missing keys or cycles. */
|
||||||
export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] {
|
export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] {
|
||||||
const producedBy = new Map<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
|
// validate dependencies exist
|
||||||
for (const n of nodes) {
|
for (const node of nodes) {
|
||||||
for (const key of n.needs) {
|
for (const key of node.needs) {
|
||||||
if (!seedKeys.includes(key) && !producedBy.has(key)) {
|
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}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -21,19 +59,39 @@ export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] {
|
|||||||
const ordered: GraphNode[] = [];
|
const ordered: GraphNode[] = [];
|
||||||
const state = new Map<GraphNode, 'visiting' | 'done'>();
|
const state = new Map<GraphNode, 'visiting' | 'done'>();
|
||||||
|
|
||||||
const visit = (n: GraphNode, trail: string[]): void => {
|
const visit = (node: GraphNode, trail: string[]): void => {
|
||||||
const s = state.get(n);
|
const visitState = state.get(node);
|
||||||
if (s === 'done') return;
|
if (visitState === 'done') return;
|
||||||
if (s === 'visiting') throw new Error(`cycle detected: ${[...trail, n.name].join(' -> ')}`);
|
if (visitState === 'visiting') throw new Error(`cycle detected: ${[...trail, node.name].join(' -> ')}`);
|
||||||
state.set(n, 'visiting');
|
state.set(node, 'visiting');
|
||||||
for (const key of n.needs) {
|
|
||||||
const dep = producedBy.get(key);
|
for (const key of node.needs) {
|
||||||
if (dep && dep !== n) visit(dep, [...trail, n.name]);
|
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;
|
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 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);
|
||||||
|
if (!node || inClosure.has(node)) continue; // no producer = seed/envelope; already-seen = skip
|
||||||
|
inClosure.add(node);
|
||||||
|
work.push(...node.needs);
|
||||||
|
}
|
||||||
|
|
||||||
|
return ordered.filter((node) => inClosure.has(node));
|
||||||
|
}
|
||||||
-90
@@ -1,90 +0,0 @@
|
|||||||
import http from 'http';
|
|
||||||
import { errorToResponse } from './transformers';
|
|
||||||
import type { ResponseShape } from './pipeline';
|
|
||||||
|
|
||||||
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<ResponseShape>;
|
|
||||||
|
|
||||||
export interface RouteDef { method: string; pattern: string; handler: RouteHandler }
|
|
||||||
export interface MatchedRoute { params: Record<string, string>; handler: RouteHandler }
|
|
||||||
|
|
||||||
export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined {
|
|
||||||
const segs = path.split('/').filter(Boolean);
|
|
||||||
for (const r of routes) {
|
|
||||||
if (r.method !== method) continue;
|
|
||||||
const pat = r.pattern.split('/').filter(Boolean);
|
|
||||||
if (pat.length !== segs.length) continue;
|
|
||||||
const params: Record<string, string> = {};
|
|
||||||
let ok = true;
|
|
||||||
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]) { ok = false; break; }
|
|
||||||
}
|
|
||||||
if (ok) return { params, handler: r.handler };
|
|
||||||
}
|
|
||||||
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): Promise<string | undefined> {
|
|
||||||
const chunks: Buffer[] = [];
|
|
||||||
for await (const chunk of req) chunks.push(chunk as Buffer);
|
|
||||||
if (chunks.length === 0) return undefined;
|
|
||||||
const raw = Buffer.concat(chunks).toString('utf8');
|
|
||||||
return raw === '' ? undefined : raw;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function createHttpServer(routes: RouteDef[]): http.Server {
|
|
||||||
return 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);
|
|
||||||
} catch {
|
|
||||||
// stream/network failure — not the client's JSON fault
|
|
||||||
res.writeHead(500, { 'content-type': 'application/json' });
|
|
||||||
res.end(JSON.stringify({ error: 'Internal Server Error' }));
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let result: ResponseShape;
|
|
||||||
try {
|
|
||||||
result = await matched.handler({
|
|
||||||
method: req.method ?? 'GET', url, headers: req.headers,
|
|
||||||
params: matched.params, query: parseQuery(url), body,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
result = errorToResponse(error);
|
|
||||||
}
|
|
||||||
res.writeHead(result.status, result.headers);
|
|
||||||
res.end(result.body);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
// 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 { matchRoute, allowedMethods, 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 path = req.url.split('?')[0];
|
||||||
|
const injected = computeInjected(opts, req);
|
||||||
|
|
||||||
|
if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) {
|
||||||
|
return { preflight: corsPreflightHeaders(opts.cors, req) };
|
||||||
|
}
|
||||||
|
|
||||||
|
const matched = matchRoute(routes, req.method, path);
|
||||||
|
|
||||||
|
if (!matched) {
|
||||||
|
if ((req.method === 'GET' || req.method === 'HEAD') && opts?.static) {
|
||||||
|
const hit = await opts.static(path);
|
||||||
|
|
||||||
|
if (hit) {
|
||||||
|
const body = req.method === 'HEAD' ? '' : hit.body;
|
||||||
|
return {
|
||||||
|
injected,
|
||||||
|
outcome: { kind: 'buffered', status: 200, headers: { 'content-type': hit.contentType }, body },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Path matches a route under a different method → 405 with Allow; otherwise 404.
|
||||||
|
const allow = allowedMethods(routes, path);
|
||||||
|
const err = allow.length ? new HttpError(405, 'Method Not Allowed') : new NotFound('Not Found');
|
||||||
|
const rendered = renderError(err, { method: req.method, url: req.url, headers: req.headers }, opts?.onError);
|
||||||
|
const headers = allow.length ? { ...rendered.headers, allow: allow.join(', ') } : rendered.headers;
|
||||||
|
return { injected, outcome: { kind: 'buffered', status: rendered.status, headers, body: rendered.body } };
|
||||||
|
}
|
||||||
|
|
||||||
|
let result: PipelineResult;
|
||||||
|
|
||||||
|
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: 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,92 @@
|
|||||||
|
import type { RouteDef, MatchedRoute } from './types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Matches a route pattern against a request path. Supports static segments, `:param` (one segment),
|
||||||
|
* and a trailing `:name*` catch-all that captures the rest of the path (slashes included) into `params.name`.
|
||||||
|
* @returns Extracted params (decoded) when the path matches, otherwise undefined.
|
||||||
|
*/
|
||||||
|
export function matchPattern(pattern: string, path: string): Record<string, string> | undefined {
|
||||||
|
const pathSegs = path.split('/').filter(Boolean);
|
||||||
|
const patternSegs = pattern.split('/').filter(Boolean);
|
||||||
|
const params: Record<string, string> = {};
|
||||||
|
|
||||||
|
for (let i = 0; i < patternSegs.length; i++) {
|
||||||
|
const seg = patternSegs[i];
|
||||||
|
|
||||||
|
// Trailing catch-all: capture every remaining segment (possibly none) as one decoded value.
|
||||||
|
if (seg.startsWith(':') && seg.endsWith('*')) {
|
||||||
|
params[seg.slice(1, -1)] = pathSegs.slice(i).map(decodeURIComponent).join('/');
|
||||||
|
return params;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (i >= pathSegs.length) return undefined; // pattern longer than path
|
||||||
|
|
||||||
|
if (seg.startsWith(':')) params[seg.slice(1)] = decodeURIComponent(pathSegs[i]);
|
||||||
|
else if (seg !== pathSegs[i]) return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
// No catch-all consumed the tail, so the lengths must match exactly.
|
||||||
|
return patternSegs.length === pathSegs.length ? params : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Splits a pattern into its fixed-prefix segment kinds (2 = static, 1 = param) and whether it ends in a catch-all. */
|
||||||
|
function segScores(pattern: string): { catchAll: boolean; kinds: number[] } {
|
||||||
|
const kinds: number[] = [];
|
||||||
|
|
||||||
|
for (const seg of pattern.split('/').filter(Boolean)) {
|
||||||
|
if (seg.startsWith(':') && seg.endsWith('*')) return { catchAll: true, kinds };
|
||||||
|
kinds.push(seg.startsWith(':') ? 1 : 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { catchAll: false, kinds };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Orders two matching patterns by specificity: exact beats catch-all, then static beats param, then longer wins. */
|
||||||
|
function moreSpecific(a: string, b: string): number {
|
||||||
|
const scoreA = segScores(a);
|
||||||
|
const scoreB = segScores(b);
|
||||||
|
if (scoreA.catchAll !== scoreB.catchAll) return scoreA.catchAll ? -1 : 1;
|
||||||
|
const length = Math.max(scoreA.kinds.length, scoreB.kinds.length);
|
||||||
|
|
||||||
|
for (let i = 0; i < length; i++) {
|
||||||
|
const kindA = scoreA.kinds[i] ?? -1;
|
||||||
|
const kindB = scoreB.kinds[i] ?? -1;
|
||||||
|
if (kindA !== kindB) return kindA - kindB;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Finds the most specific route matching both method and path (static > param > catch-all; 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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)) methods.add(route.method);
|
||||||
|
return [...methods];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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,222 @@
|
|||||||
|
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 { matchRoute } 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']);
|
||||||
|
const matched = isPreflight ? undefined : matchRoute(routes, method, path);
|
||||||
|
|
||||||
|
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>;
|
||||||
|
}
|
||||||
+165
@@ -0,0 +1,165 @@
|
|||||||
|
import type { StreamEncoder } from '../encoders';
|
||||||
|
import { handle, computeInjected, type HandleResult } from './core';
|
||||||
|
import { mergeInjectedHeaders } from './headers';
|
||||||
|
import { parseRequestBody } from './server';
|
||||||
|
import { matchRoute } 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 });
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Response(result.outcome.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);
|
||||||
|
const matched = matchRoute(routes, request.method, url.pathname);
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
+74
-5
@@ -1,14 +1,83 @@
|
|||||||
|
/**
|
||||||
|
* @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';
|
import 'reflect-metadata';
|
||||||
|
|
||||||
export const VERSION = '0.0.0';
|
/** Package version, replaced at publish time. */
|
||||||
|
export const VERSION = '26.7.0-beta.0';
|
||||||
|
|
||||||
|
// Application
|
||||||
export { createApp } from './app';
|
export { createApp } from './app';
|
||||||
export type { App, InspectLine } from './app';
|
export type { App, InspectLine, Explain, MeshConfig } from './app';
|
||||||
export { Provider, Step, Route, Get, Module, Transformer } from './metadata';
|
|
||||||
|
// Graph visualization
|
||||||
|
export { toMermaid, toDOT } from './graph-viz';
|
||||||
|
export type { GraphView } from './graph-viz';
|
||||||
|
export { buildOpenApi } from './openapi';
|
||||||
|
export type { OpenApiDoc, OpenApiInfo, OpenApiRoute } from './openapi';
|
||||||
|
|
||||||
|
// Views
|
||||||
|
export { render } from './views';
|
||||||
|
|
||||||
|
// Routing & decorators
|
||||||
|
export {
|
||||||
|
Provider,
|
||||||
|
Step,
|
||||||
|
Route,
|
||||||
|
Get,
|
||||||
|
Module,
|
||||||
|
Transformer,
|
||||||
|
Sse,
|
||||||
|
Ws,
|
||||||
|
Stream,
|
||||||
|
Post,
|
||||||
|
Put,
|
||||||
|
Patch,
|
||||||
|
Delete,
|
||||||
|
Html,
|
||||||
|
} from './metadata';
|
||||||
|
export type { Transport, HttpMethod } from './metadata';
|
||||||
export type { Plugin } from './plugin';
|
export type { Plugin } from './plugin';
|
||||||
|
|
||||||
|
// Transformers & error signals
|
||||||
export { JsonTransformer } from './transformers';
|
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 { Bus } from './bus';
|
||||||
export { flow, Flow } from './flow';
|
export { flow, Flow } from './flow';
|
||||||
export type { StepFn, CompiledFlow } 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';
|
export type { Query, Headers, Context, ArgSpec } from './params';
|
||||||
|
|
||||||
|
// Streaming
|
||||||
|
export { channel, isAsyncIterable } from './channel';
|
||||||
|
export type { Channel } from './channel';
|
||||||
|
export { Rooms } from './rooms';
|
||||||
|
export { sseEncoder, ndjsonEncoder } from './encoders';
|
||||||
|
export type { StreamEncoder } from './encoders';
|
||||||
|
|
||||||
|
// 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';
|
||||||
|
export type { Manifest, RequestEnvelope, Frame } from './mesh/protocol';
|
||||||
@@ -0,0 +1,259 @@
|
|||||||
|
import type { Bus } from '../bus';
|
||||||
|
import { HttpError } from '../signals';
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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 { 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(() => {
|
||||||
|
socket.close();
|
||||||
|
reject(new Error(`mesh connect timeout: ${args.url}`));
|
||||||
|
}, timeoutMs);
|
||||||
|
|
||||||
|
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 });
|
||||||
|
rejectAllPending(pending, `mesh link to ${args.url} is down`);
|
||||||
|
if (!manifest) reject(new Error(`mesh handshake failed: ${args.url}`));
|
||||||
|
},
|
||||||
|
{ once: true },
|
||||||
|
);
|
||||||
|
|
||||||
|
void readFrames(hs).catch(() => {
|
||||||
|
/* inbound failed; the abort listener above reports it */
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
/**
|
||||||
|
* 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>;
|
||||||
|
query: Record<string, string>;
|
||||||
|
body: unknown;
|
||||||
|
headers: Record<string, string | string[] | undefined>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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'; 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: 'ping' }
|
||||||
|
| { type: 'pong' };
|
||||||
|
|
||||||
|
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;
|
||||||
|
|
||||||
|
/** 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import type { Link } from './link';
|
||||||
|
import type { RequestEnvelope } from './protocol';
|
||||||
|
import type { ResponseShape } from '../pipeline';
|
||||||
|
|
||||||
|
/** 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',
|
||||||
|
params: ctx?.params ?? {},
|
||||||
|
query: ctx?.query ?? {},
|
||||||
|
body: ctx?.body,
|
||||||
|
headers: ctx?.headers ?? {},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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 scope of link.manifest.scopes) {
|
||||||
|
const node: RemoteScopeNode = {
|
||||||
|
name: scope.token,
|
||||||
|
run: async (ctx: any) => ({ [scope.token]: await link.rpc('scope', scope.token, envelopeFrom(ctx)) }),
|
||||||
|
};
|
||||||
|
(scope.scope === 'app' ? providers : steps).push(node);
|
||||||
|
}
|
||||||
|
|
||||||
|
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 };
|
||||||
|
}
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
// 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,
|
||||||
|
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)
|
||||||
|
routes: RouteEntry[]; // exported buffered routes
|
||||||
|
}): Manifest {
|
||||||
|
return {
|
||||||
|
scopes: [
|
||||||
|
...args.providers.map((token) => ({ token, scope: 'app' as const })),
|
||||||
|
...args.steps.map((token) => ({ token, scope: 'request' as const })),
|
||||||
|
],
|
||||||
|
routes: args.routes,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
resolveScope: (name: string, env: RequestEnvelope) => Promise<unknown>;
|
||||||
|
resolveRoute: (name: string, env: RequestEnvelope) => Promise<ResponseShape>;
|
||||||
|
bus?: Bus;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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,
|
||||||
|
/**
|
||||||
|
* 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);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
+157
-21
@@ -1,13 +1,50 @@
|
|||||||
import 'reflect-metadata';
|
import 'reflect-metadata';
|
||||||
|
|
||||||
|
/** Any class constructor. Kept `any` because decorators must accept every target shape. */
|
||||||
export type Ctor = new (...args: any[]) => any;
|
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 type TransformerFn = (value: unknown) => { status?: number; headers?: Record<string, string>; body: string };
|
||||||
|
|
||||||
export interface ProviderMeta { provides: string; needs: string[]; optional: boolean }
|
/** Metadata attached by `@Html`: optional file path and whether it is a template. */
|
||||||
export interface StepMeta { provides: string; needs: string[]; optional: boolean }
|
export interface HtmlMeta {
|
||||||
export interface RouteMeta { method: 'GET'; path: string; handlerName: string }
|
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' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
||||||
|
/** Wire transport a route responds with. */
|
||||||
|
export type Transport = 'buffer' | 'sse' | 'ndjson' | 'negotiate' | 'ws';
|
||||||
|
/** 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 {
|
export interface ModuleOptions {
|
||||||
mountpoint: string; providers?: Ctor[]; steps?: Ctor[]; controllers?: Ctor[];
|
mountpoint: string;
|
||||||
|
providers?: Ctor[];
|
||||||
|
steps?: Ctor[];
|
||||||
|
controllers?: Ctor[];
|
||||||
}
|
}
|
||||||
|
|
||||||
const K = {
|
const K = {
|
||||||
@@ -17,63 +54,162 @@ const K = {
|
|||||||
routes: Symbol('gt:routes'),
|
routes: Symbol('gt:routes'),
|
||||||
module: Symbol('gt:module'),
|
module: Symbol('gt:module'),
|
||||||
transformer: Symbol('gt:transformer'),
|
transformer: Symbol('gt:transformer'),
|
||||||
|
html: Symbol('gt:html'),
|
||||||
};
|
};
|
||||||
|
|
||||||
export function Provider(opts: { provides: string; needs?: string[]; optional?: 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) => {
|
return (target) => {
|
||||||
const meta: ProviderMeta = { provides: opts.provides, needs: opts.needs ?? [], optional: opts.optional ?? false };
|
const meta: ProviderMeta = {
|
||||||
|
provides: opts.provides,
|
||||||
|
needs: opts.needs ?? [],
|
||||||
|
optional: opts.optional ?? false,
|
||||||
|
export: opts.export ?? false,
|
||||||
|
};
|
||||||
Reflect.defineMetadata(K.provider, meta, target);
|
Reflect.defineMetadata(K.provider, meta, target);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Step(opts: { provides: string; needs?: string[]; optional?: 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) => {
|
return (target) => {
|
||||||
const meta: StepMeta = { provides: opts.provides, needs: opts.needs ?? [], optional: opts.optional ?? false };
|
const meta: StepMeta = {
|
||||||
|
provides: opts.provides,
|
||||||
|
needs: opts.needs ?? [],
|
||||||
|
optional: opts.optional ?? false,
|
||||||
|
export: opts.export ?? false,
|
||||||
|
};
|
||||||
Reflect.defineMetadata(K.step, meta, target);
|
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 {
|
export function Route(prefix: string): ClassDecorator {
|
||||||
return (target) => { Reflect.defineMetadata(K.routePrefix, prefix, target); };
|
return (target) => {
|
||||||
}
|
Reflect.defineMetadata(K.routePrefix, prefix, target);
|
||||||
|
|
||||||
export function Get(path: string): MethodDecorator {
|
|
||||||
return (target, propertyKey) => {
|
|
||||||
const ctor = target.constructor;
|
|
||||||
const routes = (Reflect.getMetadata(K.routes, ctor) as RouteMeta[]) ?? [];
|
|
||||||
routes.push({ method: 'GET', path, handlerName: String(propertyKey) });
|
|
||||||
Reflect.defineMetadata(K.routes, routes, ctor);
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function routeDecorator(method: HttpMethod, transport: Transport) {
|
||||||
|
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,
|
||||||
|
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 `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 `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 {
|
export function Transformer(fn: TransformerFn): MethodDecorator {
|
||||||
return (target, propertyKey) => {
|
return (target, propertyKey) => {
|
||||||
Reflect.defineMetadata(K.transformer, fn, target.constructor, String(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 {
|
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 {
|
export function getProviderMeta(cls: Ctor): ProviderMeta | undefined {
|
||||||
return Reflect.getMetadata(K.provider, cls);
|
return Reflect.getMetadata(K.provider, cls);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Reads the `@Step` metadata off a class, if any. */
|
||||||
export function getStepMeta(cls: Ctor): StepMeta | undefined {
|
export function getStepMeta(cls: Ctor): StepMeta | undefined {
|
||||||
return Reflect.getMetadata(K.step, cls);
|
return Reflect.getMetadata(K.step, cls);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Reads the `@Module` metadata off a class, if any. */
|
||||||
export function getModuleMeta(cls: Ctor): ModuleOptions | undefined {
|
export function getModuleMeta(cls: Ctor): ModuleOptions | undefined {
|
||||||
return Reflect.getMetadata(K.module, cls);
|
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 {
|
export function getTransformer(cls: Ctor, methodName: string): TransformerFn | undefined {
|
||||||
return Reflect.getMetadata(K.transformer, cls, methodName);
|
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[] {
|
export function getRoutes(cls: Ctor): RouteMeta[] {
|
||||||
const prefix: string = Reflect.getMetadata(K.routePrefix, cls) ?? '';
|
const prefix: string = Reflect.getMetadata(K.routePrefix, cls) ?? '';
|
||||||
const routes: RouteMeta[] = Reflect.getMetadata(K.routes, 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 {
|
/** Joins two path segments with exactly one slash, collapsing any duplicates. */
|
||||||
return `${a.replace(/\/$/, '')}/${b.replace(/^\//, '')}`.replace(/\/+/g, '/');
|
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);
|
||||||
|
});
|
||||||
|
}
|
||||||
+120
@@ -0,0 +1,120 @@
|
|||||||
|
import type { ArgSpec } from './params';
|
||||||
|
import type { Transport } from './metadata';
|
||||||
|
|
||||||
|
/** 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' } };
|
||||||
|
|
||||||
|
/** Converts a route pattern to an OpenAPI path template: `/users/:id` → `/users/{id}`, `:rest*` → `{rest}`. */
|
||||||
|
function templatePath(pattern: string): string {
|
||||||
|
const segments = pattern
|
||||||
|
.split('/')
|
||||||
|
.filter(Boolean)
|
||||||
|
.map((seg) => (seg.startsWith(':') ? `{${seg.slice(1).replace(/\*$/, '')}}` : seg));
|
||||||
|
return `/${segments.join('/')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every `:name` (and `:name*`) segment of a pattern becomes a required path parameter. */
|
||||||
|
function pathParams(pattern: string): Parameter[] {
|
||||||
|
return pattern
|
||||||
|
.split('/')
|
||||||
|
.filter((seg) => seg.startsWith(':'))
|
||||||
|
.map((seg) => ({ name: seg.slice(1).replace(/\*$/, ''), in: 'path', required: true, schema: { type: 'string' } }));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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,
|
||||||
|
};
|
||||||
|
}
|
||||||
+79
-24
@@ -1,12 +1,24 @@
|
|||||||
import 'reflect-metadata';
|
import 'reflect-metadata';
|
||||||
import type { Ctor } from './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>;
|
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>;
|
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>;
|
export type Context = Record<string, unknown>;
|
||||||
|
|
||||||
type ArgSource = 'ctx' | 'needs' | 'params' | 'query' | 'body' | 'headers';
|
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');
|
const ARGS = Symbol('gt:args');
|
||||||
|
|
||||||
@@ -21,58 +33,101 @@ function record(target: object, methodKey: string | symbol | undefined, spec: Ar
|
|||||||
}
|
}
|
||||||
|
|
||||||
function envelope(source: ArgSource) {
|
function envelope(source: ArgSource) {
|
||||||
return (arg?: string | string[]): ParameterDecorator =>
|
return (arg?: string | string[] | StandardSchemaV1, schema?: StandardSchemaV1): ParameterDecorator =>
|
||||||
(target, methodKey, index) => {
|
(target, methodKey, index) => {
|
||||||
const spec: ArgSpec = Array.isArray(arg)
|
const spec: ArgSpec = { index, source };
|
||||||
? { index, source, keys: arg }
|
if (Array.isArray(arg)) spec.keys = arg;
|
||||||
: typeof arg === 'string'
|
else if (typeof arg === 'string') spec.key = arg;
|
||||||
? { index, source, key: arg }
|
else if (isStandardSchema(arg)) spec.schema = arg;
|
||||||
: { index, source };
|
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);
|
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');
|
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');
|
export const query = envelope('query');
|
||||||
|
/** Inject the request body; pass a schema to validate it. */
|
||||||
export const body = envelope('body');
|
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');
|
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 {
|
export function needs(key: string): ParameterDecorator {
|
||||||
return (target, methodKey, index) => record(target, methodKey, { index, source: 'needs', key });
|
return (target, methodKey, index) => record(target, methodKey, { index, source: 'needs', key });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Inject the whole request context bag. */
|
||||||
export function ctx(): ParameterDecorator {
|
export function ctx(): ParameterDecorator {
|
||||||
return (target, methodKey, index) => record(target, methodKey, { index, source: 'ctx' });
|
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[] {
|
export function getArgs(cls: Ctor, methodName: string): ArgSpec[] {
|
||||||
const map: Record<string, ArgSpec[]> = Reflect.getMetadata(ARGS, cls) ?? {};
|
const map: Record<string, ArgSpec[]> = Reflect.getMetadata(ARGS, cls) ?? {};
|
||||||
return [...(map[methodName] ?? [])].sort((a, b) => a.index - b.index);
|
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[] {
|
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 [];
|
if (specs.length === 0) return [];
|
||||||
const max = Math.max(...specs.map((s) => s.index));
|
const maxIndex = Math.max(...specs.map((spec) => spec.index));
|
||||||
const args: unknown[] = new Array(max + 1).fill(undefined);
|
const args: unknown[] = new Array(maxIndex + 1).fill(undefined);
|
||||||
for (const s of specs) args[s.index] = resolveOne(s, context);
|
|
||||||
|
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;
|
return args;
|
||||||
}
|
}
|
||||||
|
|
||||||
function resolveOne(s: ArgSpec, context: Context): unknown {
|
function resolveOne(spec: ArgSpec, context: Context): unknown {
|
||||||
if (s.source === 'ctx') return context;
|
if (spec.source === 'ctx') return context;
|
||||||
if (s.source === 'needs') return context[s.key as string];
|
if (spec.source === 'needs') return context[spec.key as string];
|
||||||
const bag = context[s.source];
|
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
|
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>;
|
const values = bag as Record<string, unknown>;
|
||||||
if (s.keys) {
|
|
||||||
const out: Record<string, unknown> = {};
|
if (spec.keys) {
|
||||||
for (const k of s.keys) out[k] = record[k];
|
const picked: Record<string, unknown> = {};
|
||||||
return out;
|
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;
|
||||||
}
|
}
|
||||||
+91
-16
@@ -1,31 +1,106 @@
|
|||||||
import { Bus } from './bus';
|
import { Bus } from './bus';
|
||||||
import { errorToResponse } from './transformers';
|
import { renderError, type ErrorRenderer } from './transformers';
|
||||||
import type { TransformerFn } from './metadata';
|
import { isAsyncIterable } from './channel';
|
||||||
|
import type { TransformerFn, Transport } from './metadata';
|
||||||
|
import { TransportMismatchError } from './signals';
|
||||||
|
|
||||||
export interface PipelineStep { name: string; origin: string; run: (ctx: any) => any }
|
/** A single step in a request pipeline: a named unit whose `run` merges its output into the shared context. */
|
||||||
export interface ResponseShape { status: number; headers: Record<string, string>; body: string }
|
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;
|
||||||
|
|
||||||
|
/** 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: {
|
export async function runPipeline(args: {
|
||||||
steps: PipelineStep[];
|
steps: PipelineStep[];
|
||||||
handler: (ctx: any) => unknown;
|
handler: (ctx: any) => unknown;
|
||||||
transformer: TransformerFn;
|
transformer: TransformerFn;
|
||||||
seed: Record<string, unknown>;
|
seed: Record<string, unknown>;
|
||||||
bus: Bus;
|
bus: Bus;
|
||||||
}): Promise<ResponseShape> {
|
transport: Transport;
|
||||||
const { steps, handler, transformer, seed, bus } = args;
|
onError?: ErrorRenderer;
|
||||||
let ctx: any = { ...seed };
|
}): Promise<PipelineResult> {
|
||||||
|
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 {
|
try {
|
||||||
for (const s of steps) {
|
context = await runSteps(steps, context, bus);
|
||||||
bus.emit('request:step:enter', { name: s.name, scope: s.origin });
|
const result = await handler(context);
|
||||||
const out = await s.run(ctx);
|
const streaming = isAsyncIterable(result);
|
||||||
ctx = { ...ctx, ...out };
|
const contract = TRANSPORT_RETURN[transport];
|
||||||
bus.emit('request:step:leave', { name: s.name, scope: s.origin });
|
|
||||||
|
if (contract === 'buffer' && streaming) {
|
||||||
|
throw new TransportMismatchError(transport, 'stream', context.req as { method?: string; url?: string });
|
||||||
}
|
}
|
||||||
const result = await handler(ctx);
|
|
||||||
const r = transformer(result);
|
if (contract === 'stream' && !streaming) {
|
||||||
return { status: r.status ?? 200, headers: r.headers ?? {}, body: r.body };
|
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) {
|
} catch (error) {
|
||||||
bus.emit('request:step:error', { name: 'pipeline', 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';
|
import { Bus } from './bus';
|
||||||
|
|
||||||
|
/** A step or provider a plugin contributes to the graph. */
|
||||||
export interface ScopeNode {
|
export interface ScopeNode {
|
||||||
kind: 'step' | 'provider';
|
kind: 'step' | 'provider';
|
||||||
name: string;
|
name: string;
|
||||||
@@ -8,10 +9,19 @@ export interface ScopeNode {
|
|||||||
run: (ctx: any) => any;
|
run: (ctx: any) => any;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ScopeApi { add(node: ScopeNode): void }
|
/** The narrow surface a plugin uses to register nodes into the host graph. */
|
||||||
export interface PluginApi { bus: { on: Bus['on'] }; scope: ScopeApi }
|
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;
|
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 {
|
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.
|
// 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 };
|
const api: PluginApi = { bus: { on: bus.on.bind(bus) }, scope };
|
||||||
|
|||||||
@@ -0,0 +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);
|
||||||
|
}
|
||||||
|
|
||||||
|
return hub as unknown as Channel<T>;
|
||||||
|
}
|
||||||
|
/** 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 {
|
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}`);
|
super(message ?? `HTTP ${status}`);
|
||||||
this.name = new.target.name;
|
this.name = new.target.name;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 401 Unauthorized. */
|
||||||
export class Unauthorized extends HttpError {
|
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 {
|
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 {
|
export class NotModified extends HttpError {
|
||||||
constructor() { super(304); }
|
constructor() {
|
||||||
|
super(304);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 302 redirect to `location`. */
|
||||||
export class Redirect extends HttpError {
|
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 {
|
/** 422 raised when request input fails Standard Schema validation. */
|
||||||
return e instanceof HttpError;
|
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/@Post/@Put/@Patch/@Delete) 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 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) => ({
|
export const JsonTransformer: TransformerFn = (value) => ({
|
||||||
status: 200,
|
status: 200,
|
||||||
headers: { 'content-type': 'application/json' },
|
headers: { 'content-type': 'application/json' },
|
||||||
body: JSON.stringify(value),
|
body: JSON.stringify(value),
|
||||||
});
|
});
|
||||||
|
|
||||||
export function errorToResponse(e: unknown): { status: number; headers: Record<string, string>; body: string } {
|
/**
|
||||||
if (isHttpError(e)) {
|
* Map a thrown value to a JSON error response (422 for validation, `HttpError` status, else 500).
|
||||||
const headers: Record<string, string> = { 'content-type': 'application/json' };
|
* An `HttpError` carrying a `body` renders that payload instead of the default `{ error: message }`.
|
||||||
if (e instanceof Redirect) headers.location = e.location;
|
*/
|
||||||
return { status: e.status, headers, body: JSON.stringify({ error: e.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 {
|
return {
|
||||||
status: 500,
|
status: 500,
|
||||||
headers: { 'content-type': 'application/json' },
|
headers: { 'content-type': 'application/json' },
|
||||||
body: JSON.stringify({ error: 'Internal Server Error' }),
|
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);
|
||||||
|
});
|
||||||
|
});
|
||||||
+489
-13
@@ -1,13 +1,17 @@
|
|||||||
import 'reflect-metadata';
|
import 'reflect-metadata';
|
||||||
import { expect, test, vi } from 'vitest';
|
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 { JsonTransformer } from '../src/transformers';
|
||||||
import { Unauthorized } from '../src/signals';
|
import { Unauthorized } from '../src/signals';
|
||||||
import { createApp } from '../src/app';
|
import { createApp } from '../src/app';
|
||||||
import { needs, param, query } from '../src/params';
|
import { needs, param, query, body } from '../src/params';
|
||||||
|
|
||||||
@Provider({ provides: 'db' })
|
@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'] })
|
@Step({ provides: 'user', needs: ['db', 'req'] })
|
||||||
class Auth {
|
class Auth {
|
||||||
@@ -22,7 +26,9 @@ class Auth {
|
|||||||
class UserCtl {
|
class UserCtl {
|
||||||
@Get('/:id')
|
@Get('/:id')
|
||||||
@Transformer(JsonTransformer)
|
@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] })
|
@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']);
|
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 () => {
|
test('a logger plugin observes step:enter without mutating the chain', async () => {
|
||||||
const seen: string[] = [];
|
const seen: string[] = [];
|
||||||
const logger = (api: any) => api.bus.on('request:step:enter', (p: any) => seen.push(p.name));
|
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', () => {
|
test('required provider failure aborts boot', () => {
|
||||||
@Provider({ provides: 'broken' })
|
@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: [] })
|
@Module({ mountpoint: '/x', providers: [Broken], steps: [], controllers: [] })
|
||||||
class BrokenModule {}
|
class BrokenModule {}
|
||||||
|
|
||||||
@@ -65,15 +89,27 @@ test('required provider failure aborts boot', () => {
|
|||||||
test('optional provider failure warns but does not abort boot', async () => {
|
test('optional provider failure warns but does not abort boot', async () => {
|
||||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||||
@Provider({ provides: 'cache', optional: true })
|
@Provider({ provides: 'cache', optional: true })
|
||||||
class FlakyCache { provide() { throw new Error('cache down'); } }
|
class FlakyCache {
|
||||||
|
provide() {
|
||||||
|
throw new Error('cache down');
|
||||||
|
}
|
||||||
|
}
|
||||||
@Route('/ping')
|
@Route('/ping')
|
||||||
class PingCtl { @Get('/') ping() { return { ok: true }; } }
|
class PingCtl {
|
||||||
|
@Get('/') ping() {
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
}
|
||||||
@Module({ mountpoint: '/sys', providers: [FlakyCache], steps: [], controllers: [PingCtl] })
|
@Module({ mountpoint: '/sys', providers: [FlakyCache], steps: [], controllers: [PingCtl] })
|
||||||
class SysModule {}
|
class SysModule {}
|
||||||
|
|
||||||
const app = createApp({ modules: [SysModule] });
|
const app = createApp({ modules: [SysModule] });
|
||||||
const server = await app.listen(0); // must NOT throw
|
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"));
|
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();
|
server.close();
|
||||||
warn.mockRestore();
|
warn.mockRestore();
|
||||||
});
|
});
|
||||||
@@ -82,7 +118,9 @@ test('handler receives @query value through a live request', async () => {
|
|||||||
@Route('/search')
|
@Route('/search')
|
||||||
class SearchCtl {
|
class SearchCtl {
|
||||||
@Get('/')
|
@Get('/')
|
||||||
run(@query('q') q: string) { return { q }; }
|
run(@query('q') q: string) {
|
||||||
|
return { q };
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@Module({ mountpoint: '/s', providers: [], steps: [], controllers: [SearchCtl] })
|
@Module({ mountpoint: '/s', providers: [], steps: [], controllers: [SearchCtl] })
|
||||||
class SearchModule {}
|
class SearchModule {}
|
||||||
@@ -99,11 +137,449 @@ test('boot fails when a handler needs something nothing provides', () => {
|
|||||||
@Route('/things')
|
@Route('/things')
|
||||||
class ThingCtl {
|
class ThingCtl {
|
||||||
@Get('/')
|
@Get('/')
|
||||||
list(@needs('missing') _m: any) { return []; }
|
list(@needs('missing') _m: any) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@Module({ mountpoint: '/t', providers: [], steps: [], controllers: [ThingCtl] })
|
@Module({ mountpoint: '/t', providers: [], steps: [], controllers: [ThingCtl] })
|
||||||
class ThingModule {}
|
class ThingModule {}
|
||||||
|
|
||||||
expect(() => createApp({ modules: [ThingModule] }))
|
expect(() => createApp({ modules: [ThingModule] })).toThrow(/handler 'list' needs 'missing'/);
|
||||||
.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 {}
|
||||||
|
expect(() => createApp({ modules: [M] })).toThrow(/did you mean 'user'\?/);
|
||||||
|
});
|
||||||
|
|
||||||
|
import { Sse, Ws } from '../src/metadata';
|
||||||
|
import { inbound } from '../src/params';
|
||||||
|
import { channel } from '../src/channel';
|
||||||
|
|
||||||
|
describe('app streaming wiring', () => {
|
||||||
|
it('serves an SSE route declared with @Sse', async () => {
|
||||||
|
@Route('/')
|
||||||
|
class Ctl {
|
||||||
|
@Sse('/ticks') ticks() {
|
||||||
|
return (async function* () {
|
||||||
|
yield { t: 1 };
|
||||||
|
yield { t: 2 };
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@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;
|
||||||
|
const res = await fetch(`http://127.0.0.1:${addr.port}/ticks`, { headers: { accept: 'text/event-stream' } });
|
||||||
|
expect(res.headers.get('content-type')).toBe('text/event-stream');
|
||||||
|
const text = await res.text();
|
||||||
|
expect(text).toContain('data: {"t":1}');
|
||||||
|
server.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('serves a @Ws route receiving @inbound and returning a channel', async () => {
|
||||||
|
@Route('/')
|
||||||
|
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();
|
||||||
|
})();
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@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;
|
||||||
|
const WebSocket = (await import('ws')).default;
|
||||||
|
const client = new WebSocket(`ws://127.0.0.1:${addr.port}/echo`);
|
||||||
|
await new Promise((r) => client.on('open', r));
|
||||||
|
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();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
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 };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Route('/')
|
||||||
|
class Ctl {
|
||||||
|
@Get('/needs') needs(@needs('tracked') t: any) {
|
||||||
|
return { t };
|
||||||
|
}
|
||||||
|
@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;
|
||||||
|
|
||||||
|
await fetch(`http://127.0.0.1:${port}/free`).then((r) => r.json());
|
||||||
|
expect(ran).toEqual([]); // step did NOT run for /free
|
||||||
|
await fetch(`http://127.0.0.1:${port}/needs`).then((r) => r.json());
|
||||||
|
expect(ran).toEqual(['tracked']); // step ran for /needs
|
||||||
|
expect(app.inspect('/free').map((l) => l.kind)).toEqual(['handler']); // no step in the chain
|
||||||
|
server.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
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 {};
|
||||||
|
},
|
||||||
|
});
|
||||||
|
@Route('/')
|
||||||
|
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;
|
||||||
|
await fetch(`http://127.0.0.1:${port}/free`).then((r) => r.json());
|
||||||
|
expect(ran).toEqual(['obs']); // ran despite the route @needs-ing nothing
|
||||||
|
server.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
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 {};
|
||||||
|
},
|
||||||
|
});
|
||||||
|
@Step({ provides: 'user', needs: [] })
|
||||||
|
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 {}
|
||||||
|
const app = createApp({ modules: [M], plugins: [observer] });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
const port = (server.address() as any).port;
|
||||||
|
await fetch(`http://127.0.0.1:${port}/free`).then((r) => r.json());
|
||||||
|
expect(seen).toEqual({ id: 'u1' }); // observer got user, not undefined
|
||||||
|
server.close();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
import { Rooms } from '../src/rooms';
|
||||||
|
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 {}
|
||||||
|
const app = createApp({ modules: [M] });
|
||||||
|
const g = app.graph();
|
||||||
|
expect(g.nodes.find((n) => n.name === 'db')).toMatchObject({ kind: 'provider', origin: 'module:M' });
|
||||||
|
expect(g.nodes.find((n) => n.name === 'user')).toMatchObject({ kind: 'step', needs: ['db'] });
|
||||||
|
const route = g.routes.find((r) => r.pattern === '/api/u/:id')!;
|
||||||
|
expect(route.chain).toEqual(['db', 'user', 'get']);
|
||||||
|
expect(app.toMermaid()).toContain('flowchart');
|
||||||
|
});
|
||||||
|
|
||||||
|
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 {}
|
||||||
|
const app = createApp({ modules: [M] });
|
||||||
|
const e = app.explain('/api/u/me');
|
||||||
|
expect(e).toMatchObject({ pattern: '/api/u/me', method: 'GET', transport: 'buffer' });
|
||||||
|
expect(e.chain.map((c) => `${c.kind}:${c.name}`)).toEqual(['step:user', 'handler:me']);
|
||||||
|
expect(e.chain[0]).toMatchObject({ origin: 'module:M', provides: ['user'] });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
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 {}
|
||||||
|
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('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 {}
|
||||||
|
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 {}
|
||||||
|
const app = createApp({ modules: [M] });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
const port = (server.address() as any).port;
|
||||||
|
|
||||||
|
const res = await fetch(`http://127.0.0.1:${port}/ticks`, { headers: { accept: 'text/event-stream' } });
|
||||||
|
const reader = res.body!.getReader();
|
||||||
|
await reader.read(); // first event; stream still open
|
||||||
|
|
||||||
|
await app.close(); // must NOT hang despite the open stream
|
||||||
|
await expect(fetch(`http://127.0.0.1:${port}/ticks`).then((r) => r.text())).rejects.toThrow();
|
||||||
|
reader.cancel().catch(() => {});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
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 {}
|
||||||
|
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 {}
|
||||||
|
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 {}
|
||||||
|
const app = createApp({ modules: [M], overrides: { nope: 1 } });
|
||||||
|
await expect(app.listen(0)).rejects.toThrow(/unknown token 'nope'/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
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 {}
|
||||||
|
const app = createApp({ modules: [M] });
|
||||||
|
const s = await app.listen(0);
|
||||||
|
const port = (s.address() as any).port;
|
||||||
|
expect(await fetch(`http://127.0.0.1:${port}/api/r/x`).then((r) => r.json())).toEqual({ ok: true });
|
||||||
|
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 {}
|
||||||
|
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();
|
||||||
});
|
});
|
||||||
@@ -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,74 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { channel, isAsyncIterable } from '../src/channel';
|
||||||
|
|
||||||
|
const collect = async <T>(it: AsyncIterable<T>, n: number): Promise<T[]> => {
|
||||||
|
const out: T[] = [];
|
||||||
|
for await (const v of it) { out.push(v); if (out.length === n) break; }
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('isAsyncIterable', () => {
|
||||||
|
it('detects async iterables, rejects sync ones', () => {
|
||||||
|
expect(isAsyncIterable(channel())).toBe(true);
|
||||||
|
expect(isAsyncIterable((async function* () {})())).toBe(true);
|
||||||
|
expect(isAsyncIterable('string')).toBe(false);
|
||||||
|
expect(isAsyncIterable([1, 2])).toBe(false);
|
||||||
|
expect(isAsyncIterable(Buffer.from('x'))).toBe(false);
|
||||||
|
expect(isAsyncIterable(null)).toBe(false);
|
||||||
|
expect(isAsyncIterable({})).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('channel', () => {
|
||||||
|
it('fans out the same values to two subscribers', async () => {
|
||||||
|
const ch = channel<number>();
|
||||||
|
const a = collect(ch, 3);
|
||||||
|
const b = collect(ch, 3);
|
||||||
|
await Promise.resolve(); // let both subscribe
|
||||||
|
ch.push(1); ch.push(2); ch.push(3);
|
||||||
|
expect(await a).toEqual([1, 2, 3]);
|
||||||
|
expect(await b).toEqual([1, 2, 3]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('close() ends the for-await', async () => {
|
||||||
|
const ch = channel<number>();
|
||||||
|
const seen: number[] = [];
|
||||||
|
const done = (async () => { for await (const v of ch) seen.push(v); })();
|
||||||
|
await Promise.resolve();
|
||||||
|
ch.push(1); ch.close();
|
||||||
|
await done;
|
||||||
|
expect(seen).toEqual([1]);
|
||||||
|
expect(ch.closed).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fail() throws in the consumer', async () => {
|
||||||
|
const ch = channel<number>();
|
||||||
|
const boom = new Error('boom');
|
||||||
|
const run = (async () => { for await (const _ of ch) { /* */ } })();
|
||||||
|
await Promise.resolve();
|
||||||
|
ch.fail(boom);
|
||||||
|
await expect(run).rejects.toThrow('boom');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('bounded buffer drops oldest for a slow subscriber', async () => {
|
||||||
|
const ch = channel<number>({ buffer: 2 });
|
||||||
|
const it = ch[Symbol.asyncIterator]();
|
||||||
|
await Promise.resolve();
|
||||||
|
ch.push(1); ch.push(2); ch.push(3); // 1 dropped, queue = [2,3]
|
||||||
|
ch.close();
|
||||||
|
expect((await it.next()).value).toBe(2);
|
||||||
|
expect((await it.next()).value).toBe(3);
|
||||||
|
expect((await it.next()).done).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('.return() on one subscriber does not affect the other', async () => {
|
||||||
|
const ch = channel<number>();
|
||||||
|
const a = ch[Symbol.asyncIterator]();
|
||||||
|
const b = ch[Symbol.asyncIterator]();
|
||||||
|
await Promise.resolve();
|
||||||
|
await a.return!(); // a unsubscribes
|
||||||
|
ch.push(7); ch.close();
|
||||||
|
expect((await b.next()).value).toBe(7);
|
||||||
|
expect((await a.next()).done).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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,29 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { sseEncoder, ndjsonEncoder } from '../src/encoders';
|
||||||
|
|
||||||
|
describe('sseEncoder', () => {
|
||||||
|
it('frames data as SSE events', () => {
|
||||||
|
expect(sseEncoder.encode({ a: 1 })).toBe('data: {"a":1}\n\n');
|
||||||
|
});
|
||||||
|
it('frames errors as an SSE error event with only the message', () => {
|
||||||
|
expect(sseEncoder.encodeError(new Error('nope'))).toBe('event: error\ndata: {"error":"nope"}\n\n');
|
||||||
|
});
|
||||||
|
it('sets text/event-stream headers and has a ping', () => {
|
||||||
|
expect(sseEncoder.headers['content-type']).toBe('text/event-stream');
|
||||||
|
expect(typeof sseEncoder.ping).toBe('function');
|
||||||
|
expect(sseEncoder.ping!()).toBe(': ping\n\n');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ndjsonEncoder', () => {
|
||||||
|
it('frames one JSON line per item', () => {
|
||||||
|
expect(ndjsonEncoder.encode({ a: 1 })).toBe('{"a":1}\n');
|
||||||
|
});
|
||||||
|
it('frames errors as a terminal JSON line', () => {
|
||||||
|
expect(ndjsonEncoder.encodeError(new Error('nope'))).toBe('{"error":"nope"}\n');
|
||||||
|
});
|
||||||
|
it('sets ndjson content-type and has no ping', () => {
|
||||||
|
expect(ndjsonEncoder.headers['content-type']).toBe('application/x-ndjson');
|
||||||
|
expect(ndjsonEncoder.ping).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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,25 @@
|
|||||||
|
import { describe, it, expect, afterAll } from 'vitest';
|
||||||
|
import { app } from '../../example/chat';
|
||||||
|
|
||||||
|
let server: any; let port: number;
|
||||||
|
afterAll(() => server?.close());
|
||||||
|
|
||||||
|
describe('chat example', () => {
|
||||||
|
it('two authed clients in a room see each other; missing token is rejected 4401', async () => {
|
||||||
|
server = await app.listen(0); port = (server.address() as any).port;
|
||||||
|
const WebSocket = (await import('ws')).default;
|
||||||
|
|
||||||
|
const a = new WebSocket(`ws://127.0.0.1:${port}/chat/general?token=alice`);
|
||||||
|
const b = new WebSocket(`ws://127.0.0.1:${port}/chat/general?token=bob`);
|
||||||
|
await Promise.all([new Promise((r) => a.on('open', r)), new Promise((r) => b.on('open', r))]);
|
||||||
|
const bGot = new Promise<string>((r) => b.on('message', (d: Buffer) => r(d.toString())));
|
||||||
|
await new Promise((r) => setTimeout(r, 50)); // let server-side open()/subscribe complete (channel has no replay)
|
||||||
|
a.send('hi');
|
||||||
|
expect(await bGot).toContain('hi');
|
||||||
|
a.close(); b.close();
|
||||||
|
|
||||||
|
const noTok = new WebSocket(`ws://127.0.0.1:${port}/chat/general`);
|
||||||
|
const code = await new Promise<number>((r) => noTok.on('close', (c: number) => r(c)));
|
||||||
|
expect(code).toBe(4401);
|
||||||
|
});
|
||||||
|
});
|
||||||
Loaded 100 of 176 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user