Author SHA1 Message Date
chrnxandClaude Opus 5 180de79462 docs: describe the mechanism instead of asserting adjectives
npm shows this line in search results, and "a zen, opinionated, type-safe
framework" is three adjectives a reader cannot verify. Zen is a real claim
here — the framework does the wiring so you write business logic — but it
lands only when the mechanism is visible.

So: state what you declare, and the three things the framework does with it.
Those three are exactly the work it takes off your hands, which is the claim,
demonstrated rather than announced.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-07 14:41:09 -05:00
chrnx 4f504eda11 Merge branch 'develop' into docs/observability-scope-and-analytics
CI / build (pull_request) Successful in 34s
2026-08-07 19:27:37 +00:00
chrnx 94ab334d85 Merge pull request 'chore: clear the dependency advisories blocking CI' (#17) from chore/audit-advisories into develop
CI / build (push) Successful in 33s
Reviewed-on: #17
2026-08-07 19:27:21 +00:00
chrnxandClaude Opus 5 3a8d93320d chore: clear the dependency advisories blocking CI
CI / build (pull_request) Successful in 33s
Both audit trees were failing, for unrelated reasons and with different fixes.

**Root — undici, high.** miniflare 4.20260730.0 (the newest stable) pulls
undici 7.28.0, and the advisory range is 7.0.0–7.28.0. `npm audit fix --force`
wants miniflare 5.20260801.1-alpha: a breaking major, and an alpha, to patch a
devDependency that never ships. undici 7.29.0 is outside the range, so pin it
through `overrides` instead — same approach already used for find-my-way and
hyperid.

**website — js-yaml, high.** Reached through Starlight. 4.3.1 carries the fix
and the bump is not breaking, so a plain `npm audit fix` covers it.

Verified: root and website audits both report 0 vulnerabilities; 357 tests
pass; `test:edge` still passes, which is the one that actually exercises
miniflare against the pinned undici; `docs:build` produces its 23 pages.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-07 14:22:43 -05:00
chrnxandClaude Opus 5 270480b2d6 docs: fix changelog compare links to point at the public mirror
CI / build (pull_request) Failing after 13s
CHANGELOG.md ships inside the npm package, and its link references pointed at
the internal Gitea host — unreachable for anyone reading the changelog on
npmjs. Point them at the GitHub mirror, and compare Unreleased against `main`,
since `develop` is not mirrored.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-07 14:13:54 -05:00
chrnxandClaude Opus 5 27f1d103ea docs(website): add privacy-friendly analytics to the docs site
CI / build (pull_request) Failing after 12s
GoatCounter via Starlight's `head` option, same site code as the marketing
site so /docs traffic lands in one dashboard and referrer paths stay
comparable. No cookies, no personal data, no consent banner, nothing to host.

Answers the one question we cannot answer today: do the articles convert into
documentation reads?

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-07 14:03:39 -05:00
chrnxandClaude Opus 5 0ad53fa284 docs: lead with the problem, document limits, declare the observability gap
The README opened with identity and an install block; the pain that motivates
the graph only appeared after a scroll. Move it up: `req.user` first, then the
idea, then how to install it.

Three fixes while in here:

- The install line now pins `@beta`. `latest` and `beta` both point at the
  newest beta until a stable ships, and the versioning note said the opposite.
- Document `RequestLimits`. Body caps, multipart parts and the request /
  headers / keep-alive timeouts were already applied with defaults tighter
  than Node's, and nothing in the README said so.
- Honest scope now admits there is no observability layer — no logger, no
  metrics, no tracing hooks — and points at the issue tracking it as one
  design. It is the gap a team hits in week one of a real evaluation.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-07 14:03:37 -05:00
chrnx 5fccd3cc8c Merge pull request 'fix(release): validate npm provenance and mutable staging' (#14) from hotfix/npm-release-provenance into develop
CI / build (push) Successful in 33s
Reviewed-on: #14
2026-08-03 03:44:11 +00:00
chrnx 9398a5a2df fix(ci): keep Verdaccio staging mutable
CI / build (pull_request) Successful in 34s
Replace an existing prerelease before publishing the refreshed candidate. Verdaccio remains mutable for validation while npmjs release versions stay immutable.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 22:42:39 -05:00
chrnx 29aafde84c fix(ci): make Verdaccio staging idempotent
CI / build (pull_request) Successful in 32s
Stage only release branches and preserve immutable versions. Repeated identical candidates now exit successfully, while content changes under an existing version require a prerelease bump.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 22:38:56 -05:00
chrnx dbb996dd4c fix(package): declare npm publication metadata
Link the package to its public source, issue tracker, and documentation so npm Trusted Publishing can validate provenance and consumers receive canonical project links.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 22:38:47 -05:00
chrnx f45ee7d309 Merge pull request 'feat: close router and security gaps for 26.8 beta' (#12) from feat/router-security-beta into develop
CI / build (push) Successful in 39s
Reviewed-on: #12
2026-08-03 02:28:13 +00:00
chrnx 00aef4541b Merge branch 'feat/router-security-beta' into develop
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 21:22:10 -05:00
chrnx bd3b2556bc docs: remove design whitespace
CI / build (pull_request) Successful in 56s
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 21:21:13 -05:00
chrnx 87c1226e97 chore(deps): sync deno lockfile
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 21:19:03 -05:00
chrnx 1db4e01e40 fix(deno): snapshot metadata before websocket upgrade
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 21:18:40 -05:00
chrnx 74f09d2e0b docs: document router completeness for beta
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 21:13:59 -05:00
chrnx fcd3df7022 docs(website): align guides with router behavior
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 21:11:08 -05:00
chrnx 934fbd4c19 ci: gate releases on clean dependency audits
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 21:03:54 -05:00
chrnx d9276a4769 docs: expand website documentation audit plan
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 21:01:49 -05:00
chrnx 3a56e656bd chore(deps): remediate security advisories
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 20:56:17 -05:00
chrnx a2acec69bf feat(openapi): document constrained route params
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 20:47:18 -05:00
chrnx 9a61ba8646 feat(http): complete HEAD and OPTIONS semantics
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 20:45:44 -05:00
chrnx 63be0ef8f7 feat(router): expose HEAD and OPTIONS decorators
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 20:40:02 -05:00
chrnx 8e38fffd77 fix(router): reject invalid and ambiguous paths
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 20:39:09 -05:00
chrnx 790db661e5 feat(router): compile safe constrained patterns
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 20:36:46 -05:00
chrnx 63a61aeb0b docs: plan router security beta implementation
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 20:34:03 -05:00
chrnx e343ae501f docs: design router security beta
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 20:28:11 -05:00
chrnx e0212d14e5 Merge pull request 'docs: refresh README + docs, host at /docs on expressive-tea.io' (#10) from docs/readme-refresh into develop
CI / build (push) Successful in 29s
CI / build (pull_request) Successful in 23s
2026-07-18 21:08:35 +00:00
chrnx ab6b1b1ef2 Merge pull request 'ci: npmjs Trusted Publishing (OIDC, no token)' (#8) from ci/trusted-publishing into develop
CI / build (push) Successful in 29s
CI / build (pull_request) Successful in 24s
2026-07-18 20:17:41 +00:00
chrnx 1a313c21ad ci: publish prereleases under their channel dist-tag, not latest
CI / build (pull_request) Successful in 24s
A beta/alpha/rc version must not become 'latest' on npmjs (else npm install serves a prerelease). Derive the dist-tag from the version: 26.7.0-beta.0 -> beta, stable -> latest.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-18 14:59:48 -05:00
chrnx 3ff90b418d ci: publish to npmjs via OIDC Trusted Publishing (no token)
CI / build (pull_request) Successful in 23s
Replaces the NPM_AUTH secret on the prod path with npm Trusted Publishing: id-token: write + npm>=11.5.1, npm exchanges the OIDC token for a short-lived publish token and attaches provenance. Requires a trusted publisher configured on npmjs (Expressive-Tea/green-tea, release.yml).

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-18 14:53:28 -05:00
chrnx 8e822cad17 Merge pull request 'fix(ci): unpublish before publish to Verdaccio' (#6) from fix/stage-unpublish into develop
CI / build (push) Successful in 24s
CI / build (pull_request) Successful in 24s
2026-07-18 19:08:56 +00:00
chrnx 3fe0016dbd fix(ci): unpublish before publish to Verdaccio (registry rejects overwrite)
CI / build (pull_request) Successful in 24s
The staging registry (npm.svc.zoit.services) does not allow overwriting an existing version, so re-publishing the same prerelease on each main merge failed. Unpublish the version first (tolerant --force, no-op when absent) then publish fresh.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-18 14:08:39 -05:00
chrnx 8bd2a3f61c Merge pull request 'ci: stage/promote/release workflows (two-forge pipeline)' (#4) from feat/ci-publish-workflows into develop
CI / build (push) Successful in 24s
CI / build (pull_request) Successful in 32s
2026-07-18 02:18:28 +00:00
chrnx 96d863d402 ci: use the NPM_AUTH secret for both Verdaccio and npmjs publishes
CI / build (pull_request) Successful in 24s
One secret name across forges: Gitea's NPM_AUTH (org-level) = the Verdaccio token for staging; GitHub's NPM_AUTH = the npmjs token for production. Each forge supplies its own value.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 21:17:17 -05:00
chrnx 33df70730b ci: add stage/promote/release workflows for the two-forge pipeline
CI / build (pull_request) Successful in 23s
stage.yml (Gitea-only): publish package to Verdaccio under 'stg' tag on main merge. promote.yml (Gitea-only): mirror only main + version tags to GitHub. release.yml (GitHub-only): publish stable to npmjs on a v* tag. Forge is detected via github.server_url; secrets: VERDACCIO_TOKEN (Gitea), GH_PROMOTE_TOKEN (Gitea, set), NPM_TOKEN (GitHub, pending).

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 20:43:43 -05:00
chrnx 5fc37a2df7 Merge pull request 'ci: relocate workflow to .github/workflows (two-forge compat)' (#3) from chore/ci-two-forge into develop
CI / build (push) Successful in 23s
2026-07-18 01:42:52 +00:00
chrnx 2a84331022 ci: relocate CI workflow to .github/workflows for two-forge compatibility
CI / build (pull_request) Successful in 24s
GitHub Actions only reads .github/workflows; Gitea reads both. Relocating (content unchanged) makes the one gate portable across both forges — the foundation for the Gitea(stg)+GitHub(prod) pipeline.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 20:36:36 -05:00
chrnx 91fe8f8aff Merge pull request 'Deep graphs: O(n²) → O(n), plus a boot warning when they're suspiciously deep' (#2) from fix/pipeline-context-on2 into develop
CI / build (push) Successful in 25s
2026-07-18 00:35:28 +00:00
chrnx 3a4cd5a7ce test(bench): reach bench servers cross-host + add scale and Bun/Deno servers
CI / build (pull_request) Successful in 59s
Fastify and the Nest adapters bound 127.0.0.1, unreachable from a separate load generator; bind 0.0.0.0 so two-machine benchmarks work.

Adds scale-{green-tea,express} (step-vs-middleware depth sweeps that surfaced the O(n^2)) and green-tea-{bun,deno} (the same app served via serveBun/serveDeno, to benchmark across runtimes).

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 19:05:52 -05:00
chrnx 642ef109b2 feat(app): warn at boot when a route's dependency chain is unusually deep
A route whose need-closure resolves to more than 20 steps is almost always a modeling smell -- a step doing too much, or work that belongs in a provider. Per-request cost is linear, so this is a design nudge, not a perf guard (and a warning, not an error).

Tunable and silenceable via createApp({ warnGraphDepth }): a number sets the threshold, false quiets it. Default 20.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 16:25:31 -05:00
chrnx 4081106813 perf(pipeline): merge step output in place to drop the O(n^2) context copy
runSteps rebuilt the whole request context every step with { ...context, ...output }, so an N-step route paid 1+2+...+N = O(N^2) property copies plus N throwaway objects. At 100 chained steps that measured ~250us/req vs ~100us after the fix (2.5x throughput); per-step cost drops from superlinear to a flat ~0.5us/step.

Mutate one accumulator in place with Object.assign -- O(N). The returned context is now the same object every step observes. Adds a regression guard that fails if a per-step copy is reintroduced; full suite green (322 tests).

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 15:50:59 -05:00
chrnx b72883c2ed docs(runtimes): scope the parity claim to what the suite actually tests
CI / build (pull_request) Successful in 33s
The parity suite compares Node's listener against app.fetch inside Node
('Node is truth') — it does not exercise all four runtimes. Saying 'every
runtime ... enforced by a parity test suite' overstates it; the honest
version is that the others share the same app.fetch/app.upgrade core and
each has its own smoke tests. Also fixed the line crediting Node's
WebSocket support to serveDeno/serveBun — Node does it through listen().

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 10:27:36 -05:00
chrnx 489aa685bb docs: host the docs at green-tea.expressive-tea.io/docs
The site hangs off the expressive-tea.io cPanel as green-tea.expressive-tea.io.
A four-level docs.green-tea.expressive-tea.io subdomain reads badly and would
need its own AutoSSL cert (the *.expressive-tea.io wildcard stops one level
up). A /docs subfolder needs no extra host, DNS, or cert — it's a path — and
is what most projects do.

So the docs site now builds with base: '/docs' (its dist/ contents drop into
the subdomain's docs/ folder in cPanel), the 77 hard-coded content links are
prefixed, and the two hero actions Starlight doesn't rewrite are fixed by
hand. Verified: /docs/ serves, / 404s, no unprefixed internal href remains.
README points at the new docs URL.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 10:13:10 -05:00
chrnx c12be9a2f5 docs(site): document matcha, stop contradicting the transport rule, drop Node-only
The streaming guide argued with itself: the table said a plain return
streams by Accept while the section below it, added with the
explicit-transport change, said that same return is a 500. The prose got
swept, the table didn't.

Getting started said green-tea targets Node — true when written, wrong
since the Deno/Bun/edge adapters landed — and led with a manual install
even though matcha scaffolds a live app in two commands. matcha had no
page at all, so the CLI was invisible to anyone reading the docs.

site: pointed at green-tea.dev, which is the marketing site's domain; the
docs deploy to docs.green-tea.dev.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 09:29:04 -05:00
chrnx 0541464093 docs(readme): tell the truth about runtimes, transport, and where the docs live
The README claimed green-tea was Node-only with Deno/Bun/edge "on the
roadmap, not built" — all four have shipped. It also taught that a plain
return of an AsyncIterable streams by Accept, which the explicit-transport
change turned into a 500 TransportMismatchError: the one thing a README
must never do is document behavior that now throws.

docs/ had been frozen since the Starlight site replaced it; nothing but
the README referenced those two files, so they were a second copy to keep
in sync and had already drifted. Point at the site instead.

Also adds what shipped unmentioned (@Html/views/static, the four runtimes,
matcha) and fixes the CHANGELOG's YY.MM.PATCH, which contradicted the
README's correct explanation of why the month is not zero-padded.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 09:14:13 -05:00
chrnx 502b2c6b72 Merge branch 'feature/mesh-link-health' into develop
CI / build (push) Successful in 1m2s
Link health for mesh: say what is actually wrong, and notice it without waiting
for a user to find out.

Writing the tests for the status codes turned up three bugs. A teapot with a live
control channel could never shut down — control connections were the one kind of
long-lived socket nobody registered for force-close, so server.close() waited on
a teacup that had no reason to hang up. A downed teapot answered 500 after a full
30s timeout, having queued the frame on a closed socket to wait out a verdict
already known; it now answers 503 at once, and a live-but-slow teapot answers 504.
And the heartbeat's first close code, 1011, silently did nothing: a client may
only send 1000 or 3000-4999, so it threw `invalid code` into a catch that swallows
throws, leaving the link open while looking closed.

Ping/pong are mesh frames, not WebSocket protocol pings, because Deno's and Bun's
platform WebSocket does not expose ws.ping(). They land in v1 while the wire has
no deployed peers to break.

Reconnect, and reconciling app-scope values that outlive their teapot from cache,
stay out — post-beta, on their own spec.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 23:54:21 -05:00
chrnx dba40b0c8b feat(mesh): heartbeat the link, and tell the truth when a teapot is gone
Three bugs, found by writing the tests for the status codes.

A teapot with a live control channel could never shut down. Control connections
were never registered with the stream registry, so server.close() sat waiting on
a connected teacup that had no reason to hang up, and app.close() never resolved.
Every other long-lived socket was already tracked; the control channel was the
one that skipped it.

A downed teapot answered 500 — after 30 seconds. sendRpc queued the frame on a
closed socket and waited out the full timeout for a verdict already known. It now
rejects immediately with 503: 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. An RPC
that times out on a *live* link is 504 — a slow teapot and a gone one are
different stories.

Heartbeat: each teacup pings its teapots (`mesh.heartbeatMs`, default 15s) and
closes a link after two unanswered rounds. This is what catches a half-open
connection, where the socket looks open with nobody home — otherwise a teacup only
learns on the next request. Ping/pong are mesh frames rather than WebSocket
protocol pings because Deno's and Bun's platform WebSocket does not expose
ws.ping(), so a protocol-level heartbeat could not work everywhere mesh runs.
Added to v1 while the wire still has no deployed peers; later it would be a
version bump that refuses every old peer.

The heartbeat's first close code was 1011, which silently did nothing: a *client*
may only send 1000 or 3000-4999, so it threw `invalid code` — and our neutral
close swallows throws, so the link stayed open while looking closed. 4011 mirrors
1011's meaning inside the application range.

Reconnect (and reconciling app-scope values, which survive their teapot from
cache) stays out — it is a post-beta spec of its own.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 23:32:45 -05:00
chrnx 5e7d952f45 Merge branch 'refactor/solid-cleanup' into develop
A SOLID audit that turned into making mesh work off Node.

The audit found the repo already sound on DIP/ISP, and most candidate findings
did not survive verification. Five real ones did, and fixing the observability
gap exposed the rest: steps were run by three hand-rolled loops, only one of
which emitted request:step:enter/leave, so a logging plugin silently saw nothing
on @Ws routes.

Pulling that thread reached mesh, which was Node-only by construction rather
than by decision: only listen() finalized a mesh graph, and listen() builds a
Node http.Server, so app.fetch — the entry Deno/Bun/edge use — threw forever and
told operators to call something they could not call. Mesh now runs on Node, Deno
and Bun, teapot and teacup, in any combination, proven by cross-process interop
tests rather than reasoned about.

Wire protocol is versioned before it has peers to break; duplicate exported
routes fail the boot rather than silently shadowing, since there is no load
balancing to fall back on; local-over-remote precedence now warns instead of
being an accident of merge order; app.ready() resolves the graph without booting
providers, so one protocol works against mesh and non-mesh apps alike.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 23:14:26 -05:00
chrnx 9886e53747 feat(app): add app.ready() so introspection works on any app
inspect()/graph()/explain() are synchronous, but a mesh graph is not knowable
until its teapots have been asked, so on a mesh app they threw and the caller had
no way to fix it. Code holding an `App` could not tell which kind it had — the
Liskov complaint from the audit, and the last of it: fetch/upgrade stopped
throwing when the boot moved into the gate.

app.ready() resolves the graph and returns. On a mesh app it connects the
teapots; on every other app it is a no-op. So one shape works for both:

    await app.ready();
    app.graph();

which is what actually restores substitutability — a uniform protocol, not a type
that describes the asymmetry.

Deliberately not a full boot: it does not run provider factories. Resolving the
graph and being ready to serve are different things, and a devtool drawing a
diagram should not open your database connections. Serving boots them too and
shares the same memoized step, so ready() then fetch() resolves the graph once.

The guards stay — sync code cannot await network I/O — but the message names the
fix instead of describing the trap.

createApp hit 26 on the complexity gate with ready() added. Both boot stages had
their own copy of the same memoisation, so it collapses into one `once` helper
used by both, which is a smaller createApp than before this change.

Refs .specs/2026-07-15-green-tea-solid-audit (App/Mesh LSP)

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 23:00:14 -05:00
chrnx 34dbb32b2c docs(mesh): warn on shadowed remote routes, and tell the truth about mesh
Local routes are merged ahead of remote ones, so a local twin wins. That
precedence is worth keeping — your own code beating an imported one is how you
override a teapot — but it was an accident of [...local, ...remote] ordering with
nothing said, so a shadowed export looked like a broken teapot from the outside.
Warn, name the teapot, and leave the call to the developer.

The docs had gone stale in the way that started all of this. runtimes.md claimed
four times that mesh is Node-only; the mesh guide said finalization is deferred to
listen(); the changelog said "WebSocket and mesh remain Node-only". All false now.

The mesh guide gains what was enforced but never written down — which is how the
listen() trap got made in the first place, when the previous plan's "document it"
never landed:
- runs on Node/Deno/Bun, teapot and teacup, any combination; not on edge, and why
- no listen() required: the graph boots on first use
- buffered routes only, and why streams cannot cross an RPC hop
- one teapot per route, local-over-remote precedence, and the protocol version

Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 9

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 16:20:55 -05:00
chrnx 033af2d1fc fix(mesh): fail the boot when two teapots export the same route
Duplicate scope tokens already threw in setRunner, but duplicate routes did not:
both were pushed into remoteRoutes, and matchRoute keeps the first of two
identical patterns (moreSpecific returns 0, not > 0). The second teapot's route
was silently dead. Same collision, two behaviours — one loud, one mute.

Fail the boot instead, naming the route and both teapots, since which pair
clashed is the thing an operator needs. The message says load balancing is not
implemented *yet*: it is a not-yet, not an impossibility.

Throwing now also keeps the door open. "First teapot wins" is a semantic callers
could come to rely on, so shipping it would make balancing a breaking change
later. An error cannot be relied on — turning it into a strategy stays additive.

Scopes keep failing rather than balancing, and should: an app-scope provider is
memoised, so "balancing" a cached value means nothing.

Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 16:04:57 -05:00
chrnx a74417494f test(mesh): prove mesh across Node, Deno and Bun
Every mesh test ran on Node and drove listen(); nothing off Node was covered, so
the cross-runtime work was implemented but not demonstrated. vitest excludes
test/{deno,bun,edge}, so `npm test` would not have noticed either way.

Adds, in the real runtimes:
- Deno and Bun, teapot and teacup, served through serveDeno/serveBun. Bun is not a
  duplicate of Deno: its socket events land on a server-level handler, so the
  control channel reaches app.upgrade by a different path.
- The interop matrix, in separate processes: a Deno teacup consuming a Node teapot
  and a Node teacup consuming a Deno teapot. Each asserts the `runtime` field the
  *other* process produces, so a peer answering from the wrong side fails the test.
  Node serves and connects with the `ws` package; Deno uses its global WebSocket —
  same-runtime tests could never have exercised that pairing.
- A hand-rolled v999 peer, refused across the boundary with both versions named.

Verified these tests fail for the right reason: breaking the control-channel
routing in app.upgrade fails the Node-teacup-consumes-Deno-teapot case and only
that case.

test:deno needs --allow-run/--allow-env to spawn the Node peer. The peer lives in
test/interop rather than test/deno because tsconfig excludes test/deno, so tsx
would not apply experimentalDecorators there; vitest ignores it as a non-.test.ts.

Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 8

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 15:30:43 -05:00
chrnx 0c68cba532 feat(mesh): mount the control channel on app.upgrade, and close links without a server
Two halves of the same "mesh off Node" gap; they touch the same file and landed
together.

Control channel (Task 6): meshControl existed only inside listen(), passed to
createHttpServer, so a teapot could only export its scopes from Node. app.upgrade
— the path serveDeno/serveBun drive — had never heard of it, which would have left
"mesh on three runtimes" meaning consume-only. It is now built in the boot gate
(it captures the finalized ordered nodes, so it cannot exist before finalize) and
the reserved path is routed from app.upgrade. Task 3 already made handle() take a
neutral WsSocket and upgrade holds one, so this is a direct call, not a second
implementation. handle() returns the connection's lifetime like runWsConnection,
so upgrade awaits it instead of returning while the peer is still talking. An app
with nothing exported refuses the reserved path explicitly rather than falling
through to "no matching ws route".

Link lifecycle (Task 7): links were reaped by server.on('close'), reachable only
through listen(), so a mesh app booted through app.fetch had links and no server
and leaked every teapot connection at `if (!server) return`. close() now closes
them first either way; that aborts each socket, which rejects its in-flight RPCs.

Also fixes a race the new tests exposed: upgrade awaited the boot *before* handing
the socket to a consumer, but `channel` is fan-out, so frames arriving during the
boot were dropped with no subscriber attached. For the control channel that is
`hello` itself — against a teapot with slow providers the handshake would hang
until timeout. Inbound is now subscribed synchronously on entry and the buffered
iterator handed down, closing the same gap for regular @Ws routes.

Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Tasks 6, 7

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 15:13:20 -05:00
chrnx db9a7712af feat(mesh): boot the mesh graph from the app boot gate, not listen()
Only listen() spliced remote scopes and finalized the graph, and listen() builds
a Node http.Server. Deno/Bun/edge serve through app.fetch and can never call it,
so mesh was Node-only by construction: fetch() threw "unavailable before
listen()" forever on those runtimes, telling operators to call something they
had no way to call. buildAppFetch also hardcoded remoteRoutes to [], so even past
the guard it would not have served a remote route.

Move splice+finalize into the memoized boot gate that fetch, upgrade and listen
already share, ahead of the providers — remote nodes must join before the topo
sort. Await it before building the route table rather than after, since for a
mesh app the table is not knowable until the splice has run. listen() keeps
working by awaiting the same gate; the memoization means a fetch followed by a
listen boots once, and concurrent first requests splice once.

The fetch/upgrade guards are gone rather than reworded: they are now unreachable.

inspect()/graph()/explain() keep theirs — they are synchronous and cannot await
network I/O — but their message no longer claims listen() is the only way in.

test/fetch.test.ts asserted the old contract (fetch throws until listen), i.e.
the trap itself; it now pins that a mesh app serves without listen() and that
listen() afterwards does not re-run provider factories.

Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 5

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 15:04:49 -05:00
chrnx 0ea4db3fef feat(mesh): connect the teacup over a runtime-neutral WebSocket client
connectLink constructed `require('ws')` directly and drove its EventEmitter API,
which is why a teacup could only run on Node. It now goes through the neutral
WsSocket like every other consumer, over whichever client the runtime provides:
the platform global (Deno, Bun, Node >= 22) or the `ws` peer for Node 18-21,
which has no global. `ws` stays optional and is only reached for when the global
is absent.

One bridge covers both because `ws` also implements the browser-compatible event
API and delivers text frames as `event.data` strings — probed against the real
package rather than taken on faith.

Both implementations are exercised in one run: `ws` is always in the matrix, so
the Node 18-21 path cannot rot unseen on CI that only runs a modern Node, which
is how a fallback quietly stops working. connectLink takes an optional Ctor to
make that possible; it doubles as a bring-your-own-WebSocket hook for runtimes
we do not ship an adapter for.

Verified the edge bundle is unaffected: `require('ws')` tree-shakes out of the
workerd build entirely.

Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 4

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 15:00:04 -05:00
chrnx 71b59e7c25 refactor(mesh): serve the control channel over the neutral WsSocket
The mesh control channel was the last consumer speaking the `ws` EventEmitter
API directly: http/ws.ts handed meshControl.handle a raw socket, while every
@Ws route already went through nodeSocket() to get a neutral WsSocket. Mesh did
not lack an abstraction — it skipped the one the codebase already had.

handle() now takes a WsSocket and consumes `inbound`, so both feeds work: Node
via the existing nodeSocket, and Deno/Bun via app.upgrade, where the socket is
already neutral. That is what unblocks mounting the control channel off Node.

RPCs are still dispatched without awaiting. The old `ws.on('message')` listener
overlapped them, and the peer's id-keyed pending map exists for exactly that —
awaiting inside the receive loop would have silently serialized every mesh call.
A test now pins the overlap.

The unused `http` import in http/types.ts fell out with MeshControl's req
parameter: nothing in that module is Node-shaped any more.

Node behaviour is unchanged — the teapot↔teacup integration tests pass
untouched. teapot.test.ts drives handle() directly, so its fake moved from a raw
EventEmitter to a fake WsSocket.

Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 3

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 14:53:09 -05:00
chrnx 87772868ab refactor(mesh): import node:crypto explicitly in the teapot
safeEqual guards the mesh shared secret and reached for Buffer + timingSafeEqual
through a bare 'crypto' specifier, leaving resolution to Deno/Bun node-compat
heuristics. Name the builtin explicitly — the authentication path should not
depend on which compat layer happens to answer.

Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 2

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 14:53:07 -05:00
chrnx dd0ea91a1b feat(mesh): version the wire protocol and validate frame shapes
Cross-runtime mesh means peers are separate processes on separate deploy
cadences, so the frame union is a contract between green-tea versions rather
than an internal detail. There was no version field, and decode validated only
that `type` was a known tag before casting `parsed as Frame` — every other
field was trusted, so a skewed or malformed peer failed somewhere downstream
instead of at the boundary.

Add MESH_PROTOCOL_VERSION to the hello/manifest frames. Both ends refuse a
mismatch: the teapot checks the version *before* the secret, since a skewed
peer is not an auth failure and "wrong secret" would send its operator hunting
the wrong bug.

Validate fields per frame type via a Record keyed on the type tag, so a new
frame type must add a row. The lookup uses an own-property check: `type` is
peer-controlled and a bare lookup would resolve SHAPE['constructor'] up the
prototype chain to a truthy non-check.

This is a breaking wire change, done now because it is free exactly once —
mesh is alpha behind experimental:true and has no deployed peers. Adding a
version later would break every peer already in the field.

Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 1

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 14:47:35 -05:00
chrnx d56eeafcd8 refactor: close type holes on the transport and error axes
- OpenApiRoute.transport was typed `string`, so the compiler could not check the
  transport branching at all. Type it Transport and key the documented 200 off a
  Record, so a new transport fails the build instead of silently going undocumented.
- pickEncoder fell through to ndjson for unknown transports; make the mapping
  exhaustive so a new transport cannot inherit the wrong wire format by accident.
- HttpError carries optional headers, removing the instanceof Redirect special case
  that coupled the error renderer to one subclass. Custom errors needing headers
  (retry-after, etag) no longer require touching transformers.
- Drop the module-global connSeq in mesh/link: `pending` is already per-connection,
  so a per-link counter suffices and connection ids stop depending on test order.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 14:37:03 -05:00
chrnx 9421b102d9 refactor(adapters): share ws plumbing across bun/deno/edge
toWsRequest, the neutral-socket wrapper and the upgrade error guard were
copy-pasted across all three runtime adapters, comments included. A change to
the upgrade close code meant remembering to touch three files.

Extract the shared parts to http/ws-adapter (kept separate from ws-core: that
module runs a connection, this one builds one from a host runtime's socket).
Bun keeps its own socket wrapper — its events land on a server-level handler
rather than the socket, so the lifecycle genuinely differs.

Verified against real runtimes: deno test, bun test, workerd via miniflare.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 14:37:03 -05:00
chrnx 922700674c fix(bus): emit step events for ws and mesh routes
Steps were executed by three separate hand-rolled loops: runPipeline (HTTP),
buildWsRoutes (ws) and resolveScope (mesh). Only the HTTP one emitted
request:step:enter/leave, so a logging plugin silently observed nothing on ws
routes — a gap in a documented public API, not just redundancy.

Route every transport through a single runSteps() so observability is uniform
by construction rather than by remembering to copy the emit calls.

Also fixes the plugins guide, which documented a request:step:exit event that
has never existed (the bus emits request:step:leave).

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 14:37:03 -05:00
96 changed files with 6145 additions and 2698 deletions

No files matched your search

@@ -13,9 +13,16 @@ jobs:
with: with:
node-version: '18' node-version: '18'
- run: npm ci - run: npm ci
- run: npm audit
- run: npm run lint - run: npm run lint
- run: npm run format:check - run: npm run format:check
- run: npm run complexity:check - run: npm run complexity:check
- run: npm run typecheck - run: npm run typecheck
- run: npm test - run: npm test
- run: npm run build - run: npm run build
- uses: actions/setup-node@v4
with:
node-version: '22.12'
- run: npm ci --prefix website
- run: npm audit --prefix website
- run: npm run docs:build
+30
View File
@@ -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
+35
View File
@@ -0,0 +1,35 @@
name: Release → npmjs
# Production publish. Runs on GITHUB ONLY, on a version tag (`v*`). Publishes the stable
# package to npmjs via OIDC **Trusted Publishing** — no long-lived token. Requires a trusted
# publisher configured on npmjs for this package (org Expressive-Tea, repo green-tea,
# workflow release.yml). npm also attaches build provenance automatically.
on:
push:
tags: ['v*']
jobs:
publish-prod:
if: ${{ github.server_url == 'https://github.com' }}
runs-on: ubuntu-latest
permissions:
id-token: write # OIDC for Trusted Publishing (also enables provenance)
contents: read
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
registry-url: 'https://registry.npmjs.org'
- run: npm install -g npm@latest # npm >= 11.5.1 is required for OIDC trusted publishing
- run: npm ci
- run: npm audit
# `npm publish` runs prepublishOnly (lint + complexity + typecheck + test + build) first.
# No NODE_AUTH_TOKEN — npm exchanges the OIDC id-token for a short-lived publish token.
# A prerelease (26.7.0-beta.N) publishes under its channel tag (beta/alpha/rc) so `latest`
# never points at a beta; a stable version publishes under `latest`.
- name: Publish
run: |
TAG=$(node -e "const v=require('./package.json').version;const m=v.match(/-([a-z]+)/);console.log(m?m[1]:'latest')")
echo "dist-tag: $TAG"
npm publish --access public --tag "$TAG"
+35
View File
@@ -0,0 +1,35 @@
name: Stage → Verdaccio
# Staging publish. Runs on GITEA ONLY (the `if` guards against GitHub) for release
# branches. Publishes prereleases to the internal Verdaccio under the `stg` dist-tag.
# Staging versions are intentionally mutable: an existing prerelease is removed before
# publishing the updated release candidate under the same version.
on:
push:
branches: ['release/**']
jobs:
publish-stg:
if: ${{ github.server_url != 'https://github.com' }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
- run: npm ci
- run: npm audit
- name: Validate release candidate
run: npm run prepublishOnly
- name: Publish prerelease to Verdaccio
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_AUTH }}
run: |
npm config set //npm.svc.zoit.services/:_authToken "$NODE_AUTH_TOKEN"
VER=$(node -p "require('./package.json').version")
case "$VER" in
*-*) ;;
*) echo "Refusing to stage non-prerelease version: $VER" >&2; exit 1 ;;
esac
npm unpublish "@green-tea/core@$VER" --registry https://npm.svc.zoit.services --force 2>/dev/null || true
npm publish --ignore-scripts --registry https://npm.svc.zoit.services --tag stg
+76 -9
View File
@@ -3,29 +3,94 @@
All notable changes to `@green-tea/core` are documented here. All notable changes to `@green-tea/core` are documented here.
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
green-tea uses calendar versioning: `YY.MM.PATCH`. green-tea uses calendar versioning: `YY.M.PATCH` — the month is not zero-padded, since
npm treats versions as semver and semver forbids leading zeros.
## [Unreleased] ## [Unreleased]
## [26.8.0-beta.0] - 2026-08-02
### Added ### Added
- **Safe constrained route parameters:** patterns such as `:id(\d+)` match a complete decoded
segment. The parser accepts a deliberately small, bounded regex subset and rejects unsafe or
malformed expressions at boot. Specificity is now static ▸ constrained param ▸ plain param ▸
catch-all; matching remains a linear scan.
- **`@Head` and `@Options` route decorators**, explicit-handler priority, buffered-GET HEAD fallback,
and automatic `204` OPTIONS responses with deterministic `Allow` ordering. GET implies HEAD and
every existing path implies OPTIONS; streaming GET routes do not become implicit HEAD routes.
- **OpenAPI route constraints and methods:** constrained path params emit `schema.pattern`, and
explicitly declared HEAD/OPTIONS handlers appear as operations without inventing automatic ones.
- **HTML / views:** `@Html` decorator (string, file, and template modes), a zero-dep built-in - **HTML / views:** `@Html` decorator (string, file, and template modes), a zero-dep built-in
template engine (`{{ }}` escaped / `{{{ }}}` raw, exported as `render`) with a `viewEngine` template engine (`{{ }}` escaped / `{{{ }}}` raw, exported as `render`) with a `viewEngine`
bring-your-own hook, and zero-config `static` directory serving (`createApp({ static: true })`). bring-your-own hook, and zero-config `static` directory serving (`createApp({ static: true })`).
File and static serving require a filesystem (Node/Deno/Bun); string-mode `@Html` runs everywhere. 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 - **`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 same app runs HTTP and SSE on Deno/Bun/edge runtimes via the Fetch API.
(WebSocket and mesh remain Node-only).
- **Deno adapter** (`@green-tea/core/deno`): `serveDeno(app)` runs HTTP + SSE + WebSocket on Deno. - **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. - **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. - **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`). - **`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 ### Fixed
- The Deno WebSocket adapter snapshots request and connection metadata before accepting an upgrade;
Deno 2.9 invalidates that metadata once upgraded, which previously broke WebSocket and mesh boots.
- Repeated slashes and malformed path encoding now return `400` consistently across Node and Fetch
adapters, retaining configured security/CORS headers. `/path` and `/path/` remain equivalent.
- Ambiguous same-method route shapes now fail at boot with both declarations named. Effective-shape
checks also cover remote mesh conflicts and local routes that shadow a remote export.
- HEAD responses always suppress the body while preserving handler status and headers; Fetch
responses also avoid constructing forbidden bodies for `204`, `205`, and `304` statuses.
- The opt-in dev routes `/__graph__` (graph viewer) and `/__openapi__` are now - The opt-in dev routes `/__graph__` (graph viewer) and `/__openapi__` are now
served over `app.fetch` too, so they work on every runtime (Deno/Bun/edge), served over `app.fetch` too, so they work on every runtime (Deno/Bun/edge),
not only the Node `app.listen()` path. not only the Node `app.listen()` path.
- **A teapot with a live control channel could never shut down.** Mesh control connections were
not registered with the stream registry, so `server.close()` waited on a connected teacup that
had no reason to hang up, and `app.close()` never resolved.
- **A downed teapot now answers 503 immediately** instead of hanging for the full `timeoutMs`
(30s by default) and then answering 500. A closed socket cannot deliver the frame, so the wait
bought nothing. An RPC that times out on a live link is now 504, not 500 — a dead upstream and
a slow one are different operational stories, and neither is "this service broke".
- **`request:step:enter`/`leave` are now emitted for `@Ws` and mesh routes.** Only HTTP routes
emitted them, so a logging plugin silently observed nothing on a WebSocket route — a gap in a
documented plugin API. All transports now run their steps through one path.
- **A mesh route exported by two teapots now fails the boot**, naming both effective patterns and
both teapots, instead of silently serving whichever connected first and leaving the other dead.
There is no load balancing to fall back on, so green-tea will not pick for you.
- **A local route shadowing a remote one now warns.** Local still takes precedence — that is how you
override a teapot — but a silently shadowed export used to look like a broken teapot.
- **`app.close()` closes mesh links even with no server**, so a mesh app booted through `app.fetch`
(every Deno/Bun deployment) no longer leaks its teapot connections.
- **WebSocket frames arriving during boot are no longer dropped.** `app.upgrade` awaited the boot
before handing the socket to a consumer, and the inbound channel is fan-out, so a peer that spoke
first lost those frames — for mesh, that was the handshake itself.
- The plugins guide documented a `request:step:exit` event that has never existed; the bus emits
`request:step:leave`.
### Changed ### Changed
- Root, runtime-only, and website dependency audits are clean after supported package updates and
narrow pins for vulnerable transitives. CI audits root + website trees and builds the docs; the
GitHub OIDC release workflow audits immediately before its publish gate.
- App-scope providers now boot exactly once (memoized): a second `app.listen()` - App-scope providers now boot exactly once (memoized): a second `app.listen()`
call no longer re-runs provider factories or their side effects. call no longer re-runs provider factories or their side effects.
- **`WsOpenCtx.req`** (available in `@Ws`/`@Sse` handlers) is now a neutral - **`WsOpenCtx.req`** (available in `@Ws`/`@Sse` handlers) is now a neutral
@@ -35,10 +100,11 @@ green-tea uses calendar versioning: `YY.MM.PATCH`.
`ctx.req`; use `ctx.protocol` / `ctx.ip` / `ctx.query` / `ctx.headers` `ctx.req`; use `ctx.protocol` / `ctx.ip` / `ctx.query` / `ctx.headers`
instead — all still provided. instead — all still provided.
- **Breaking (pre-1.0): transport is now enforced by declaration.** A buffered route - **Breaking (pre-1.0): transport is now enforced by declaration.** A buffered route
(`@Get`/`@Post`/`@Put`/`@Patch`/`@Delete`) whose handler returns an `AsyncIterable`, or a streaming (`@Get`/`@Head`/`@Post`/`@Put`/`@Patch`/`@Delete`/`@Options`) whose handler returns an
route (`@Sse`/`@Ws`) whose handler returns a plain value, now fails with a 500 `TransportMismatchError` `AsyncIterable`, or a streaming route (`@Sse`/`@Ws`) whose handler returns a plain value, now
instead of silently switching behavior. `@Stream` still negotiates both. Declare `@Sse`/`@Stream`/`@Ws` fails with a 500 `TransportMismatchError` instead of silently switching behavior. `@Stream`
to stream — a return value no longer changes a route's wire contract. still negotiates both. Declare `@Sse`/`@Stream`/`@Ws` to stream — a return value no longer
changes a route's wire contract.
## [26.7.0-beta.0] - 2026-07-07 ## [26.7.0-beta.0] - 2026-07-07
@@ -87,5 +153,6 @@ change before the stable release.
- **Benchmarks** — reproducible `npm run bench` harness vs Express 5, Fastify 5, - **Benchmarks** — reproducible `npm run bench` harness vs Express 5, Fastify 5,
NestJS, and raw `http`; results in [BENCHMARKS.md](./BENCHMARKS.md). NestJS, and raw `http`; results in [BENCHMARKS.md](./BENCHMARKS.md).
[Unreleased]: https://git.svc.zoit.services/Green-Tea/core/compare/26.7.0-beta.0...develop [Unreleased]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.0...main
[26.7.0-beta.0]: https://git.svc.zoit.services/Green-Tea/core/releases/tag/26.7.0-beta.0 [26.8.0-beta.0]: https://github.com/Expressive-Tea/green-tea/compare/v26.7.0-beta.0...v26.8.0-beta.0
[26.7.0-beta.0]: https://github.com/Expressive-Tea/green-tea/releases/tag/v26.7.0-beta.0
+52 -23
View File
@@ -11,31 +11,47 @@
not a mutable bag threaded through positional middleware. <i>That's the tea.</i> 🍵 not a mutable bag threaded through positional middleware. <i>That's the tea.</i> 🍵
</p> </p>
`@green-tea/core` — **beta**, RC-track. One runtime dependency: `reflect-metadata`. Two optional peers you install only if you use them: `ws` (WebSocket / mesh) and `busboy` (multipart uploads). ---
```bash ## The problem
npm install @green-tea/core reflect-metadata
# optional, only if you use them: ```js
npm install ws # WebSocket routes (@Ws) and mesh const user = req.user;
npm install busboy # multipart/form-data file uploads
``` ```
--- It compiles. TypeScript is happy. And it's a prayer — `req.user` exists only if some middleware ran before this handler, which depends on where the router got mounted, which line `app.use()` sits on, and whether a package you installed last sprint quietly inserted itself into the middle of your chain.
So you keep the whole request in your head: what ran, what's on `req` by now, what order things fire in, which plugin deleted your body parser. That bookkeeping is where the bugs live, and no test or type catches them, because nothing is *wrong* — the code is correct and the app is still broken.
## The idea ## The idea
Most frameworks make you keep the whole request in your head: which middleware ran, whether `req.user` exists by now, what order things fire in, which plugin quietly deleted your body parser. That mental bookkeeping is where bugs live. green-tea puts the request on the page instead. You declare what each step **needs** and **produces**; the framework computes the order, type-checks the wiring, and can print the whole thing.
green-tea puts the request on the page instead. You declare what each step **needs** and **produces**; the framework computes the order, type-checks the wiring, and can print the whole thing. A route runs only the steps its handler actually depends on. Boot fails loudly when a dependency is missing, so you never serve `undefined`. - Order is **derived** from your dependencies, never maintained by hand.
- Boot **fails loudly** when nothing provides a key, so you never serve `undefined`.
- A route runs **only** the steps its handler actually depends on.
- `app.explain('/users/:id')` prints the whole chain. Onboarding is reading, not archaeology.
Less to hold in your head. That's the tea. Less to hold in your head. That's the tea.
```bash
npm install @green-tea/core@beta reflect-metadata
```
`@green-tea/core` — **beta**, RC-track. One runtime dependency: `reflect-metadata`. Two optional peers you install only if you use them:
```bash
npm install ws # WebSocket routes (@Ws) and mesh
npm install busboy # multipart/form-data file uploads
```
## What's different — and why it matters ## What's different — and why it matters
- **The pipeline is a graph, not a chain.** You never write "put this before that." You declare `needs`/`provides` and green-tea topologically sorts it. *Why it matters:* no ordering bugs, no positional guesswork, and each route runs only its slice of the graph (an auth step doesn't run on public routes). - **The pipeline is a graph, not a chain.** You never write "put this before that." You declare `needs`/`provides` and green-tea topologically sorts it. *Why it matters:* no ordering bugs, no positional guesswork, and each route runs only its slice of the graph (an auth step doesn't run on public routes).
- **The type is the contract.** What a handler reads from the context *is* its dependency list. In the typed `flow` core, a handler that reads `ctx.user` **fails to compile** if no step produces `user`. *Why it matters:* whole classes of "it was undefined in prod" disappear at compile time. - **The type is the contract.** What a handler reads from the context *is* its dependency list. In the typed `flow` core, a handler that reads `ctx.user` **fails to compile** if no step produces `user`. *Why it matters:* whole classes of "it was undefined in prod" disappear at compile time.
- **You can see the request before it runs.** `app.explain('/users/:id')` prints the ordered chain with origins; `app.graph()` / `GET /__graph__` render it as a live diagram; `app.openapi()` projects the same metadata into an OpenAPI 3.1 spec. *Why it matters:* onboarding, debugging, audits, and API docs are reading, not archaeology. (NestJS puts the graph behind a paid Devtools plan.) - **You can see the request before it runs.** `app.explain('/users/:id')` prints the ordered chain with origins; `app.graph()` / `GET /__graph__` render it as a live diagram; `app.openapi()` projects the same metadata into an OpenAPI 3.1 spec. *Why it matters:* onboarding, debugging, audits, and API docs are reading, not archaeology. (NestJS puts the graph behind a paid Devtools plan.)
- **One primitive for real-time.** Return an `AsyncIterable` and the transport streams it — SSE, ndjson, or a WebSocket duplex — with backpressure and cleanup handled. *Why it matters:* no separate gateway, adapter, or library to bolt on. - **One primitive for real-time.** Declare the transport — SSE, ndjson, or a WebSocket duplex — and return an `AsyncIterable`; backpressure and cleanup are handled. *Why it matters:* no separate gateway, adapter, or library to bolt on.
- **The same app runs on Node, Deno, Bun, and the edge.** One codebase, one import; you swap the entry point (`app.listen` → `serveDeno` / `serveBun` / `edgeHandler`) and nothing else. HTTP, SSE, and WebSocket — including rooms and channels — behave identically on all four. *Why it matters:* the graph model isn't a bet on one runtime's future, and no other opinionated/DI framework runs everywhere.
- **A remote dependency looks like a local one.** `@needs('billing')` resolves the same whether `billing` lives in this process or on another node (mesh, experimental). *Why it matters:* no gRPC layer or message-pattern DSL to learn — there's the graph, and some nodes happen to live elsewhere. - **A remote dependency looks like a local one.** `@needs('billing')` resolves the same whether `billing` lives in this process or on another node (mesh, experimental). *Why it matters:* no gRPC layer or message-pattern DSL to learn — there's the graph, and some nodes happen to live elsewhere.
- **Plugins can't sabotage you.** A plugin gets `bus.on(...)` (observe) and `scope.add(...)` (extend its own scope). There is no API to reorder or delete another scope's steps. *Why it matters:* installing a plugin can't break your body parser. - **Plugins can't sabotage you.** A plugin gets `bus.on(...)` (observe) and `scope.add(...)` (extend its own scope). There is no API to reorder or delete another scope's steps. *Why it matters:* installing a plugin can't break your body parser.
@@ -50,14 +66,15 @@ green-tea has one model: an **`AsyncIterable`**. A handler that returns a sequen
| `@Sse` | server → client | `text/event-stream` | live updates to a browser (`EventSource`) | | `@Sse` | server → client | `text/event-stream` | live updates to a browser (`EventSource`) |
| `@Ws` | duplex | WebSocket | chat, collaboration — anything two-way | | `@Ws` | duplex | WebSocket | chat, collaboration — anything two-way |
| `@Stream` | negotiated | SSE / ndjson / WS, picked from the client's `Accept` / `Upgrade` | one handler, the client chooses | | `@Stream` | negotiated | SSE / ndjson / WS, picked from the client's `Accept` / `Upgrade` | one handler, the client chooses |
| *(plain return)* | server → client | SSE or ndjson by `Accept` | programmatic streaming over `fetch` |
The primitive never changes — it's always an `AsyncIterable`. What changes is **direction and framing**, and you declare which. That's the difference between each iterable green-tea hands you: The primitive never changes — it's always an `AsyncIterable`. What changes is **direction and framing**, and you declare which. That's the difference between each iterable green-tea hands you:
- **`@Sse` / plain return** — you return **one** iterable: the *outbound* stream. Each `yield` becomes an SSE event, or an ndjson line. - **`@Sse`** — you return **one** iterable: the *outbound* stream. Each `yield` becomes an SSE event, or an ndjson line.
- **`@Ws` (duplex)** — **two** iterables. `@inbound()` gives you the client's *incoming* messages to consume; the one you **return** is the *outbound* stream to the client. `@abort()` hands you an `AbortSignal` for teardown. - **`@Ws` (duplex)** — **two** iterables. `@inbound()` gives you the client's *incoming* messages to consume; the one you **return** is the *outbound* stream to the client. `@abort()` hands you an `AbortSignal` for teardown.
- **`@Stream`** — you write the handler once; the client's request decides whether it arrives as SSE, ndjson, or a WebSocket. No branching in your code. - **`@Stream`** — you write the handler once; the client's request decides whether it arrives as SSE, ndjson, or a WebSocket. No branching in your code.
**Your wire contract is what you declared, never what you happened to return.** A buffered route that returns an iterable, or a streaming route that returns a plain value, fails loudly with a `TransportMismatchError` — green-tea will not quietly switch a route's transport because of a return type. Refactoring a handler's internals can't change how it talks to the client.
Fan-out is a primitive too: `channel()` is a **multicast** `AsyncIterable` (bounded, drop-oldest) so one source feeds many subscribers, and `rooms` are named broadcast hubs — publish once, every connection in the room receives it. Fan-out is a primitive too: `channel()` is a **multicast** `AsyncIterable` (bounded, drop-oldest) so one source feeds many subscribers, and `rooms` are named broadcast hubs — publish once, every connection in the room receives it.
```typescript ```typescript
@@ -91,6 +108,8 @@ Beta shipped the parts a real API needs, without growing the runtime dependency
- **Validation via [Standard Schema](https://standardschema.dev).** `@body(schema)` accepts zod, valibot, or arktype — you bring the validator, the core stays zero-dep. Invalid input → `422` with per-field issues; the parsed value reaches your handler typed. - **Validation via [Standard Schema](https://standardschema.dev).** `@body(schema)` accepts zod, valibot, or arktype — you bring the validator, the core stays zero-dep. Invalid input → `422` with per-field issues; the parsed value reaches your handler typed.
- **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS. - **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS.
- **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response. - **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response.
- **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency.
- **Ceilings that are already on.** `limits` caps body size (`413`), multipart parts, and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. Configurable, and safe before you configure anything.
- **Graceful shutdown.** `app.close()` drains in-flight requests, closes live streams and mesh links. - **Graceful shutdown.** `app.close()` drains in-flight requests, closes live streams and mesh links.
- **Testable by construction.** `createApp({ overrides: { db: fakeDb } })` swaps any node in one line. - **Testable by construction.** `createApp({ overrides: { db: fakeDb } })` swaps any node in one line.
- **Dual ESM + CommonJS.** Ships both builds behind an `exports` map — `import` and `require` both resolve, with matching type declarations. - **Dual ESM + CommonJS.** Ships both builds behind an `exports` map — `import` and `require` both resolve, with matching type declarations.
@@ -117,6 +136,7 @@ Every framework here can serve `/users/:id`. The difference shows up as the app
| **Real-time** | bolt on `ws`/`sse` libs | plugins | separate Gateway + adapter | separate engine | **return an `AsyncIterable`** — SSE, ndjson & WebSocket, one primitive | | **Real-time** | bolt on `ws`/`sse` libs | plugins | separate Gateway + adapter | separate engine | **return an `AsyncIterable`** — SSE, ndjson & WebSocket, one primitive |
| **Cross-service calls** | HTTP client / gRPC by hand | HTTP client / gRPC | Microservices transport + message patterns | — | **`@needs('x')` resolves on another node** | | **Cross-service calls** | HTTP client / gRPC by hand | HTTP client / gRPC | Microservices transport + message patterns | — | **`@needs('x')` resolves on another node** |
| **Plugin can break your pipeline?** | yes (deletes your body parser) | encapsulated, but hooks are global | interceptor order matters | yes | **no** — plugins only `bus.on` + `scope.add` | | **Plugin can break your pipeline?** | yes (deletes your body parser) | encapsulated, but hooks are global | interceptor order matters | yes | **no** — plugins only `bus.on` + `scope.add` |
| **Runs on** | Node | Node | Node | Node | **Node · Deno · Bun · edge** — same code, swap the entry point |
| **Runtime deps** | minimal | minimal | heavy (rxjs, reflect-metadata, …) | Express + InversifyJS | **`reflect-metadata` only** (`ws`, `busboy` optional) | | **Runtime deps** | minimal | minimal | heavy (rxjs, reflect-metadata, …) | Express + InversifyJS | **`reflect-metadata` only** (`ws`, `busboy` optional) |
### Read it as a story ### Read it as a story
@@ -189,17 +209,20 @@ The handler signature declares exactly what it wants — in any order, nothing m
`@needs` keys are validated at boot: nothing provides the key → `createApp` throws with a clear error instead of serving `undefined`. Pass a Standard Schema (`@body(User)`) and the value is validated, coerced, and typed before your handler sees it. `@needs` keys are validated at boot: nothing provides the key → `createApp` throws with a clear error instead of serving `undefined`. Pass a Standard Schema (`@body(User)`) and the value is validated, coerced, and typed before your handler sees it.
> **Optional providers degrade, they don't crash.** A provider marked `optional: true` that throws on boot does **not** abort startup — it is left unregistered and logged. On `listen()` the app prints a one-line summary of what's running degraded, and the list is queryable via `app.degraded()`. Routes that actually need a degraded provider fail at request time, not at boot. This is deliberate (graceful degradation); wire an alert off `app.degraded()` or the `boot:provider:fail` bus event in production so a degraded start is never silent. > **Optional providers degrade, they don't crash.** A provider marked `optional: true` that throws on boot does **not** abort startup — it is left unregistered and logged. The first serving call (`fetch`, `upgrade`, or `listen`) prints a one-line summary of what's running degraded, and the list is queryable via `app.degraded()`. Routes that actually need a degraded provider fail at request time, not at boot. This is deliberate (graceful degradation); wire an alert off `app.degraded()` or the `boot:provider:fail` bus event in production so a degraded start is never silent.
## Routing ## Routing
Patterns match by segment: static, `:param` (one segment), and a trailing `:name*` **catch-all** that captures the rest of the path — slashes included — into `params.name`. When more than one route matches, the **most specific wins** (static ▸ `:param` ▸ catch-all), independent of registration order. A path that exists under a *different* method returns **`405` with an `Allow` header**, not `404`. Patterns match by segment: static, constrained params such as `:id(\d+)`, plain `:param`, and a trailing `:name*` **catch-all**. The most specific wins (static ▸ constrained ▸ plain param ▸ catch-all), and ambiguous same-method shapes fail at boot instead of depending on registration order.
```typescript ```typescript
@Get('/users/:id(\\d+)') // /users/42
@Get('/files/:path*') // /files/img/2026/logo.png → params.path = "img/2026/logo.png" @Get('/files/:path*') // /files/img/2026/logo.png → params.path = "img/2026/logo.png"
``` ```
**Not yet** (post-beta, on the roadmap): regex / typed param constraints like `:id(\d+)`, and route matching is a linear scan — fine for typical route tables, but a radix-tree matcher for very large ones isn't built. `@Head` and `@Options` provide explicit handlers. Otherwise a buffered GET can serve HEAD without a body, and OPTIONS on an existing path returns `204` with canonical `Allow`; other method mismatches return `405`. `/path` and `/path/` are equivalent, while repeated slashes and malformed encoding return `400` rather than being normalized ambiguously. Constraints use a deliberately safe regex subset. See the full [routing guide](https://green-tea.expressive-tea.io/docs/guides/routing/).
Matching is still a linear scan — fine for typical route tables. A radix tree for very large tables remains post-beta work.
## Two layers ## Two layers
@@ -220,21 +243,24 @@ green-tea is **beta**, on the road to a release candidate. Express and Fastify h
**Bring your own auth (and friends).** green-tea ships transport security — TLS/wss, secure-by-default headers, CORS — but **not** authentication, authorization, rate-limiting, CSRF, or sessions. You compose those as steps and plugins (the `Authenticate` step in the quick look is the pattern). Unlike Express/Fastify, there is no off-the-shelf plugin ecosystem for them yet. **Bring your own auth (and friends).** green-tea ships transport security — TLS/wss, secure-by-default headers, CORS — but **not** authentication, authorization, rate-limiting, CSRF, or sessions. You compose those as steps and plugins (the `Authenticate` step in the quick look is the pattern). Unlike Express/Fastify, there is no off-the-shelf plugin ecosystem for them yet.
**Node only.** Runs on Node ≥ 18. Deno / Bun / edge runtimes (over web-standard `Request`/`Response`) are on the roadmap, not built — only `src/http/` is runtime-specific today. **No observability layer, either.** There is no built-in logger, no metrics export, and no tracing hooks; core does not depend on a logging library and does not intend to. Today you compose those as steps and providers like anything else. A first-class contract — an injectable logger, structured output, and hooks an OpenTelemetry exporter can attach to — is [tracked as one design](https://github.com/Expressive-Tea/green-tea/issues/10), because doing it piecemeal produces three mechanisms that don't fit together. If your team's definition of production-ready includes shipping traces on day one, this is the gap to know about.
**Runtimes differ in what they can offer.** Node ≥ 18, Deno, and Bun run everything. On the edge (Cloudflare Workers) there is no `app.listen()`, no filesystem — so `@Html` file/template modes and `static` serving are unavailable — and mesh does not run there at all (the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which `nodejs_compat` doesn't provide). Workers also require the `nodejs_compat` flag.
**mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet. **mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet.
## Docs & development ## Docs & development
- **[Quickstart](./docs/quickstart.md)** — install + concrete examples (routes/DI, `flow`, validation, uploads, SSE, WebSocket, mesh, plugins). - **[green-tea.expressive-tea.io/docs](https://green-tea.expressive-tea.io/docs)** — getting started, concepts (the graph, `flow`), and guides: routing, DI, validation, uploads, streaming, HTML, security, errors, introspection, OpenAPI, plugins, mesh, runtimes, testing.
- **[Architecture](./docs/architecture.md)** — the mental map (layers, request lifecycle, mesh) as diagrams. - **[matcha](https://github.com/Expressive-Tea/matcha)** — the CLI. `matcha new` scaffolds a project (Node, Deno, or Bun), `matcha create` generates and auto-wires controllers/steps/providers/modules, `matcha run` detects your runtime and watches. A standalone Rust binary — no JS runtime needed to install it.
```bash ```bash
npm install npm install
npm test # vitest npm test # vitest (Node); test:deno / test:bun / test:edge for the other runtimes
npm run typecheck # tsc --noEmit (includes the compile-time-guarantee type test) npm run typecheck # tsc --noEmit (includes the compile-time-guarantee type test)
npm run build # emit dist/ npm run build # emit dist/ (tsup: dual ESM + CJS)
npm run bench # regenerate BENCHMARKS.md npm run bench # regenerate BENCHMARKS.md
npm run docs:dev # the documentation site (website/)
``` ```
## Roadmap ## Roadmap
@@ -244,13 +270,16 @@ npm run bench # regenerate BENCHMARKS.md
- ✅ **streams** — SSE / ndjson / WebSocket duplex over a multicast `AsyncIterable` channel, with backpressure and cleanup. - ✅ **streams** — SSE / ndjson / WebSocket duplex over a multicast `AsyncIterable` channel, with backpressure and cleanup.
- ✅ **graph introspection** — `explain` / `graph` / `toMermaid` / `GET /__graph__`. - ✅ **graph introspection** — `explain` / `graph` / `toMermaid` / `GET /__graph__`.
- ✅ **mesh (walking skeleton)** — `teapot`/`teacup` distributed DI over a secret-gated WS control channel. A BEAM/OTP-style cluster, *not* microservices. - ✅ **mesh (walking skeleton)** — `teapot`/`teacup` distributed DI over a secret-gated WS control channel. A BEAM/OTP-style cluster, *not* microservices.
- **next** — API freeze + first published release, mesh sub-specs (discovery, load-balancing, failover), runtime adapters (Deno / Bun / edge over web-standard `Request`/`Response`), official plugins. - ✅ **runs everywhere** — Node, Deno, Bun, and Cloudflare Workers over web-standard `Request`/`Response`, with identical WebSocket behaviour on all four.
- ✅ **HTML** — `@Html` (string / file / template), a built-in template engine with a bring-your-own `viewEngine` hook, and `static` serving.
- ✅ **router completeness for beta** — safe constrained params, deterministic precedence, explicit/automatic HEAD and OPTIONS, strict path validation, and ambiguity checks across local and mesh routes.
- **next** — API freeze + first published release, mesh sub-specs (discovery, load-balancing, failover), official plugins, and a radix-tree matcher for very large route tables.
## Versioning ## Versioning
green-tea uses **calendar versioning**: `YY.M.PATCH` (e.g. `26.7.0` = the first release cut in July 2026, patch 0). The month is **not** zero-padded — npm treats versions as semver, which forbids leading zeros. A version tells you *when* it shipped, not how many breaking changes preceded it — those are always called out in the [CHANGELOG](./CHANGELOG.md). green-tea uses **calendar versioning**: `YY.M.PATCH` (e.g. `26.8.0` = the first release cut in August 2026, patch 0). The month is **not** zero-padded — npm treats versions as semver, which forbids leading zeros. A version tells you *when* it shipped, not how many breaking changes preceded it — those are always called out in the [CHANGELOG](./CHANGELOG.md).
**While in beta**, releases carry a `-beta.N` pre-release suffix on the calendar version (e.g. `26.7.0-beta.0`) and publish under the npm `beta` dist-tag — so a plain `npm install @green-tea/core` won't pick one up until the first stable calendar release. The API can still change between betas. **While in beta**, releases carry a `-beta.N` pre-release suffix on the calendar version (e.g. `26.8.0-beta.0`) and publish under the npm `beta` dist-tag. Until the first stable release there is nothing else to install, so `latest` tracks the newest beta too — `npm install @green-tea/core` and `@green-tea/core@beta` resolve to the same version. Install with the explicit `@beta` tag anyway: the day a stable ships, `latest` moves to it and your installs stay on the channel you meant. The API can still change between betas.
## License ## License
+1 -1
View File
@@ -12,7 +12,7 @@ app.post('/validate', {
if (!b.email.includes('@')) { reply.code(422); return { error: 'invalid' }; } if (!b.email.includes('@')) { reply.code(422); return { error: 'invalid' }; }
return { email: b.email }; return { email: b.email };
}); });
app.listen({ port: 0 }, (err, addr) => { app.listen({ port: 0, host: '0.0.0.0' }, (err, addr) => {
if (err) { console.error(err); process.exit(1); } if (err) { console.error(err); process.exit(1); }
console.log(`READY ${Number(new URL(addr).port)}`); console.log(`READY ${Number(new URL(addr).port)}`);
}); });
+34
View File
@@ -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}`);
+33
View File
@@ -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}`) });
+1 -1
View File
@@ -9,7 +9,7 @@ async function main() {
inst.disable('x-powered-by'); inst.disable('x-powered-by');
inst.set('etag', false); inst.set('etag', false);
const app = await NestFactory.create(BenchModule, new ExpressAdapter(inst), { logger: false }); const app = await NestFactory.create(BenchModule, new ExpressAdapter(inst), { logger: false });
await app.listen(0, '127.0.0.1'); await app.listen(0, '0.0.0.0');
const server = app.getHttpServer(); const server = app.getHttpServer();
server.keepAliveTimeout = 5000; // parity (works on Node http.Server after listen) server.keepAliveTimeout = 5000; // parity (works on Node http.Server after listen)
console.log(`READY ${server.address().port}`); console.log(`READY ${server.address().port}`);
+1 -1
View File
@@ -6,7 +6,7 @@ import { BenchModule } from './_nest-shared';
async function main() { async function main() {
const adapter = new FastifyAdapter({ logger: false, keepAliveTimeout: 5000 }); // parity via constructor const adapter = new FastifyAdapter({ logger: false, keepAliveTimeout: 5000 }); // parity via constructor
const app = await NestFactory.create<NestFastifyApplication>(BenchModule, adapter, { logger: false }); const app = await NestFactory.create<NestFastifyApplication>(BenchModule, adapter, { logger: false });
await app.listen(0, '127.0.0.1'); await app.listen(0, '0.0.0.0');
const server = app.getHttpServer(); const server = app.getHttpServer();
console.log(`READY ${(server.address() as any).port}`); console.log(`READY ${(server.address() as any).port}`);
} }
+26
View File
@@ -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}`);
});
+33
View File
@@ -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); });
Generated
+24 -13
View File
@@ -18,11 +18,11 @@
"workspace": { "workspace": {
"packageJson": { "packageJson": {
"dependencies": [ "dependencies": [
"npm:@eslint/js@^9.39.4", "npm:@eslint/js@^9.39.5",
"npm:@nestjs/common@^11.1.27", "npm:@nestjs/common@^11.1.28",
"npm:@nestjs/core@^11.1.27", "npm:@nestjs/core@^11.1.28",
"npm:@nestjs/platform-express@^11.1.27", "npm:@nestjs/platform-express@^11.1.28",
"npm:@nestjs/platform-fastify@^11.1.27", "npm:@nestjs/platform-fastify@^11.1.28",
"npm:@stylistic/eslint-plugin@^5.10.0", "npm:@stylistic/eslint-plugin@^5.10.0",
"npm:@types/autocannon@^7.12.7", "npm:@types/autocannon@^7.12.7",
"npm:@types/busboy@^1.5.4", "npm:@types/busboy@^1.5.4",
@@ -32,20 +32,31 @@
"npm:autocannon@8", "npm:autocannon@8",
"npm:busboy@^1.6.0", "npm:busboy@^1.6.0",
"npm:cognitive-complexity-ts@~0.8.2", "npm:cognitive-complexity-ts@~0.8.2",
"npm:eslint@^9.39.4", "npm:esbuild@0.27.2",
"npm:eslint@^9.39.5",
"npm:express@^5.2.1", "npm:express@^5.2.1",
"npm:fastify@^5.10.0", "npm:fastify@^5.11.0",
"npm:graphql@^16.9.0", "npm:graphql@^16.9.0",
"npm:prettier@^3.9.4", "npm:miniflare@^4.20260730.0",
"npm:prettier@^3.9.6",
"npm:reflect-metadata@0.2.2", "npm:reflect-metadata@0.2.2",
"npm:rxjs@^7.8.2", "npm:rxjs@^7.8.2",
"npm:tsup@^8.5.1", "npm:tsup@^8.5.1",
"npm:tsx@^4.23.0", "npm:tsx@^4.23.5",
"npm:typescript-eslint@^8.63.0", "npm:typescript-eslint@^8.65.0",
"npm:typescript@^5.5.0", "npm:typescript@^5.5.0",
"npm:vitest@2", "npm:vite@^6.4.3",
"npm:ws@^8.21.0" "npm:vitest@^3.2.7",
] "npm:ws@^8.21.1"
],
"overrides": {
"find-my-way": "9.7.0",
"autocannon": {
"hyperid": {
"uuid": "11.1.1"
}
}
}
} }
} }
} }
-115
View File
@@ -1,115 +0,0 @@
# green-tea — Architecture
> The request and boot are an explicit **dependency graph**, not a mutable middleware chain.
> You declare *what* you need; the framework computes the order. The graph can extend in
> **time** (streams) and across **machines** (mesh).
## The four layers
```mermaid
flowchart TB
subgraph L3["#3 MESH — the graph crosses machines"]
direction LR
teacup["teacup (consumer)"] -- "WS RPC" --> teapot["teapot (host)"]
end
subgraph L2["#2 STREAMS — the graph emits over time"]
sse["SSE / ndjson"]:::n
ws["WebSocket duplex"]:::n
end
subgraph L15["#1.5 ARG DECORATORS — the handler declares its deps"]
sig["handler signature = dependency declaration"]:::n
end
subgraph L1["#1 CORE — graph DI + boot + router + pipeline + flow"]
core["Providers · Steps · Routes · Transformers · Container · Bus"]:::n
end
L3 --> L2 --> L15 --> L1
classDef n fill:#f6f8fa,stroke:#aaa;
```
## Building blocks
```mermaid
flowchart LR
Provider["@Provider\n(app scope · singleton)"]:::p
Step["@Step\n(request scope · per call)"]:::s
Route["@Route + @Get/@Post/@Sse/@Ws/@Stream"]:::r
Transformer["@Transformer\nvalue → ResponseShape"]:::t
Container["Container.resolve()\nasync · transport-agnostic"]:::c
Bus["Bus\nlifecycle events"]:::b
Provider --> Container
Step --> Container
Route --> Transformer
Container -. "remote binding (mesh)" .-> Provider
classDef p fill:#e7f5ff,stroke:#4dabf7;
classDef s fill:#fff3bf,stroke:#f59f00;
classDef r fill:#ebfbee,stroke:#40c057;
classDef t fill:#f3f0ff,stroke:#7950f2;
classDef c fill:#fff0f6,stroke:#e64980;
classDef b fill:#f1f3f5,stroke:#868e96;
```
## Request lifecycle
```mermaid
sequenceDiagram
participant C as Client
participant H as http.ts (transport)
participant P as Pipeline
participant G as Graph (providers/steps)
participant T as Transformer
C->>H: HTTP request
H->>H: matchRoute(method, path)
H->>P: runPipeline(seed = req envelope)
P->>G: providers (cached) + steps (topo order)
Note over G: each step merges into ctx;<br/>throw = short-circuit, return = continue
P->>P: handler(args resolved from ctx)
alt returns a value
P->>T: transformer → {status, headers, body}
T-->>C: buffered response
else returns an AsyncIterable
P-->>C: stream (SSE / ndjson / WS), backpressure + cleanup
else @needs a remote token
G-->>C: RPC to teapot, value spliced into ctx
end
```
## The unifying rule
```mermaid
flowchart TD
Q{"what does the handler return /\nwhere does a token live?"}
Q -->|"a value"| A["buffered (transformer → JSON)"]
Q -->|"an AsyncIterable"| B["stream (SSE / WS)"]
Q -->|"a token with no local provider"| D["RPC to a teapot (mesh)"]
```
One question — *"what produces this token and where does it live?"* — answers local DI,
streaming, and distribution. That single seam is why green-tea isn't "Express with decorators":
**the graph is the product.**
## Mesh walking skeleton (spec #3)
```mermaid
flowchart LR
subgraph A["Node A — teapot"]
ea["@Provider({export:true})\n@Step({export:true})\n@Get('/x',{export:true})"]
mc["control channel\n/__mesh__/control\n(secret-gated)"]
end
subgraph B["Node B — teacup"]
bn["@needs('auth') with\nno local provider"]
lk["link: handshake → manifest\n→ synthetic graph nodes\nwith RPC runners"]
end
bn --> lk
lk -- "hello + secret" --> mc
mc -- "manifest {scopes, routes}" --> lk
lk -- "rpc-req {id, kind, name, ctx}" --> mc
mc -- "rpc-res {id, ok, result}" --> lk
```
- **Provider exported → app scope** (resolved once via RPC, cached).
- **Step exported → request scope** (RPC per request, carries the request envelope).
- **Route exported → proxy** (teacup forwards the request, teapot runs the full pipeline).
Deferred to mesh sub-specs: discovery/auto-registration, 2-way load-balancing, failover/health.
@@ -0,0 +1,170 @@
# Router correctness and security beta design
**Date:** 2026-08-02
**Target:** `26.8.0-beta.0`
**Status:** Approved
## Goal
Prepare the August beta by completing the router's missing HTTP behavior, adding safe segment constraints, aligning the public documentation with the code, and removing known dependency vulnerabilities from the core repository and documentation site.
The release keeps the current linear matcher. A radix tree remains a separate performance project that must earn its complexity through benchmarks.
## Scope
This change includes:
- first-class `HEAD` and `OPTIONS` routes;
- automatic `HEAD` fallback to `GET`;
- automatic bare `OPTIONS` responses;
- correct and deterministic `Allow` headers;
- a tolerant trailing-slash policy with rejection of repeated internal slashes;
- route-pattern validation at boot;
- safe parameter constraints such as `:id(\d+)`;
- malformed URI handling as a client error;
- duplicate and ambiguous route detection;
- OpenAPI projection of constrained parameters;
- dependency remediation for the root package and `website/`;
- public documentation and changelog updates;
- the `26.8.0-beta.0` package-version bump.
This change excludes:
- a radix-tree matcher;
- arbitrary, unrestricted regular expressions;
- manual publication, npm tags, or registry mutations;
- mesh discovery, load balancing, and failover.
## Route semantics
### Path normalization
`/users` and `/users/` identify the same route. The matcher removes one trailing slash except for `/`.
The ingress rejects repeated slashes, including `/users//42`, with `400 Bad Request`. It applies this rule before declared-route matching and static-file fallback, so Node and Fetch adapters behave alike.
Malformed percent encoding also returns `400 Bad Request`. A malformed path never escapes the matcher as `URIError` and never becomes `500`.
### Methods
The public `HttpMethod` type and decorator surface gain `HEAD` and `OPTIONS`. `@Head` and `@Options` accept the same route options as the existing buffered method decorators.
For `HEAD`, an explicit `HEAD` route wins. Without one, the router matches the corresponding `GET` route and executes its pipeline, but every adapter suppresses the response body. The response retains the status and headers that `GET` would produce. Streaming routes do not serve as implicit `HEAD` handlers.
For a bare `OPTIONS` request, an explicit `OPTIONS` route wins. Without one, any matching path receives `204 No Content` and an `Allow` header. CORS preflight remains the earlier specialized branch and keeps its configured CORS response.
`Allow` uses a stable method order. It adds `HEAD` when a buffered `GET` route exists and adds `OPTIONS` whenever the path exists. A request with another unsupported method receives `405` plus the same value.
### Pattern validation
The application compiles and validates route patterns during graph construction. Invalid declarations fail before the app serves traffic. Validation rejects:
- a catch-all outside the final segment;
- empty parameter or catch-all names;
- repeated parameter names in one pattern;
- repeated internal slashes in declarations;
- malformed constraints;
- duplicate routes with the same method and effective pattern;
- patterns that differ only by parameter names and therefore match the same requests with equal precedence.
Errors name the method, pattern, controller origin, and conflict when applicable.
### Segment constraints
The matcher accepts a constrained parameter such as `:id(\d+)`. A constraint matches the whole decoded segment. `/users/12` matches `:id(\d+)`; `/users/12x` does not. A failed constraint remains a normal non-match, so another route may win before the router returns `404`.
The implementation compiles constraints once and caches the compiled pattern. It accepts a deliberately small regular-expression subset for common numeric, UUID, slug, and enumerated segments. It rejects lookarounds, backreferences, nested groups, nested quantifiers, and other constructs that create a practical ReDoS risk. This keeps the advertised syntax without executing unrestricted attacker-facing regular expressions.
Specificity remains deterministic:
1. static segment;
2. constrained parameter;
3. unconstrained parameter;
4. catch-all.
Registration order resolves only genuine, non-ambiguous ties that survive boot validation.
## Architecture
`src/http/router.ts` owns pattern parsing, validation, compilation, matching, method fallback, and `Allow` calculation. A compiled representation records normalized segments, parameter names, optional constraints, catch-all state, and specificity.
`src/metadata.ts` exposes the new method type and decorators. Application graph construction compiles route definitions and reports declaration errors with controller context. The runtime-neutral HTTP core decides `HEAD`, `OPTIONS`, `400`, `404`, and `405`; Node and Fetch adapters only serialize its outcome.
`src/openapi.ts` converts constrained paths to OpenAPI templates and places the accepted expression in the path parameter's `schema.pattern`. It lists explicit `HEAD` and `OPTIONS` operations but does not invent operations for automatic fallbacks.
Mesh route manifests carry the expanded method union. Existing wire behavior stays compatible because method values are strings and the change adds values without changing the envelope shape.
## Error behavior
Declaration errors fail at boot. Request syntax errors return the standard error envelope with status `400` and pass through the configured `onError` renderer. Pattern non-matches return `404`; method mismatches return `405`; automatic `OPTIONS` returns `204`.
Error responses keep the existing security and CORS header injection. They do not include decoded attacker input, stack traces, or internal regular-expression details.
## Dependency remediation
The published runtime dependency set is already clean: `npm audit --omit=dev` reports zero vulnerabilities. The full development tree and documentation site require remediation.
The root update will prefer the smallest supported versions that close each advisory:
- Vitest moves to `3.2.6`, which fixes the critical advisory while preserving Node 18 support;
- the Nest benchmark packages move to `11.1.28`, including Multer `2.2.0`;
- Miniflare moves to its current compatible patch with fixed Sharp;
- Fastify and compatible toolchain packages receive current patch/minor updates;
- `find-my-way` receives a narrow `9.7.0` override while Nest pins the vulnerable `9.6.0`, with Nest/Fastify benchmarks as a compatibility gate;
- Autocannon's `hyperid`/`uuid` chain receives an isolated remediation only if the benchmark suite proves it compatible; otherwise the benchmark dependency will be replaced or isolated rather than suppressing the advisory.
The documentation site moves Astro to `7.1.6`, Starlight to `0.41.6`, and resolves the patched PostCSS and SVGO versions. Both lockfiles will be regenerated from their manifests.
The work will not use `npm audit fix --force`, security-audit suppression, or an incompatible downgrade merely to produce a green report.
## Documentation
The change updates:
- the README routing section and roadmap;
- the Routing guide;
- the Decorators reference;
- the OpenAPI guide where constrained parameters affect output;
- the CHANGELOG and package version;
- the Starlight 404 configuration that currently emits a build warning.
Examples will state the trailing-slash policy, double-slash rejection, automatic method behavior, constraint limits, and the deferred radix-tree work.
## Verification
The implementation adds unit and integration coverage for:
- explicit and implicit `HEAD`;
- body suppression and header preservation;
- explicit and automatic `OPTIONS`;
- CORS-preflight precedence;
- deterministic `Allow` values;
- trailing slash equivalence and double-slash rejection;
- invalid percent encoding;
- route-declaration failures;
- constrained matches, non-matches, precedence, and unsafe-expression rejection;
- OpenAPI path and `schema.pattern` output;
- Node and Fetch parity;
- mesh method serialization where relevant.
The release gate runs:
- root and website audits with zero known vulnerabilities;
- the runtime-only root audit separately;
- Node tests, typecheck, lint, format, complexity, and build;
- Deno, Bun, and Edge suites when their runtimes are available;
- documentation build without the current 404 warning;
- framework benchmarks, including the Nest/Fastify paths affected by overrides;
- `npm pack --dry-run` to inspect the published artifact.
## CI and publication flow
Gitea remains the source of the release flow:
1. CI runs on `develop` and `main`.
2. A merge to Gitea `main` publishes the package to internal Verdaccio under `stg`.
3. Gitea's promotion workflow pushes only `main` and version tags to GitHub.
4. A promoted `v*` tag triggers GitHub's `release.yml`.
5. GitHub publishes to npm through Trusted Publishing/OIDC and derives `beta` from `26.8.0-beta.0`.
This implementation prepares the version and validates the workflows. It does not merge to `main`, create a release tag, publish to Verdaccio, or invoke `npm publish` locally.
@@ -0,0 +1,679 @@
# Router Security Beta Implementation Plan
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
**Goal:** Ship `26.8.0-beta.0` with complete HEAD/OPTIONS behavior, safe constrained route parameters, strict path handling, accurate documentation, and clean dependency audits.
**Architecture:** Keep the linear route table, but compile and validate each pattern once. Centralize path syntax, matching, method fallback, and `Allow` calculation in the runtime-neutral HTTP layer so Node and Fetch adapters stay behaviorally identical. Remediate tooling dependencies without changing the package's Node 18 runtime contract or its one required runtime dependency.
**Tech Stack:** TypeScript, legacy decorators, Node HTTP, Fetch API, Vitest, OpenAPI 3.1, Astro/Starlight, npm lockfiles, GitHub/Gitea Actions.
---
### Task 1: Compile and validate route patterns
**Skills:** `@superpowers:test-driven-development`, `@security-review`
**Files:**
- Modify: `src/http/router.ts`
- Modify: `src/http/types.ts`
- Test: `test/router.test.ts`
**Step 1: Write failing compiler tests**
Add tests that establish the supported grammar and precedence:
```typescript
describe('compilePattern', () => {
it('compiles constrained params and gives them precedence over plain params', () => {
const routes = [route('GET', '/users/:value'), route('GET', '/users/:id(\\d+)')];
expect(matchRoute(routes, 'GET', '/users/42')?.def.pattern).toBe('/users/:id(\\d+)');
expect(matchRoute(routes, 'GET', '/users/diego')?.def.pattern).toBe('/users/:value');
});
it.each([
'/files/:rest*/tail',
'/users/:',
'/users/:id/:id',
'/users//:id',
'/users/:id((a+)+)',
'/users/:id((?=a)a)',
'/users/:id(\\1)',
])('rejects invalid or unsafe pattern %s', (pattern) => {
expect(() => compilePattern(pattern)).toThrow(/invalid route pattern|unsafe route constraint/);
});
});
```
Also cover numeric, UUID-like, slug, and bounded-quantifier examples; a constraint must match the complete decoded segment.
**Step 2: Run the focused test and confirm RED**
Run:
```bash
npx vitest run test/router.test.ts
```
Expected: FAIL because `compilePattern` and constrained matching do not exist.
**Step 3: Implement the compiled representation**
In `src/http/router.ts`, add:
```typescript
type CompiledSegment =
| { kind: 'static'; value: string }
| { kind: 'param'; name: string; constraint?: RegExp }
| { kind: 'catchAll'; name: string };
export interface CompiledPattern {
source: string;
normalized: string;
shape: string;
segments: CompiledSegment[];
kinds: number[]; // static=3, constrained=2, param=1; catch-all stored separately
catchAll: boolean;
}
```
Implement `compilePattern(pattern)`, `matchCompiled(compiled, pathSegments)`, and a string-keyed cache used by `matchPattern`. Parse `:name(expr)` only when the closing `)` ends the segment. Anchor accepted constraints as `^(?:${expr})$`.
Implement `assertSafeConstraint` as a small whitelist parser. Permit literals, character classes, `\\d`/`\\w`/`\\s` classes, escaped literals, and simple quantifiers. Reject expression length above 128, groups, alternation, anchors, lookarounds, backreferences, nested quantifiers, and adjacent unbounded quantified atoms without a separating literal. Do not add a runtime dependency.
Build `shape` from segment kinds and constraint source so `:id` and `:name` have the same effective shape.
**Step 4: Run tests and confirm GREEN**
Run:
```bash
npx vitest run test/router.test.ts
npm run typecheck
```
Expected: all router tests pass and TypeScript reports no errors.
**Step 5: Commit**
```bash
git add src/http/router.ts src/http/types.ts test/router.test.ts
git commit -s -m "feat(router): compile safe constrained patterns"
```
### Task 2: Validate request paths and route-table ambiguity
**Skills:** `@superpowers:test-driven-development`, `@security-review`
**Files:**
- Modify: `src/http/router.ts`
- Modify: `src/app/index.ts`
- Modify: `src/app/types.ts`
- Test: `test/router.test.ts`
- Test: `test/app.test.ts`
**Step 1: Write failing path-policy tests**
Add router tests for the approved normalization:
```typescript
expect(normalizeRequestPath('/users')).toBe('/users');
expect(normalizeRequestPath('/users/')).toBe('/users');
expect(normalizeRequestPath('/')).toBe('/');
expect(() => normalizeRequestPath('/users//42')).toThrow(/repeated slash/);
expect(() => normalizeRequestPath('/users/%E0%A4%A')).toThrow(/malformed path encoding/);
```
Add app-construction tests proving that identical routes and routes that differ only by parameter names fail before serving:
```typescript
expect(() => createApp({ modules: [DuplicateRouteModule] })).toThrow(/ambiguous route.*GET/);
```
Cover the same path under different methods as valid.
**Step 2: Run focused tests and confirm RED**
```bash
npx vitest run test/router.test.ts test/app.test.ts
```
Expected: FAIL because normalization and ambiguity checks are absent.
**Step 3: Implement request normalization**
Add `InvalidRequestPathError` and `normalizeRequestPath(path)` to `src/http/router.ts`. Strip exactly one trailing slash except at root, reject `//`, and call `decodeURIComponent` on every raw segment only to validate encoding. Matching still compares static segments according to the existing encoded-path contract and decodes captured values once.
**Step 4: Implement route-table validation**
Store a `compiled` pattern on each internal `RoutePlan`/`RouteDef`, or expose a shared cache accessor if that avoids duplicating state. During `collectControllers`, compile each joined pattern and compare the candidate's method plus `shape` with existing route plans. Throw an error that includes method, pattern, controller/handler, and conflicting declaration.
Apply the same validation after remote mesh routes join. A remote conflict must name both mesh owner URLs rather than silently selecting registration order.
**Step 5: Run focused and mesh tests**
```bash
npx vitest run test/router.test.ts test/app.test.ts test/mesh/fetch-boot.test.ts test/mesh/integration.test.ts
npm run typecheck
```
Expected: all selected tests pass.
**Step 6: Commit**
```bash
git add src/http/router.ts src/app/index.ts src/app/types.ts test/router.test.ts test/app.test.ts
git commit -s -m "fix(router): reject invalid and ambiguous paths"
```
### Task 3: Add HEAD and OPTIONS to the public decorator API
**Skills:** `@superpowers:test-driven-development`
**Files:**
- Modify: `src/metadata.ts`
- Modify: `src/index.ts`
- Modify: `src/signals.ts`
- Test: `test/metadata.test.ts`
- Test: `test/smoke.test.ts`
**Step 1: Write failing decorator tests**
```typescript
class Methods {
@Head('/resource') head() {}
@Options('/resource') options() {}
}
expect(getRoutes(Methods).map(({ method }) => method)).toEqual(['HEAD', 'OPTIONS']);
```
Add a public-barrel smoke test that imports `Head`, `Options`, and `HttpMethod` from `src/index.ts`.
**Step 2: Run tests and confirm RED**
```bash
npx vitest run test/metadata.test.ts test/smoke.test.ts
```
Expected: FAIL because the exports do not exist.
**Step 3: Implement decorators and messages**
Extend `HttpMethod`:
```typescript
export type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS';
```
Create buffered `Head` and `Options` decorators through `routeDecorator`, export them from `src/index.ts`, and update `TransportMismatchError`'s buffered-method message. Keep `@Html` restricted to GET/POST and update its rejection text to include HEAD/OPTIONS.
**Step 4: Run tests and typecheck**
```bash
npx vitest run test/metadata.test.ts test/smoke.test.ts test/transport-enforcement.test.ts test/views-html.test.ts
npm run typecheck
```
Expected: all pass.
**Step 5: Commit**
```bash
git add src/metadata.ts src/index.ts src/signals.ts test/metadata.test.ts test/smoke.test.ts
git commit -s -m "feat(router): expose HEAD and OPTIONS decorators"
```
### Task 4: Implement runtime-neutral HEAD, OPTIONS, and path errors
**Skills:** `@superpowers:test-driven-development`, `@security-review`
**Files:**
- Modify: `src/http/router.ts`
- Modify: `src/http/core.ts`
- Modify: `src/http/web.ts`
- Modify: `src/http/server.ts`
- Test: `test/router.test.ts`
- Test: `test/http.test.ts`
- Test: `test/fetch.test.ts`
- Test: `test/parity.test.ts`
- Test: `test/transport-security.test.ts`
**Step 1: Write failing method-semantics tests**
Cover these cases in both Node and `app.fetch`:
```typescript
// Explicit HEAD wins.
// Otherwise buffered GET runs once, retains status/headers, and emits an empty body.
// Streaming GET does not become implicit HEAD.
// Explicit OPTIONS wins.
// Automatic OPTIONS returns 204 and deterministic Allow.
// GET implies HEAD; every existing path implies OPTIONS.
// CORS preflight still runs before explicit/automatic OPTIONS.
// Double slash and malformed encoding return 400 with security headers.
```
Use a canonical expected header such as `GET, HEAD, POST, OPTIONS`.
**Step 2: Run focused tests and confirm RED**
```bash
npx vitest run test/router.test.ts test/http.test.ts test/fetch.test.ts test/parity.test.ts test/transport-security.test.ts
```
Expected: new assertions fail under the current 405 behavior.
**Step 3: Implement method resolution**
In `src/http/router.ts`, add a stable method order and helpers:
```typescript
export interface ResolvedRoute extends MatchedRoute {
implicitHead: boolean;
}
export function resolveRoute(routes: RouteDef[], method: string, path: string): ResolvedRoute | undefined;
export function allowedMethods(routes: RouteDef[], path: string): HttpMethod[];
```
`resolveRoute` tries explicit method first. For HEAD only, it falls back to a matching buffered GET. `allowedMethods` deduplicates explicit methods, adds HEAD for buffered GET, adds OPTIONS for every existing path, and sorts canonically.
**Step 4: Implement core outcomes**
At the start of `handle`, normalize the path and render `InvalidRequestPathError` as `400`. Preserve the existing CORS-preflight branch. Resolve explicit OPTIONS normally; otherwise return buffered `204` with `allow` and empty body. For an implicit or explicit HEAD route, run the normal pipeline but replace a buffered result body with `''`. Reject a stream outcome for HEAD as a transport mismatch rather than opening a stream.
**Step 5: Align body acquisition in both adapters**
Replace early `matchRoute` calls in `src/http/web.ts` and `src/http/server.ts` with the same normalization and resolution helper used by `handle`. If path validation fails before body acquisition, render `400` through `onError` with injected security/CORS headers. Never read a request body for automatic OPTIONS or an invalid path.
**Step 6: Run focused tests and confirm GREEN**
```bash
npx vitest run test/router.test.ts test/http.test.ts test/fetch.test.ts test/parity.test.ts test/transport-security.test.ts
npm run typecheck
```
Expected: all selected tests pass with Node/Fetch parity.
**Step 7: Commit**
```bash
git add src/http/router.ts src/http/core.ts src/http/web.ts src/http/server.ts test/router.test.ts test/http.test.ts test/fetch.test.ts test/parity.test.ts test/transport-security.test.ts
git commit -s -m "feat(http): complete HEAD and OPTIONS semantics"
```
### Task 5: Project constraints into OpenAPI and introspection
**Skills:** `@superpowers:test-driven-development`
**Files:**
- Modify: `src/openapi.ts`
- Modify: `src/app/introspect.ts`
- Test: `test/openapi.test.ts`
- Test: `test/graph-viz.test.ts`
**Step 1: Write failing OpenAPI tests**
Add `@Get('/:id(\\d+)')`, explicit `@Head`, and explicit `@Options` routes to the fixture. Assert:
```typescript
expect(doc.paths['/api/users/{id}']).toBeDefined();
expect((doc.paths['/api/users/{id}'].get as any).parameters).toContainEqual(
expect.objectContaining({ name: 'id', schema: { type: 'string', pattern: '\\d+' } }),
);
expect(doc.paths['/api/users/{id}'].head).toBeDefined();
expect(doc.paths['/api/users/{id}'].options).toBeDefined();
```
Assert that automatic HEAD/OPTIONS operations are not invented.
**Step 2: Run tests and confirm RED**
```bash
npx vitest run test/openapi.test.ts test/graph-viz.test.ts
```
Expected: constrained template parsing or schema assertions fail.
**Step 3: Implement projection**
Reuse the route compiler's parsed segment data instead of parsing the syntax a second way. Convert params and catch-alls to `{name}`. Add `schema.pattern` only for constrained params. Ensure `inspect`, `explain`, Mermaid, and DOT retain the human-readable original pattern.
**Step 4: Run tests and typecheck**
```bash
npx vitest run test/openapi.test.ts test/graph-viz.test.ts test/app.test.ts
npm run typecheck
```
Expected: all pass.
**Step 5: Commit**
```bash
git add src/openapi.ts src/app/introspect.ts test/openapi.test.ts test/graph-viz.test.ts
git commit -s -m "feat(openapi): document constrained route params"
```
### Task 6: Remove root and website dependency advisories
**Skills:** `@security-review`
**Files:**
- Modify: `package.json`
- Modify: `package-lock.json`
- Modify: `website/package.json`
- Modify: `website/package-lock.json`
- Test: `bench/servers/nestjs-express.ts`
- Test: `bench/servers/nestjs-fastify.ts`
**Step 1: Record the failing audit baseline**
```bash
npm audit
npm --prefix website audit
npm audit --omit=dev
```
Expected: root full audit reports 17 advisories, website reports 3, runtime-only root reports 0.
**Step 2: Apply supported direct updates**
Update root dependencies with explicit commands so the manifests and lockfile agree:
```bash
npm install --save-dev vitest@^3.2.6 \
@nestjs/common@^11.1.28 @nestjs/core@^11.1.28 \
@nestjs/platform-express@^11.1.28 @nestjs/platform-fastify@^11.1.28 \
fastify@^5.11.0 miniflare@^4.20260730.0 \
@eslint/js@^9.39.5 eslint@^9.39.5 prettier@^3.9.6 \
tsx@^4.23.5 typescript-eslint@^8.65.0 ws@^8.21.1
npm --prefix website install astro@^7.1.6 @astrojs/starlight@^0.41.6
```
Do not bump TypeScript, ESLint, or GraphQL across their next major versions.
**Step 3: Add narrow overrides only for unresolved vulnerable transitives**
Run `npm audit --json` and inspect the exact remaining paths. Add the smallest overrides justified by that output, initially:
```json
{
"overrides": {
"@nestjs/platform-fastify": {
"find-my-way": "9.7.0"
},
"autocannon": {
"hyperid": {
"uuid": "11.1.1"
}
}
}
}
```
If npm rejects nested override syntax, express the same ownership with `$` references or the supported nested-object form for the installed npm version. Never add a global override when a package-scoped one works.
**Step 4: Prove compatibility before accepting overrides**
```bash
npm run typecheck
npm test
npm run bench
```
Expected: tests pass; Express, Fastify, Nest Express, and Nest Fastify scenarios start and complete; Autocannon produces all scenario rows. If the UUID override breaks Autocannon, revert only that override and replace/isolate Autocannon in a follow-up commit within this task until the full audit is clean.
**Step 5: Verify clean audits**
```bash
npm audit
npm audit --omit=dev
npm --prefix website audit
```
Expected: all three commands exit 0 with zero vulnerabilities.
**Step 6: Commit**
```bash
git add package.json package-lock.json website/package.json website/package-lock.json
git commit -s -m "chore(deps): remediate security advisories"
```
### Task 7: Add security and documentation gates to CI
**Skills:** `@security-review`
**Files:**
- Modify: `.github/workflows/ci.yml`
- Modify: `.github/workflows/release.yml`
**Step 1: Define the expected gates**
The CI job must install root and website lockfiles, audit both, build docs, and preserve the existing Node 18 package gate. The GitHub-only release job must audit the root tree immediately after `npm ci` and before `npm publish`.
**Step 2: Update CI**
Add these steps after the root `npm ci`:
```yaml
- run: npm audit
- run: npm ci --prefix website
- run: npm audit --prefix website
- run: npm run docs:build
```
Keep lint, format, complexity, typecheck, test, and build unchanged.
**Step 3: Update the GitHub release gate**
Add `npm audit` after `npm ci` in `.github/workflows/release.yml`. Do not change the tag trigger, Gitea server guard, Node 22 OIDC setup, dist-tag derivation, or `npm publish` command.
Do not modify `stage.yml` or `promote.yml`; their verified GitFlow responsibilities remain:
- Gitea `main` → Verdaccio `stg`;
- Gitea `main` and `v*` tags → GitHub;
- GitHub `v*` → npm OIDC release.
**Step 4: Validate workflow syntax and diff**
```bash
npx prettier --check .github/workflows/ci.yml .github/workflows/release.yml
git diff --check
```
If Prettier does not parse the workflow format in this repo, inspect with `ruby -e "require 'yaml'; YAML.load_file(ARGV[0])" <file>` and record that command instead.
**Step 5: Commit**
```bash
git add .github/workflows/ci.yml .github/workflows/release.yml
git commit -s -m "ci: gate releases on clean dependency audits"
```
### Task 8: Audit and align the complete website documentation
**Skills:** `@writing-clearly-and-concisely`
**Files:**
- Review: every page under `website/src/content/docs/`
- Modify: `website/src/content/docs/guides/routing.md`
- Modify: `website/src/content/docs/reference/decorators.md`
- Modify: `website/src/content/docs/guides/openapi.md`
- Modify: any other website page whose API, behavior, example, or cross-link has drifted from the code
- Create: `website/src/content/docs/404.md`
**Step 1: Build a code-backed website documentation inventory**
Compare every website page with the current public exports in `src/index.ts`, app options and methods in `src/app/types.ts`, decorator metadata in `src/metadata.ts`, routing behavior in `src/http/router.ts`, and the executable tests. Search the whole documentation tree for stale method lists, obsolete limitations, old error semantics, old beta/version examples, broken internal links, and examples that no longer typecheck conceptually.
Do not change a claim from memory. Each correction must be supported by code or a passing test.
**Step 2: Update routing documentation from the verified behavior**
Document:
- `@Head` and `@Options`;
- explicit-route priority and automatic fallbacks;
- canonical `Allow` behavior;
- `/path` equals `/path/`;
- `//` and malformed encoding return `400`;
- catch-all must be final;
- `:id(\\d+)`, whole-segment matching, precedence, and the safe-subset restriction;
- the matcher remains linear and a radix tree remains deferred.
Remove the current statement that bare OPTIONS returns 405.
**Step 3: Align cross-cutting website references**
At minimum, verify and correct:
- every buffered-method list to include or intentionally exclude `HEAD`/`OPTIONS` according to the actual API;
- `405`, automatic `OPTIONS`, implicit `HEAD`, CORS-preflight, malformed-path, and security-header descriptions;
- OpenAPI behavior: explicit HEAD/OPTIONS appear as operations, constrained params produce `schema.pattern`, and automatic fallbacks remain absent;
- mesh route-conflict wording after effective-pattern normalization;
- examples and links between routing, decorators, errors, HTML, streaming, security, OpenAPI, and `createApp` reference pages;
- navigation/frontmatter descriptions that still advertise the old router surface.
Keep intentional historical or roadmap statements only when they remain true.
**Step 4: Fix the Starlight 404 warning**
Create the missing `404.md` entry with valid Starlight frontmatter and concise navigation back to the docs index. Run `npm run docs:build` and confirm the line `Entry docs → 404 was not found` disappears.
**Step 5: Validate the whole website documentation tree**
```bash
npm run docs:build
npm --prefix website audit
rg -n 'Not built|bare `OPTIONS`|returns `405`|@Get.*@Post.*@Put.*@Patch.*@Delete' website/src/content/docs
rg -n '\]\(/docs/' website/src/content/docs
git diff --check
```
Expected: all 23+ pages build without the missing-404 warning, the website audit remains clean, obsolete router claims are gone, and every changed claim has a code/test source.
**Step 6: Commit**
```bash
git add website/src/content/docs
git commit -s -m "docs(website): align guides with router behavior"
```
### Task 9: Align package documentation and prepare the August beta
**Skills:** `@writing-clearly-and-concisely`
**Files:**
- Modify: `README.md`
- Modify: `CHANGELOG.md`
- Modify: `src/index.ts`
- Modify: `package.json`
- Modify: `package-lock.json`
**Step 1: Align the package-facing documentation**
Update README routing, roadmap, method, security, and beta-status claims from the same verified behavior documented in the website. Keep README concise and link to the complete website guides rather than duplicating their full reference material.
**Step 2: Bump the beta version consistently**
Run:
```bash
npm version 26.8.0-beta.0 --no-git-tag-version
```
Update `src/index.ts`'s `VERSION` constant and add a `26.8.0-beta.0` CHANGELOG entry covering routes, security remediation, docs, and compatibility. Confirm README's CalVer examples remain accurate.
**Step 3: Verify docs and version consistency**
```bash
npm run docs:build
node -e "const p=require('./package.json'); const l=require('./package-lock.json'); if (p.version !== l.version || p.version !== l.packages[''].version) process.exit(1)"
rg -n '26\.7\.0-beta\.0|Not built|bare `OPTIONS`' README.md CHANGELOG.md src website/src/content/docs
git diff --check
```
Expected: package versions agree, website docs still build, and any old beta string is retained only in historical release examples.
**Step 4: Commit**
```bash
git add README.md CHANGELOG.md src/index.ts package.json package-lock.json
git commit -s -m "docs: document router completeness for beta"
```
### Task 10: Run the complete release-candidate verification
**Skills:** `@superpowers:verification-before-completion`, `@security-review`
**Files:**
- Modify only if a verification failure reveals an in-scope defect.
**Step 1: Run static and Node gates**
```bash
npm run lint
npm run format:check
npm run complexity:check
npm run typecheck
npm run typecheck:bench
npm test
npm run build
```
Expected: every command exits 0. Record the existing lint-warning count separately; introduce no new warnings.
**Step 2: Run multi-runtime gates**
```bash
npm run test:deno
npm run test:bun
npm run test:edge
```
Expected: every installed runtime suite exits 0. If a runtime is unavailable, report the exact missing command; do not claim that suite passed.
**Step 3: Run security, docs, and benchmark gates**
```bash
npm audit
npm audit --omit=dev
npm --prefix website audit
npm run docs:build
npm run bench
```
Expected: zero advisories; docs build without warning; all benchmark scenarios complete.
**Step 4: Inspect the publish artifact without publishing**
```bash
npm pack --dry-run
```
Expected: package contains `dist`, assets, README, CHANGELOG, and LICENSE; version is `26.8.0-beta.0`; no docs worktree, tests, secrets, or local environment files appear.
**Step 5: Review branch and workflow boundaries**
```bash
git status --short --branch
git log --oneline --decorate develop..HEAD
git diff --check develop...HEAD
git diff --stat develop...HEAD
```
Expected: clean `feat/router-security-beta`; all commits carry `Signed-off-by`; no tag, registry publication, `main` merge, or workflow secret change occurred.
**Step 6: Commit any verification-only repair**
Only if Step 1–5 exposed an in-scope defect:
```bash
git add <exact repaired files>
git commit -s -m "fix: address beta verification findings"
```
Re-run the failed gate and the complete related suite after any repair.
-522
View File
@@ -1,522 +0,0 @@
# green-tea — Quickstart
A type-safe HTTP framework where the request/boot pipeline is an explicit **dependency
graph**. You declare what you need; the framework computes the order, validates it at boot,
and can extend the graph over time (streams) and across machines (mesh).
See [architecture.md](./architecture.md) for the mental map.
## Install
```bash
npm install @green-tea/core reflect-metadata
# ws is an OPTIONAL peer dependency — only needed for WebSocket / mesh on Node:
npm install ws # optional
```
`tsconfig.json` must enable decorator metadata:
```jsonc
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"target": "es2017",
"module": "commonjs"
}
}
```
Import `reflect-metadata` once at your entrypoint.
## 1. A route with dependency injection
A **provider** is an app-scope singleton. A **step** runs per request and transforms the
context. A handler's **argument decorators are its dependency declaration** — ask for what
you want, in any order. If you `@needs` a token nothing produces, you get a **boot error**,
not an `undefined` at runtime.
```typescript
import 'reflect-metadata';
import { createApp, Provider, Step, Route, Get, Module, Unauthorized, needs, param } from '@green-tea/core';
@Provider({ provides: 'db' })
class Database {
provide() { return { db: { find: (id: string) => ({ id, name: 'Diego' }) } }; }
}
@Step({ provides: 'user', needs: ['db', 'req'] })
class Authenticate {
run(ctx: any) {
const user = ctx.db.find(ctx.req.headers['x-token']);
if (!user) throw new Unauthorized('bad token'); // throw = short-circuit the pipeline
return { user }; // return = continue, merge into ctx
}
}
@Route('/users')
class UserController {
@Get('/:id')
getUser(@needs('user') user: any, @param('id') id: string) {
return { requested: id, you: user }; // auto-serialized as JSON
}
}
@Module({ mountpoint: '/api', providers: [Database], steps: [Authenticate], controllers: [UserController] })
class ApiModule {}
const app = createApp({ modules: [ApiModule] });
await app.listen(3000);
// GET /api/users/9 (header x-token) → { "requested": "9", "you": { "id": "...", "name": "Diego" } }
await app.close(); // graceful shutdown: drains in-flight requests, closes streams + mesh links
```
> **Per-route execution (important).** Each route runs **only the providers/steps in the transitive
> closure of its handler's `@needs`** — nothing else. A route that doesn't `@needs('user')` does **not**
> run the `Authenticate` step. This means a cross-cutting *enforcement* step (e.g. auth that throws 401)
> only protects routes that actually `@needs` its token. To run something on **every** route regardless
> of needs (logging, audit, a global guard), add it as a **plugin step** via `scope.add({ ..., provides: [] })` —
> steps that produce nothing run unconditionally. Don't rely on a token-providing step to guard routes
> that don't declare it.
### Argument decorators
| Decorator | Reads from | Adds a graph dependency? |
|---|---|---|
| `@needs('user')` | a value produced by a provider/step | **yes** (boot-validated) |
| `@ctx()` | the whole accumulated context | no |
| `@param('id')` | route params | no |
| `@query('q')` | parsed query string | no |
| `@body()` | parsed JSON body | no |
| `@headers('x')` | request headers | no |
| `@inbound()` | the incoming WS message channel | no (WS only) |
| `@abort()` | an `AbortSignal` that fires on disconnect | no (stream/WS) |
Each envelope decorator has three forms: `@query()` (whole object), `@query('q')` (one key),
`@query(['q','date'])` (subset).
## 2. Compile-time guarantee with `flow`
The decorator layer validates the graph at boot. The functional core `flow` validates it in
the **type checker**:
```typescript
import { flow } from '@green-tea/core';
const pipeline = flow()
.step('db', () => ({ find: (id: string) => id }))
.step('user', (ctx) => ctx.db.find('u1')); // referencing a missing 'db' would not compile
```
## 3. Streaming — SSE
Return an `AsyncIterable` and the pipeline streams it (the transformer is bypassed; the
transport frames it, handles backpressure, and cleans up on disconnect).
```typescript
import { Route, Sse } from '@green-tea/core';
@Route('/feed')
class FeedController {
@Sse('/ticks')
ticks() {
return (async function* () {
for (let n = 1; n <= 3; n++) yield { tick: n };
})();
}
}
// GET /feed/ticks (Accept: text/event-stream)
// data: {"tick":1}
// data: {"tick":2}
// data: {"tick":3}
```
`@Stream(path)` negotiates the transport by header (`Accept: text/event-stream` → SSE,
`Upgrade: websocket` → WS, else ndjson chunked).
## 4. Streaming — WebSocket duplex
A WS handler receives the **inbound** channel and returns the **outbound** channel — a step
that consumes one channel and produces another.
```typescript
import { Route, Ws, inbound, channel } from '@green-tea/core';
@Route('/chat')
class ChatController {
@Ws('/echo')
echo(@inbound() incoming: AsyncIterable<string>) {
const out = channel<string>();
(async () => {
for await (const msg of incoming) out.push(`echo: ${msg}`);
out.close();
})();
return out;
}
}
```
`channel<T>()` is a multicast `AsyncIterable` with `push` / `close` / `fail` and an optional
bounded buffer (`channel({ buffer: 100 })`, drop-oldest).
## 5. Mesh — distributed dependency injection
A **teacup** can depend on a token that physically lives on a **teapot**. Exports are
opt-in (`export: true`) and the control channel is gated by a shared secret.
> ⚠️ **mesh is alpha** — its API and wire protocol may change. It's gated behind `experimental: true`;
> `createApp` throws if you pass `mesh` without it. Don't ship it to production yet.
**Node A — teapot (exposes `config`, `auth`, and a route):**
```typescript
@Provider({ provides: 'config', export: true })
class Config { provide() { return { config: { region: 'mx', tier: 'pro' } }; } }
@Step({ provides: 'auth', needs: [], export: true })
class Auth { run(ctx: any) { return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; } }
@Route('/svc')
class Svc { @Get('/ping', { export: true }) ping() { return { pong: true }; } }
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth], controllers: [Svc] })
class TeapotModule {}
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'shh' } });
await teapot.listen(3002);
```
**Node B — teacup (uses `config` + `auth` with no local providers):**
```typescript
@Route('/local')
class LocalCtl {
@Get('/who')
who(@needs('config') config: any, @needs('auth') auth: any) {
return { config, auth }; // both resolved by RPC to the teapot
}
}
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: 'ws://A-host:3002/__mesh__/control', secret: 'shh' }] },
});
await teacup.listen(3003);
// GET B:3003/api/local/who (x-token: abc)
// → { "config": { "region": "mx", "tier": "pro" }, "auth": { "token": "abc" } }
```
`@needs('config' | 'auth')` validates at boot because the teapot announced them in its
manifest on connect. A provider export is app-scope (resolved once, cached); a step export is
request-scope (RPC per request, carrying the request envelope).
> Skeleton limitations (by design): no discovery, load-balancing, or failover yet; app-scope
> remote values are not reconciled on reconnect; the request envelope omits `req.url`.
## 6. Plugins & observability
```typescript
const logger = (api: any) => {
api.bus.on('request:step:enter', (p: any) => console.log(`→ ${p.name}`));
api.bus.on('stream:open', (p: any) => console.log(`stream open ${p.name}`));
api.bus.on('mesh:rpc:error', (p: any) => console.error('mesh rpc failed', p.error));
};
const app = createApp({ modules: [ApiModule], plugins: [logger] });
```
Lifecycle events: `boot:provider:*`, `request:step:*`, `stream:open|close|error`,
`mesh:connect|disconnect|rpc:error`, `plugin:mounted`.
## 7. Transport security
Four `createApp` options cover TLS, proxying, CORS, and response headers.
### TLS (native https/wss)
```typescript
import { readFileSync } from 'fs';
const app = createApp({
modules: [App],
tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') },
});
```
When `tls` is set the server serves https, and WebSocket upgrades become wss on the same
port — no other changes.
### `trustProxy`
```typescript
const app = createApp({ modules: [App], trustProxy: true });
```
Behind a reverse proxy, reads `X-Forwarded-Proto` / `X-Forwarded-For` to populate
`ctx.protocol` (`'http' | 'https'`) and `ctx.ip` (read via `@ctx()`). Off by default —
forwarded headers are ignored (and spoofable) until you opt in. It trusts the immediate hop
unconditionally; there's no CIDR allowlist yet.
### CORS
Off unless `origins` is set.
```typescript
const app = createApp({
modules: [App],
cors: { origins: 'https://app.example.com', credentials: true },
});
```
`origins` accepts `string | string[] | '*' | (origin) => boolean`. A preflight `OPTIONS`
request (with `Access-Control-Request-Method`) is auto-answered with 204.
- With `credentials: true`, the server never sends `Access-Control-Allow-Origin: *` — it
echoes the concrete allowed origin (or blocks the request).
- **Security warning:** `origins: '*'` together with `credentials: true` reflects *any*
origin with credentials attached — the classic reflect-any foot-gun. Only combine them if
you truly intend an open credentialed API; prefer an explicit allowlist.
### `security` (headers, ON by default)
Applied to every HTTP response. Disable everything with `security: false`, or override
individual headers with an options object.
| Header | Default |
|---|---|
| `X-Content-Type-Options` | `nosniff` |
| `X-Frame-Options` | `SAMEORIGIN` |
| `Referrer-Policy` | `no-referrer` |
| `X-DNS-Prefetch-Control` | `off` |
| `Strict-Transport-Security` | `max-age=15552000` (180d) — **only when the connection is secure** (native TLS, or `trustProxy` + `X-Forwarded-Proto: https`); no `includeSubDomains`/`preload` |
| `Content-Security-Policy` | not set — pass `security: { csp: "..." }` |
```typescript
const app = createApp({ modules: [App], security: { csp: "default-src 'self'" } });
```
**Scope caveat:** `security` and `cors` headers apply to HTTP responses; they do not apply
to the WebSocket handshake (101/upgrade) response.
### Defaults
| Option | Default |
|---|---|
| `tls` | off (plain http/ws) |
| `trustProxy` | off |
| `cors` | off (same-origin only) |
| `security` | ON (HSTS only when the connection is secure) |
## 8. File uploads / multipart
> Multipart parsing uses the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency — install it with `npm i busboy`. A `multipart/form-data` request to a server without busboy installed returns `501`. (JSON and urlencoded need nothing extra.)
A request with `Content-Type: multipart/form-data` makes `@body()` resolve to `{ fields, files }`
instead of a plain object:
```typescript
import { Route, Post, body } from '@green-tea/core';
import type { MultipartBody } from '@green-tea/core';
@Route('/profile')
class ProfileController {
@Post('/avatar')
upload(@body() form: MultipartBody) {
const name = form.fields.name; // string | string[]
const avatar = form.files.avatar; // UploadedFile | UploadedFile[]
return { name, size: Array.isArray(avatar) ? undefined : avatar?.size };
}
}
```
`UploadedFile` is `{ filename, contentType, data: Buffer, size }` — the whole file is buffered
in memory, no temp files.
> **Access note (asymmetry).** For multipart, `@body('title')` returns `undefined` — the value
> lives at `body.fields.title`, not `body.title`, unlike JSON/urlencoded where `@body('title')`
> picks the value directly. Use `@body()` and read `.fields`/`.files`, or key into the envelope
> itself with `@body('fields')` / `@body('files')`.
### Repeated fields — `bodyDuplicates`
By default, a repeated field name keeps the **last** value (`'last'`, matching urlencoded).
Set `bodyDuplicates: 'array'` on `createApp` to accumulate repeats into a `string[]` instead —
this applies to **both** urlencoded and multipart text fields:
```typescript
const app = createApp({ modules: [ApiModule], bodyDuplicates: 'array' });
```
Files under a repeated field name always become an array (`UploadedFile[]`), regardless of
`bodyDuplicates`.
### Per-endpoint override
```typescript
@Post('/upload', { duplicates: 'array' })
upload(@body() form: MultipartBody) { /* ... */ }
```
Precedence: route `duplicates` → app `bodyDuplicates` → `'last'`.
### Limits
Uploaded files are held in memory, so they're bounded by the same `maxBodyBytes` limit as any
other request body (over the limit → 413). `maxParts` (default `1000`) caps the number of
multipart parts per request:
```typescript
const app = createApp({ modules: [ApiModule], limits: { maxParts: 500 } });
```
A malformed multipart body (bad boundary, missing headers, truncated part) → 400.
## 9. Validation
`@body`, `@query`, `@headers`, and `@param` accept an optional **Standard Schema**
(the [`~standard` interface](https://standardschema.dev) shared by zod, valibot, arktype,
and others). green-tea's core has **zero runtime dependency** on any of them — bring
whichever validator you already use:
```typescript
import { z } from 'zod';
import { Route, Post, body } from '@green-tea/core';
const CreateUser = z.object({ email: z.string().email() });
@Route('/users')
class UserController {
@Post('/')
create(@body(CreateUser) user: { email: string }) {
return { created: user.email };
}
}
```
The value the handler receives is the schema's **parsed/coerced output**, not the raw
input — `ctx.body` (via `@ctx()` or a `@needs`-fed step) stays exactly what the transport
parsed. Query strings are always strings on the wire, so a schema is often the coercion
point:
```typescript
const ListQuery = z.object({ page: z.coerce.number() });
@Get('/list')
list(@query(ListQuery) q: { page: number }) {
return { page: q.page, isNum: typeof q.page === 'number' }; // GET /list?page=2 → true
}
```
> **Access shape (asymmetry).** `@param('id', Schema)` takes the key in slot 1 and the schema
> in slot 2 — `@param` always needs a name to say which route param it binds. `@body(Schema)`,
> `@query(Schema)`, and `@headers(Schema)` take the schema as their only argument, validating
> the whole parsed object (all of `body`/`query`/`headers`).
A failing schema short-circuits the request with **422**:
```json
{ "error": "Validation failed", "source": "body", "issues": [{ "path": "email", "message": "Invalid email" }] }
```
`source` is which envelope failed (`'body' | 'query' | 'params' | 'headers'`); `issues` is
the schema's issues flattened to `{ path, message }` (`path` is dot-joined).
**Caveats:**
- **Fail-fast.** Arguments validate in order; the **first** failing one throws — later args in
the same handler are not checked in that request.
- **Steps see raw input.** Only the resolved handler argument is coerced/validated; a `@Step`
reading the same data via `ctx.body`/`ctx.query`/etc. always sees the untouched value.
- **A throwing schema is a 500, not a 422.** The Standard Schema contract says `validate()`
returns `{ issues }` on failure — it isn't supposed to throw. If it does anyway, that
propagates as an uncaught error (→ 500), since it signals a bug in the schema, not user input.
- **Async schemas are awaited** — `validate()` returning a `Promise` works transparently.
**Not covered yet:** response/output validation, validating a `@Step`'s own inputs, and
mesh remote-route validation are all out of scope for this feature.
## Inspect & test the graph
### Visualize with Mermaid
```typescript
console.log(app.toMermaid()); // flowchart diagram of all nodes and routes
```
Enable a live `GET /__graph__` endpoint (renders HTML with Mermaid, or plain-text with `Accept: text/plain`):
```typescript
const app = createApp({ modules: [ApiModule], devGraph: true });
// GET /__graph__ → HTML viewer
// GET /__graph__ (text/plain) → raw Mermaid source
```
### Explain a route
```typescript
const e = app.explain('/api/users/:id');
// { pattern, method, transport, chain: [{ name, kind, origin, needs, provides }, ...] }
console.log(e.chain.map((n) => `${n.kind}:${n.name}`));
// → ['provider:db', 'step:user', 'handler:getUser']
```
### Override tokens in tests
Swap any provider or step token with a test double at construction time — no monkey-patching:
```typescript
const app = createApp({
modules: [ApiModule],
overrides: {
db: { find: () => ({ id: 'test-user' }) }, // plain object — wrapped as { db: value }
user: () => ({ user: { id: 'stub' } }), // function runner
},
});
```
Overrides replace only the named token's runner; the rest of the graph is untouched.
## Runnable examples
The `example/` directory holds end-to-end apps you can `node`-run and read top to bottom.
### CRUD — methods, query, JSON & urlencoded body
`@Get/@Post/@Put/@Patch/@Delete` over a provider-backed store. Filter via `@query('done')`,
read the payload via `@body()` — the same handler accepts both `application/json` and
`application/x-www-form-urlencoded` (the transport parses each into a plain object). Missing
rows throw `NotFound` (→ 404).
See [`example/crud.ts`](../example/crud.ts).
### Chat — rooms + handshake auth
A `@Step` reads `?token=` and `provides: 'user'`, throwing `Unauthorized` on a missing token —
which closes the socket with code **4401** (`4000 + status`). The `@Ws` handler pumps the
`@inbound()` channel into `rooms.room(name)` and returns that same room as its outbound channel,
so every joined socket multicasts to the others. `rooms` is the built-in shared `Rooms`
primitive (one instance app-wide).
See [`example/chat.ts`](../example/chat.ts).
### GraphQL — query/mutation over POST, subscription over SSE
A schema built programmatically with `graphql` (a dev/example dependency — the core has no
runtime dep on it). `POST /graphql` runs queries and mutations through `graphql()`. The
`mutation` pushes each new message into `rooms.room('messages')`; the `@Sse('/stream')` route
calls `subscribe()` whose source **is** that room, guards the result with `isAsyncIterable`,
and returns it — the framework streams each `ExecutionResult` as an SSE `data:` frame. This is
the tie between GraphQL, green-tea streams, and the `rooms` primitive.
See [`example/graphql.ts`](../example/graphql.ts) — `npm install graphql` first.
## The one rule to remember
```
return a VALUE → buffered response (transformer → JSON)
return an AsyncIterable → stream (SSE / WS)
@needs a remote token → RPC to a teapot (mesh)
```
+1240 -1095
View File
File diff suppressed because it is too large. Load diff
+35 -16
View File
@@ -1,9 +1,17 @@
{ {
"name": "@green-tea/core", "name": "@green-tea/core",
"version": "26.7.0-beta.0", "version": "26.8.0-beta.0",
"description": "A zen, opinionated, type-safe framework — your API is a graph, not a middleware chain.", "description": "You declare what each step needs and provides; green-tea computes the execution order, fails at boot if something is missing, and prints the whole pipeline. HTTP, SSE and WebSocket on Node, Deno, Bun and the edge.",
"license": "MIT", "license": "MIT",
"author": "green-tea contributors", "author": "green-tea contributors",
"repository": {
"type": "git",
"url": "git+https://github.com/Expressive-Tea/green-tea.git"
},
"bugs": {
"url": "https://github.com/Expressive-Tea/green-tea/issues"
},
"homepage": "https://green-tea.expressive-tea.io/docs/",
"keywords": [ "keywords": [
"http", "http",
"framework", "framework",
@@ -79,7 +87,7 @@
"build": "tsup", "build": "tsup",
"test": "vitest run", "test": "vitest run",
"test:dev": "vitest", "test:dev": "vitest",
"test:deno": "deno test --allow-net --allow-read --no-check test/deno/", "test:deno": "deno test --allow-net --allow-read --allow-run --allow-env --no-check test/deno/",
"test:bun": "bun test test/bun/", "test:bun": "bun test test/bun/",
"test:edge": "tsx test/edge/run.ts", "test:edge": "tsx test/edge/run.ts",
"typecheck": "tsc --noEmit -p tsconfig.json", "typecheck": "tsc --noEmit -p tsconfig.json",
@@ -112,12 +120,21 @@
"optional": true "optional": true
} }
}, },
"overrides": {
"find-my-way": "9.7.0",
"autocannon": {
"hyperid": {
"uuid": "11.1.1"
}
},
"undici": "7.29.0"
},
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.39.4", "@eslint/js": "^9.39.5",
"@nestjs/common": "^11.1.27", "@nestjs/common": "^11.1.28",
"@nestjs/core": "^11.1.27", "@nestjs/core": "^11.1.28",
"@nestjs/platform-express": "^11.1.27", "@nestjs/platform-express": "^11.1.28",
"@nestjs/platform-fastify": "^11.1.27", "@nestjs/platform-fastify": "^11.1.28",
"@stylistic/eslint-plugin": "^5.10.0", "@stylistic/eslint-plugin": "^5.10.0",
"@types/autocannon": "^7.12.7", "@types/autocannon": "^7.12.7",
"@types/busboy": "^1.5.4", "@types/busboy": "^1.5.4",
@@ -127,18 +144,20 @@
"autocannon": "^8.0.0", "autocannon": "^8.0.0",
"busboy": "^1.6.0", "busboy": "^1.6.0",
"cognitive-complexity-ts": "^0.8.2", "cognitive-complexity-ts": "^0.8.2",
"eslint": "^9.39.4", "eslint": "^9.39.5",
"esbuild": "0.27.2",
"express": "^5.2.1", "express": "^5.2.1",
"fastify": "^5.10.0", "fastify": "^5.11.0",
"graphql": "^16.9.0", "graphql": "^16.9.0",
"miniflare": "^4.20260708.1", "miniflare": "^4.20260730.0",
"prettier": "^3.9.4", "prettier": "^3.9.6",
"rxjs": "^7.8.2", "rxjs": "^7.8.2",
"tsup": "^8.5.1", "tsup": "^8.5.1",
"tsx": "^4.23.0", "tsx": "^4.23.5",
"typescript": "^5.5.0", "typescript": "^5.5.0",
"typescript-eslint": "^8.63.0", "typescript-eslint": "^8.65.0",
"vitest": "^2.0.0", "vite": "^6.4.3",
"ws": "^8.21.0" "vitest": "^3.2.7",
"ws": "^8.21.1"
} }
} }
+235 -101
View File
@@ -3,11 +3,11 @@ import { Bus } from '../bus';
import { Container } from '../container'; import { Container } from '../container';
import { topoSort, subgraphFor, GraphNode, nearest } from '../graph'; import { topoSort, subgraphFor, GraphNode, nearest } from '../graph';
import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz'; import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz';
import { runPipeline, PipelineStep } from '../pipeline'; import { runPipeline, runSteps, PipelineStep } from '../pipeline';
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http'; import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
import type { HttpOptions } from '../http'; import type { HttpOptions } from '../http';
import { buildFetch } from '../http/web'; import { buildFetch } from '../http/web';
import { matchWsRoute, runWsConnection, type WsRequest, type WsSocket } from '../http/ws-core'; import { matchWsRoute, runWsConnection, trackUntil, type WsRequest, type WsSocket } from '../http/ws-core';
import { isAsyncIterable } from '../channel'; import { isAsyncIterable } from '../channel';
import { JsonTransformer, type ErrorRenderer } from '../transformers'; import { JsonTransformer, type ErrorRenderer } from '../transformers';
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin'; import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin';
@@ -30,11 +30,12 @@ import { connectLink, type Link } from '../mesh/link';
import { Rooms } from '../rooms'; import { Rooms } from '../rooms';
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security'; import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
import { buildRemote } from '../mesh/teacup'; import { buildRemote } from '../mesh/teacup';
import { buildManifest, createMeshControl } from '../mesh/teapot'; import { buildManifest, createMeshControl, MESH_CONTROL_PATH } from '../mesh/teapot';
import type { MeshControl } from '../http'; import type { MeshControl } from '../http';
import type { RequestEnvelope, RouteEntry } from '../mesh/protocol'; import type { RequestEnvelope, RouteEntry } from '../mesh/protocol';
import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types'; import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types';
import { inspectRoute, buildGraphView, explainRoute } from './introspect'; import { inspectRoute, buildGraphView, explainRoute } from './introspect';
import { compilePattern } from '../http/router';
export type { App, InspectLine, ExplainNode, Explain, MeshConfig } from './types'; export type { App, InspectLine, ExplainNode, Explain, MeshConfig } from './types';
@@ -53,6 +54,21 @@ interface Registry {
setRunner(name: string, runner: Runner): void; 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. */ /** Request-time helpers shared by the HTTP, WS and mesh route builders. */
interface PipelineDeps { interface PipelineDeps {
providedSeed(plan: RoutePlan): Promise<Record<string, unknown>>; providedSeed(plan: RoutePlan): Promise<Record<string, unknown>>;
@@ -89,6 +105,12 @@ export function createApp(opts: {
static?: boolean | string; static?: boolean | string;
/** Opt in to alpha features whose API may still change. Currently gates `mesh`. */ /** Opt in to alpha features whose API may still change. Currently gates `mesh`. */
experimental?: boolean; 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 { }): App {
// mesh is alpha: its API and wire protocol may change. Require an explicit opt-in. // mesh is alpha: its API and wire protocol may change. Require an explicit opt-in.
if (opts.mesh && !opts.experimental) { if (opts.mesh && !opts.experimental) {
@@ -112,18 +134,50 @@ export function createApp(opts: {
// For each route, resolve which providers/steps feed it via topo order. // 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. // MVP: every route depends on every declared step + provider in the app graph.
// For mesh apps, finalize is DEFERRED to listen() so remote scopes can join the graph first. // 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 orderedProviders: GraphNode[] = [];
let orderedSteps: GraphNode[] = []; let orderedSteps: GraphNode[] = [];
let booted = false; let booted = false;
let remoteRoutes: RouteDef[] = [];
const meshLinks: Link[] = [];
const finalize = (): void => { const finalize = (): void => {
({ orderedProviders, orderedSteps } = finalizeGraph(registry)); ({ orderedProviders, orderedSteps } = finalizeGraph(registry, opts.warnGraphDepth));
booted = true; booted = true;
}; };
if (!opts.mesh) finalize(); 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 inspect = (routePath: string): InspectLine[] => inspectRoute(routePlans, routePath, booted);
const graph = (): GraphView => buildGraphView(providerNodes, stepNodes, routePlans, booted); const graph = (): GraphView => buildGraphView(providerNodes, stepNodes, routePlans, booted);
const explain = (routePath: string): Explain => explainRoute(routePlans, routePath, booted); const explain = (routePath: string): Explain => explainRoute(routePlans, routePath, booted);
@@ -147,17 +201,15 @@ export function createApp(opts: {
return routes; return routes;
}; };
const providedSeed = (plan: RoutePlan) => seedProviders(container, plan); // Boots exactly once, however first triggered (app.fetch, app.upgrade or listen()); calling
const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan); // several never double-boots (which would re-run provider factories and their side effects).
const bootApp = makeAppBooter(
// Boots app-scope providers exactly once, however first triggered (app.fetch or listen()); calling
// both never double-boots (which would re-run provider factories and their side effects).
const bootAppProviders = makeProviderBooter(
registry, registry,
opts.overrides, opts.overrides,
() => orderedProviders, () => orderedProviders,
{ runners, container, providerMeta, bus }, { runners, container, providerMeta, bus },
degradedProviders, degradedProviders,
ready,
); );
const staticResolver = opts.static ? buildStaticResolver(opts.static) : undefined; const staticResolver = opts.static ? buildStaticResolver(opts.static) : undefined;
@@ -173,43 +225,21 @@ export function createApp(opts: {
static: staticResolver, static: staticResolver,
}; };
const fetchFn = buildAppFetch( const fetchFn = buildAppFetch(
() => booted,
routePlans, routePlans,
{ providedSeed, planSteps, bus, onError: opts.onError }, { providedSeed, planSteps, bus, onError: opts.onError },
fetchOpts, fetchOpts,
bootAppProviders, bootApp,
devRoutes, devRoutes,
() => remoteRoutes,
); );
const upgradeFn = buildAppUpgrade( const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl);
() => booted,
routePlans,
{ providedSeed, planSteps, bus, onError: opts.onError },
streams,
bootAppProviders,
);
const listen = async (port: number): Promise<http.Server> => { const listen = async (port: number): Promise<http.Server> => {
const deps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError }; const deps = pipelineDeps;
// mesh teacup: connect remote teapots, splice their scopes/routes into the graph, then finalize // the same gate app.fetch uses: splices remote mesh scopes, finalizes, boots providers,
let remoteRoutes: RouteDef[] = []; // and builds the mesh control channel — so Node and Deno/Bun serve an identical graph
const meshLinks: Link[] = []; await bootApp();
if (opts.mesh && !booted) {
const spliced = await spliceRemoteScopes(opts.mesh, bus, registry);
remoteRoutes = spliced.remoteRoutes;
meshLinks.push(...spliced.meshLinks);
finalize();
}
await bootAppProviders();
const meshControl = buildMeshControl(opts.mesh, registry, {
container,
orderedProviders,
orderedSteps,
deps,
});
const httpRoutes = [...buildHttpRoutes(routePlans, remoteRoutes, deps), ...devRoutes()]; const httpRoutes = [...buildHttpRoutes(routePlans, remoteRoutes, deps), ...devRoutes()];
const wsRoutes = buildWsRoutes(routePlans, deps); const wsRoutes = buildWsRoutes(routePlans, deps);
@@ -232,7 +262,13 @@ export function createApp(opts: {
const close = (): Promise<void> => const close = (): Promise<void> =>
new Promise<void>((resolve) => { 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(); if (!server) return resolve();
server.close(() => resolve()); // waits for in-flight buffered to drain 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 for (const closeStream of streams) closeStream(); // force-close long-lived SSE/WS so close() resolves
server.closeIdleConnections(); // Node >=18.2: drop idle keep-alive server.closeIdleConnections(); // Node >=18.2: drop idle keep-alive
@@ -241,6 +277,7 @@ export function createApp(opts: {
return { return {
listen, listen,
close, close,
ready,
fetch: fetchFn, fetch: fetchFn,
upgrade: upgradeFn, upgrade: upgradeFn,
inspect, inspect,
@@ -313,6 +350,7 @@ function collectControllers(
const instance: any = new ControllerClass(); const instance: any = new ControllerClass();
const argSpecs = getArgs(ControllerClass, route.handlerName); const argSpecs = getArgs(ControllerClass, route.handlerName);
const pattern = joinPath(mountpoint, route.path); const pattern = joinPath(mountpoint, route.path);
const declaration = `${ControllerClass.name}.${route.handlerName}`;
if (route.export) { if (route.export) {
if (route.transport !== 'buffer') throw new Error(`cannot export streaming route ${pattern}`); if (route.transport !== 'buffer') throw new Error(`cannot export streaming route ${pattern}`);
@@ -321,11 +359,12 @@ function collectControllers(
const transformer = resolveTransformer(ControllerClass, route, pattern, viewsCtx); const transformer = resolveTransformer(ControllerClass, route, pattern, viewsCtx);
registry.routePlans.push({ const plan: RoutePlan = {
pattern, pattern,
method: route.method, method: route.method,
transport: route.transport, transport: route.transport,
origin, origin,
declaration,
providers: [], providers: [],
steps: [], steps: [],
handlerName: route.handlerName, handlerName: route.handlerName,
@@ -336,11 +375,27 @@ function collectControllers(
maxBodyBytes: route.maxBodyBytes, maxBodyBytes: route.maxBodyBytes,
maxParts: route.maxParts, maxParts: route.maxParts,
args: argSpecs, args: argSpecs,
}); };
assertRouteAvailable(registry.routePlans, plan);
registry.routePlans.push(plan);
} }
} }
} }
/** Rejects local routes that have the same method and effective match shape. */
function assertRouteAvailable(existing: RoutePlan[], candidate: RoutePlan): void {
const compiled = compilePattern(candidate.pattern);
const conflict = existing.find(
(plan) => plan.method === candidate.method && compilePattern(plan.pattern).shape === compiled.shape,
);
if (!conflict) return;
throw new Error(
`ambiguous route ${candidate.method} ${candidate.pattern} at ${candidate.declaration} conflicts with ` +
`${conflict.method} ${conflict.pattern} at ${conflict.declaration}`,
);
}
/** /**
* Resolves the response transformer for a route: `@Html` metadata builds an HTML transformer (after * Resolves the response transformer for a route: `@Html` metadata builds an HTML transformer (after
* validating placement — buffered GET/POST only, and not combined with `@Transformer`); otherwise the * validating placement — buffered GET/POST only, and not combined with `@Transformer`); otherwise the
@@ -358,7 +413,7 @@ function resolveTransformer(
if (route.transport !== 'buffer' || (route.method !== 'GET' && route.method !== 'POST')) { if (route.transport !== 'buffer' || (route.method !== 'GET' && route.method !== 'POST')) {
throw new Error( throw new Error(
`@Html on ${route.method} ${pattern} is not allowed — @Html only supports buffered GET/POST routes (not SSE/WS/PUT/PATCH/DELETE)`, `@Html on ${route.method} ${pattern} is not allowed — @Html only supports buffered GET/POST routes (not SSE/WS/HEAD/PUT/PATCH/DELETE/OPTIONS)`,
); );
} }
@@ -407,11 +462,19 @@ function provideBuiltins(registry: Registry): void {
registry.setRunner('rooms', () => ({ rooms: roomsInstance })); // merge object -> ctx.rooms 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. * 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. * @returns The app-scope providers and request-scope steps in execution order.
*/ */
function finalizeGraph(registry: Registry): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } { function finalizeGraph(
registry: Registry,
warnDepth: number | false = DEEP_GRAPH_WARN,
): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } {
const { providerNodes, stepNodes, routePlans } = registry; const { providerNodes, stepNodes, routePlans } = registry;
const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params']); const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params']);
const orderedProviders = ordered.filter((node) => providerNodes.includes(node)); const orderedProviders = ordered.filter((node) => providerNodes.includes(node));
@@ -424,6 +487,17 @@ function finalizeGraph(registry: Registry): { orderedProviders: GraphNode[]; ord
plan.providers = closure.filter((node) => providerNodes.includes(node)); plan.providers = closure.filter((node) => providerNodes.includes(node));
const sliced = new Set<GraphNode>([...closure.filter((node) => stepNodes.includes(node)), ...alwaysSteps]); 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 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); assertNeedsSatisfiable(routePlans, providerNodes, stepNodes);
@@ -457,10 +531,17 @@ async function spliceRemoteScopes(
): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[] }> { ): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[] }> {
const remoteRoutes: RouteDef[] = []; const remoteRoutes: RouteDef[] = [];
const meshLinks: Link[] = []; const meshLinks: Link[] = [];
const routeOwners = new Map<string, { url: string; pattern: string }>(); // "METHOD effective-shape" -> owner
try { try {
for (const teapot of mesh.teapots ?? []) { for (const teapot of mesh.teapots ?? []) {
const link = await connectLink({ url: teapot.url, secret: teapot.secret, timeoutMs: mesh.timeoutMs, bus }); const link = await connectLink({
url: teapot.url,
secret: teapot.secret,
timeoutMs: mesh.timeoutMs,
heartbeatMs: mesh.heartbeatMs,
bus,
});
meshLinks.push(link); meshLinks.push(link);
const { providers, steps, routes } = buildRemote(link); const { providers, steps, routes } = buildRemote(link);
const origin = `mesh:${teapot.url}`; const origin = `mesh:${teapot.url}`;
@@ -477,6 +558,43 @@ async function spliceRemoteScopes(
} }
for (const route of routes) { for (const route of routes) {
const display = `${route.method} ${route.pattern}`;
const key = `${route.method} ${compilePattern(route.pattern).shape}`;
const owner = routeOwners.get(key);
// Fail the boot rather than pick one. Route matching keeps the first of two identical
// patterns, so the loser would be silently dead — and callers could come to depend on
// "first teapot wins", which would make adding balancing later a breaking change.
// Scope tokens already fail this way in setRunner; routes now match.
if (owner) {
throw new Error(
`mesh: ambiguous remote route '${display}' from ${teapot.url} conflicts with ` +
`'${route.method} ${owner.pattern}' from ${owner.url} — ` +
'load balancing across teapots is not implemented yet, so green-tea will not choose one for you. ' +
'Export it from a single teapot.',
);
}
routeOwners.set(key, { url: teapot.url, pattern: route.pattern });
// Local routes are merged ahead of remote ones (see buildHttpRoutes), so a local twin
// wins. That precedence is deliberate — your own code beats an imported one, and it is
// how you override a teapot — but silently shadowing an export looks exactly like a
// broken teapot from the outside. Warn and let the developer decide.
if (
registry.routePlans.some(
(plan) =>
plan.method === route.method &&
compilePattern(plan.pattern).shape === compilePattern(route.pattern).shape,
)
) {
console.warn(
`[green-tea] mesh: route '${display}' is exported by teapot ${teapot.url} but also declared locally — ` +
'the local route takes precedence and the remote one will not be reached. ' +
'Remove one if that is not what you meant.',
);
}
remoteRoutes.push({ remoteRoutes.push({
method: route.method, method: route.method,
pattern: route.pattern, pattern: route.pattern,
@@ -547,11 +665,13 @@ async function bootProviders(
} }
/** /**
* Returns a memoized boot function: applies overrides and boots app-scope providers exactly once, * Returns a memoized boot function: prepares the graph, applies overrides and boots app-scope
* however first triggered — {@link buildAppFetch}'s handler or `listen()` may both call it, and the * providers exactly once, however first triggered — `app.fetch`, `app.upgrade` and `listen()` may
* memoization guarantees only the first call actually runs (and warns about) the boot sequence. * 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 makeProviderBooter( function makeAppBooter(
registry: Registry, registry: Registry,
overrides: Record<string, unknown> | undefined, overrides: Record<string, unknown> | undefined,
getOrderedProviders: () => GraphNode[], getOrderedProviders: () => GraphNode[],
@@ -562,10 +682,11 @@ function makeProviderBooter(
bus: Bus; bus: Bus;
}, },
degradedProviders: string[], degradedProviders: string[],
/** Resolves the graph (splices remote mesh scopes, finalizes). Must precede providers: remote nodes join the topo sort. */
prepareGraph: () => Promise<void>,
): () => Promise<void> { ): () => Promise<void> {
let bootPromise: Promise<void> | undefined;
const runBoot = async (): Promise<void> => { const runBoot = async (): Promise<void> => {
await prepareGraph();
applyOverrides(overrides, registry); applyOverrides(overrides, registry);
degradedProviders.length = 0; degradedProviders.length = 0;
degradedProviders.push(...(await bootProviders(getOrderedProviders(), deps))); degradedProviders.push(...(await bootProviders(getOrderedProviders(), deps)));
@@ -577,10 +698,7 @@ function makeProviderBooter(
} }
}; };
return (): Promise<void> => { return once(runBoot);
if (!bootPromise) bootPromise = runBoot();
return bootPromise;
};
} }
/** /**
@@ -606,15 +724,13 @@ function buildMeshControl(
const resolveScope = async (name: string, env: RequestEnvelope): Promise<unknown> => { const resolveScope = async (name: string, env: RequestEnvelope): Promise<unknown> => {
// context is intentionally `any`: providers and steps merge arbitrary keys into it // context is intentionally `any`: providers and steps merge arbitrary keys into it
let context: any = { req: env, params: env.params, query: env.query, body: env.body, headers: env.headers }; const seed: any = { req: env, params: env.params, query: env.query, body: env.body, headers: env.headers };
for (const provider of orderedProviders) for (const provider of orderedProviders)
if (container.has(provider.name)) Object.assign(context, await container.resolve(provider.name)); if (container.has(provider.name)) Object.assign(seed, await container.resolve(provider.name));
for (const step of orderedSteps) { const steps = orderedSteps.map((step) => ({ name: step.name, origin: step.origin, run: runners.get(step.name)! }));
const runner = runners.get(step.name)!; const context = await runSteps(steps, seed, bus);
context = { ...context, ...(await runner(context)) };
}
return context[name]; return context[name];
}; };
@@ -693,29 +809,27 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps
/** /**
* Builds `app.fetch`: a Web-Standards handler over the same route table `listen()` uses, so * 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()`. * `Deno.serve(app.fetch)` / `Bun.serve({ fetch: app.fetch })` work without ever calling `listen()`.
* Non-mesh apps finalize eagerly, so `getBooted()` is already `true` and the route table is built * The boot is awaited *before* the route table is built: for a mesh app the table is not knowable
* on the very first call. Mesh apps defer finalize to `listen()` (remote scopes must splice into the * until remote scopes have spliced in, and the boot is what does that. Both are memoized, so this
* graph first): `getBooted` reads the outer `booted` flag *live* on every call — exactly like * costs one flag check per request after the first.
* `explain()`/`graph()`/`inspect()` do — so the returned function throws until `listen()` finalizes,
* then starts working from the next call on, without ever needing to be rebuilt.
*/ */
function buildAppFetch( function buildAppFetch(
getBooted: () => boolean,
routePlans: RoutePlan[], routePlans: RoutePlan[],
deps: PipelineDeps, deps: PipelineDeps,
fetchOpts: HttpOptions, fetchOpts: HttpOptions,
ensureBooted: () => Promise<void>, ensureBooted: () => Promise<void>,
devRoutes: () => RouteDef[], devRoutes: () => RouteDef[],
getRemoteRoutes: () => RouteDef[],
): (request: Request) => Promise<Response> { ): (request: Request) => Promise<Response> {
let handler: ((request: Request) => Promise<Response>) | undefined; let handler: ((request: Request) => Promise<Response>) | undefined;
return async (request: Request): Promise<Response> => { return async (request: Request): Promise<Response> => {
await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted
if (!handler) { if (!handler) {
if (!getBooted()) throw new Error('fetch() unavailable before listen() for mesh apps'); handler = buildFetch([...buildHttpRoutes(routePlans, getRemoteRoutes(), deps), ...devRoutes()], fetchOpts);
handler = buildFetch([...buildHttpRoutes(routePlans, [], deps), ...devRoutes()], fetchOpts);
} }
await ensureBooted(); // idempotent: no-op if listen() already booted the providers
return handler(request); return handler(request);
}; };
} }
@@ -724,35 +838,56 @@ function buildAppFetch(
* Builds `app.upgrade`: the neutral WebSocket entry over the same route table `listen()` uses, so * 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 * 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. * `server.on('upgrade')` path (see `attachWs`) and never calls this.
* Mirrors {@link buildAppFetch}'s finalize guard exactly: non-mesh apps finalize eagerly, so * Mirrors {@link buildAppFetch}: the boot is awaited before the ws route table is built.
* `getBooted()` is already `true` and the ws route table builds on the first call; mesh apps defer
* finalize to `listen()`, so this throws until `listen()` finalizes, then works from the next call on.
*/ */
function buildAppUpgrade( function buildAppUpgrade(
getBooted: () => boolean,
routePlans: RoutePlan[], routePlans: RoutePlan[],
deps: PipelineDeps, deps: PipelineDeps,
streams: Set<() => void>, streams: Set<() => void>,
ensureBooted: () => Promise<void>, ensureBooted: () => Promise<void>,
getMeshControl: () => MeshControl | undefined,
): (request: WsRequest, socket: WsSocket) => Promise<void> { ): (request: WsRequest, socket: WsSocket) => Promise<void> {
let wsRoutes: WsRouteDef[] | undefined; let wsRoutes: WsRouteDef[] | undefined;
return async (request: WsRequest, socket: WsSocket): Promise<void> => { return async (request: WsRequest, socket: WsSocket): Promise<void> => {
if (!wsRoutes) { // Subscribe to inbound BEFORE awaiting the boot. `channel` is fan-out: a frame pushed with no
if (!getBooted()) throw new Error('upgrade() unavailable before listen() for mesh apps'); // subscriber is dropped, so anything the peer sends while providers are still booting would be
wsRoutes = buildWsRoutes(routePlans, deps); // 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
await ensureBooted(); // idempotent: no-op if listen() already booted the providers
const path = request.url.split('?')[0]; const path = request.url.split('?')[0];
const route = matchWsRoute(wsRoutes, path); const meshControl = getMeshControl();
if (!route) { // The reserved mesh path, checked before route matching: this is what lets a teapot export
socket.close(1008, 'no matching ws route'); // 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; return;
} }
await runWsConnection(socket, request, route, deps.bus, streams); 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);
}; };
} }
@@ -788,7 +923,7 @@ function openApiRoute(openapi: () => unknown): RouteDef {
/** Compiles every ws/negotiate route plan into a WebSocket route that seeds context and runs its steps + handler. */ /** 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[] { function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[] {
const { providedSeed, planSteps } = deps; const { providedSeed, planSteps, bus } = deps;
return routePlans return routePlans
.filter((plan) => plan.transport === 'ws' || plan.transport === 'negotiate') .filter((plan) => plan.transport === 'ws' || plan.transport === 'negotiate')
@@ -798,23 +933,22 @@ function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[
const provided = await providedSeed(plan); const provided = await providedSeed(plan);
// ws upgrades carry the neutral WsRequest (protocol/ip pre-derived by the runtime adapter); // ws upgrades carry the neutral WsRequest (protocol/ip pre-derived by the runtime adapter);
// trustProxy derivation for ws is out of scope here // trustProxy derivation for ws is out of scope here
// context is intentionally `any`: each step merges arbitrary keys into it const context = await runSteps(
let context: any = { planSteps(plan),
...provided, {
req, ...provided,
params, req,
query: parseQuery(req.url ?? ''), params,
body: undefined, query: parseQuery(req.url ?? ''),
headers: req.headers, body: undefined,
inbound, headers: req.headers,
abort, inbound,
protocol: req.protocol, abort,
ip: req.ip, protocol: req.protocol,
}; ip: req.ip,
},
for (const step of planSteps(plan)) { bus,
context = { ...context, ...(await step.run(context)) }; );
}
const result = await plan.run(context); const result = await plan.run(context);
if (!isAsyncIterable(result)) throw new Error(`@Ws handler '${plan.handlerName}' must return an AsyncIterable`); if (!isAsyncIterable(result)) throw new Error(`@Ws handler '${plan.handlerName}' must return an AsyncIterable`);
+12 -3
View File
@@ -4,7 +4,10 @@ import type { InspectLine, Explain, ExplainNode, RoutePlan } from './types';
/** Lists the provider/step/handler chain for a route, in execution order. */ /** Lists the provider/step/handler chain for a route, in execution order. */
export function inspectRoute(routePlans: RoutePlan[], routePath: string, booted: boolean): InspectLine[] { export function inspectRoute(routePlans: RoutePlan[], routePath: string, booted: boolean): InspectLine[] {
if (!booted) throw new Error('inspect() unavailable before listen() for mesh apps'); 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); const plan = routePlans.find((candidate) => candidate.pattern === routePath);
if (!plan) throw new Error(`no route: ${routePath}`); if (!plan) throw new Error(`no route: ${routePath}`);
return [ return [
@@ -25,7 +28,10 @@ export function buildGraphView(
routePlans: RoutePlan[], routePlans: RoutePlan[],
booted: boolean, booted: boolean,
): GraphView { ): GraphView {
if (!booted) throw new Error('graph() unavailable before listen() for mesh apps'); 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 { return {
nodes: [ nodes: [
...providerNodes.map((node) => ({ ...providerNodes.map((node) => ({
@@ -54,7 +60,10 @@ export function buildGraphView(
/** Explains a single route: its match criteria and the ordered chain with each node's needs/provides. */ /** 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 { export function explainRoute(routePlans: RoutePlan[], routePath: string, booted: boolean): Explain {
if (!booted) throw new Error('explain() unavailable before listen() for mesh apps'); 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); const plan = routePlans.find((candidate) => candidate.pattern === routePath);
if (!plan) throw new Error(`no route: ${routePath}`); if (!plan) throw new Error(`no route: ${routePath}`);
const toExplainNode = (node: GraphNode, kind: 'provider' | 'step'): ExplainNode => ({ const toExplainNode = (node: GraphNode, kind: 'provider' | 'step'): ExplainNode => ({
+20
View File
@@ -36,6 +36,18 @@ export interface Explain {
export interface App { export interface App {
listen(port: number): Promise<http.Server>; listen(port: number): Promise<http.Server>;
close(): Promise<void>; 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. */ /** 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>; 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. */ /** Run a WebSocket upgrade through the graph using an adapter-provided socket (Deno/Bun/edge). Node uses its own listener path. */
@@ -58,6 +70,7 @@ export interface RoutePlan {
method: HttpMethod; method: HttpMethod;
transport: Transport; transport: Transport;
origin: string; origin: string;
declaration: string;
providers: GraphNode[]; providers: GraphNode[];
steps: GraphNode[]; steps: GraphNode[];
handlerName: string; handlerName: string;
@@ -74,5 +87,12 @@ export interface RoutePlan {
export interface MeshConfig { export interface MeshConfig {
secret?: string; secret?: string;
teapots?: Array<{ url: string; 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; 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;
} }
+14 -55
View File
@@ -2,6 +2,7 @@ import { channel } from './channel';
import type { Channel } from './channel'; import type { Channel } from './channel';
import type { App } from './app/types'; import type { App } from './app/types';
import type { WsSocket, WsRequest } from './http/ws-core'; 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. // Minimal ambient for the Bun globals we use — avoids a @types/bun devDep.
// Mirrors the real Bun.serve / server.upgrade / ServerWebSocket signatures we call. // Mirrors the real Bun.serve / server.upgrade / ServerWebSocket signatures we call.
@@ -33,8 +34,6 @@ interface BunServeOptions {
type BunServeShortOptions = { port?: number; hostname?: string }; type BunServeShortOptions = { port?: number; hostname?: string };
declare const Bun: { serve(options: BunServeOptions): BunServer }; declare const Bun: { serve(options: BunServeOptions): BunServer };
const decoder = new TextDecoder();
/** Per-connection state stashed on ws.data between fetch (upgrade) and the open/message/close callbacks. */ /** Per-connection state stashed on ws.data between fetch (upgrade) and the open/message/close callbacks. */
interface BunConnData { interface BunConnData {
wsReq: WsRequest; wsReq: WsRequest;
@@ -42,48 +41,15 @@ interface BunConnData {
ac: AbortController; ac: AbortController;
} }
/** Builds a neutral WsRequest from a Bun request + server (for the client IP). */ /**
function toWsRequest(request: Request, server: BunServer): WsRequest { * Wraps a Bun ServerWebSocket as a neutral WsSocket. Unlike Deno/edge, Bun delivers socket
const url = new URL(request.url); * events to a server-level handler rather than the socket, so the channel and abort are
const headers: Record<string, string> = {}; * created during the upgrade and stashed on ws.data — there is nothing here to wire up.
request.headers.forEach((v, k) => { */
headers[k] = v;
});
return {
url: url.pathname + url.search,
headers,
protocol: url.protocol === 'https:' ? 'https' : 'http',
ip: server.requestIP(request)?.address ?? '',
};
}
/** Wraps a Bun ServerWebSocket (+ its stashed channel/abort) as a neutral WsSocket. */
function bunSocket(ws: BunServerWebSocket): WsSocket { function bunSocket(ws: BunServerWebSocket): WsSocket {
const { inbound, ac } = ws.data as BunConnData; const { inbound, ac } = ws.data as BunConnData;
return {
inbound, return neutralSocket(ws, inbound, ac);
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: () => {
try {
(ws.terminate ?? ws.close).call(ws);
} catch {
/* already closed */
}
},
};
} }
/** /**
@@ -98,7 +64,8 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServer {
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
const inbound = channel(); const inbound = channel();
const ac = new AbortController(); const ac = new AbortController();
const data: BunConnData = { wsReq: toWsRequest(request, server), inbound, ac }; const wsReq = toWsRequest(request, server.requestIP(request)?.address ?? '');
const data: BunConnData = { wsReq, inbound, ac };
if (server.upgrade(request, { data })) return undefined; if (server.upgrade(request, { data })) return undefined;
return new Response('WebSocket upgrade failed', { status: 400 }); return new Response('WebSocket upgrade failed', { status: 400 });
} }
@@ -108,21 +75,13 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServer {
websocket: { websocket: {
open(ws) { open(ws) {
const { wsReq } = ws.data as BunConnData; const { wsReq } = ws.data as BunConnData;
// fire-and-forget: app.upgrade can reject before runWsConnection's try/catch
// (mesh-before-listen, provider boot failure); guard it or an uncaught rejection void upgradeSafely(app, wsReq, bunSocket(ws));
// could crash the Bun process.
void app.upgrade(wsReq, bunSocket(ws)).catch(() => {
try {
ws.close(1011, 'internal error');
} catch {
/* already closed */
}
});
}, },
message(ws, message) { message(ws, message) {
const { inbound } = ws.data as BunConnData; const { inbound } = ws.data as BunConnData;
// decode binary to UTF-8 to match Node's Buffer.toString() (cross-adapter parity)
inbound.push(typeof message === 'string' ? message : decoder.decode(message)); inbound.push(decodeMessage(message));
}, },
close(ws) { close(ws) {
const { inbound, ac } = ws.data as BunConnData; const { inbound, ac } = ws.data as BunConnData;
+8 -83
View File
@@ -1,23 +1,11 @@
import { channel } from './channel';
import type { App } from './app/types'; import type { App } from './app/types';
import type { WsSocket, WsRequest } from './http/ws-core'; 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) // 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 // doesn't declare a global `WebSocket` either — so we ambient-declare just the shape we use.
// (both the instance interface and the `OPEN` static, mirroring the real WebSocket). interface WebSocket extends EventfulSocket {
interface WebSocketEventMap {
message: { data: string | ArrayBuffer };
close: object;
error: object;
}
interface WebSocket {
readonly readyState: number;
binaryType: string; binaryType: string;
send(data: string): void;
close(code?: number, reason?: string): void;
addEventListener<K extends keyof WebSocketEventMap>(type: K, listener: (event: WebSocketEventMap[K]) => void): void;
} }
declare const WebSocket: { readonly OPEN: number };
// Minimal ambient for the Deno globals we use — avoids a @types/deno devDep. // Minimal ambient for the Deno globals we use — avoids a @types/deno devDep.
// Mirrors the real Deno.serve / Deno.upgradeWebSocket signatures we call. // Mirrors the real Deno.serve / Deno.upgradeWebSocket signatures we call.
@@ -40,63 +28,6 @@ declare const Deno: {
upgradeWebSocket(request: Request): { socket: WebSocket; response: Response }; upgradeWebSocket(request: Request): { socket: WebSocket; response: Response };
}; };
/** Builds a neutral WsRequest from a Deno upgrade Request + connection info. */
function toWsRequest(request: Request, info: DenoServeHandlerInfo): WsRequest {
const url = new URL(request.url);
const headers: Record<string, string> = {};
request.headers.forEach((v, k) => {
headers[k] = v;
});
return {
url: url.pathname + url.search,
headers,
protocol: url.protocol === 'https:' ? 'https' : 'http',
ip: info.remoteAddr.hostname,
};
}
/** Wraps a Deno/web WebSocket as a neutral WsSocket. */
function denoSocket(ws: WebSocket): WsSocket {
const inbound = channel<unknown>();
const ac = new AbortController();
ws.binaryType = 'arraybuffer';
const decoder = new TextDecoder();
ws.addEventListener('message', (e) => {
const data = e.data;
inbound.push(typeof data === 'string' ? data : decoder.decode(data as ArrayBuffer));
});
ws.addEventListener('close', () => {
inbound.close();
ac.abort();
});
ws.addEventListener('error', () => {
inbound.fail(new Error('websocket error'));
ac.abort();
});
return {
inbound,
abort: ac.signal,
get isOpen() {
return ws.readyState === WebSocket.OPEN;
},
send: (data) => ws.send(data),
close: (code, reason) => {
try {
ws.close(code, reason);
} catch {
/* already closed */
}
},
terminate: () => {
try {
ws.close();
} catch {
/* already closed */
}
},
};
}
/** /**
* Serve a Green Tea app on Deno: HTTP + SSE via app.fetch, WebSocket via Deno.upgradeWebSocket. * 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. * WebSocket messages flow through app.upgrade over the shared neutral core.
@@ -104,18 +35,12 @@ function denoSocket(ws: WebSocket): WsSocket {
export function serveDeno(app: App, options?: DenoServeOptions): DenoHttpServer { export function serveDeno(app: App, options?: DenoServeOptions): DenoHttpServer {
return Deno.serve(options ?? {}, (request, info) => { return Deno.serve(options ?? {}, (request, info) => {
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
// Deno invalidates request connection metadata as soon as the upgrade is accepted.
const wsRequest = toWsRequest(request, info.remoteAddr.hostname);
const { socket, response } = Deno.upgradeWebSocket(request); const { socket, response } = Deno.upgradeWebSocket(request);
// Fire-and-forget: the upgrade response must be returned synchronously while socket.binaryType = 'arraybuffer'; // deliver binary frames as ArrayBuffer, which decodeMessage expects
// the graph runs. app.upgrade can reject BEFORE runWsConnection's own try/catch // fire-and-forget: the 101 response must be returned synchronously while the graph runs
// (mesh-before-listen throw, or a provider boot failure), so guard the call here — void upgradeSafely(app, wsRequest, eventSocket(socket));
// an uncaught rejection would be fatal on Deno and crash the whole server.
void app.upgrade(toWsRequest(request, info), denoSocket(socket)).catch(() => {
try {
socket.close(1011, 'internal error');
} catch {
/* already closed */
}
});
return response; return response;
} }
+4 -76
View File
@@ -1,83 +1,16 @@
import { channel } from './channel';
import type { App } from './app/types'; import type { App } from './app/types';
import type { WsSocket, WsRequest } from './http/ws-core'; import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
// Minimal ambient for the Cloudflare Workers globals we use — avoids @cloudflare/workers-types. // Minimal ambient for the Cloudflare Workers globals we use — avoids @cloudflare/workers-types.
// Declares only what we call; mirrors the real workerd signatures. // Declares only what we call; mirrors the real workerd signatures.
interface EdgeWebSocket { interface EdgeWebSocket extends EventfulSocket {
accept(): void; accept(): void;
addEventListener(
type: 'message' | 'close' | 'error',
listener: (event: { data?: string | ArrayBuffer }) => void,
): void;
send(data: string): void;
close(code?: number, reason?: string): void;
readyState: number;
} }
interface EdgeCtx { interface EdgeCtx {
waitUntil(promise: Promise<unknown>): void; waitUntil(promise: Promise<unknown>): void;
} }
declare const WebSocketPair: { new (): { 0: EdgeWebSocket; 1: EdgeWebSocket } }; declare const WebSocketPair: { new (): { 0: EdgeWebSocket; 1: EdgeWebSocket } };
const decoder = new TextDecoder();
/** Builds a neutral WsRequest from a Cloudflare Worker request. */
function toWsRequest(request: Request): WsRequest {
const url = new URL(request.url);
const headers: Record<string, string> = {};
request.headers.forEach((v, k) => {
headers[k] = v;
});
return {
url: url.pathname + url.search,
headers,
protocol: url.protocol === 'https:' ? 'https' : 'http',
ip: request.headers.get('cf-connecting-ip') ?? '',
};
}
/** Wraps a Cloudflare server-side WebSocket (already accept()ed) as a neutral WsSocket. */
function edgeSocket(server: EdgeWebSocket): WsSocket {
const inbound = channel();
const ac = new AbortController();
server.addEventListener('message', (event) => {
const data = event.data;
inbound.push(typeof data === 'string' ? data : decoder.decode(data as ArrayBuffer));
});
server.addEventListener('close', () => {
inbound.close();
ac.abort();
});
server.addEventListener('error', () => {
inbound.fail(new Error('websocket error'));
ac.abort();
});
return {
inbound,
abort: ac.signal,
get isOpen() {
return server.readyState === 1; // 1 = OPEN
},
send: (data) => {
server.send(data);
},
close: (code, reason) => {
try {
server.close(code, reason);
} catch {
/* already closed */
}
},
terminate: () => {
try {
server.close();
} catch {
/* already closed */
}
},
};
}
/** /**
* Cloudflare Workers / edge handler: HTTP + SSE via app.fetch, WebSocket via WebSocketPair. * Cloudflare Workers / edge handler: HTTP + SSE via app.fetch, WebSocket via WebSocketPair.
* Use as `export default { fetch: edgeHandler(app) }`. Requires the `nodejs_compat` * Use as `export default { fetch: edgeHandler(app) }`. Requires the `nodejs_compat`
@@ -90,13 +23,8 @@ export function edgeHandler(
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
const [client, server] = Object.values(new WebSocketPair()) as [EdgeWebSocket, EdgeWebSocket]; const [client, server] = Object.values(new WebSocketPair()) as [EdgeWebSocket, EdgeWebSocket];
server.accept(); server.accept();
const lifecycle = app.upgrade(toWsRequest(request), edgeSocket(server)).catch(() => { const wsReq = toWsRequest(request, request.headers.get('cf-connecting-ip') ?? '');
try { const lifecycle = upgradeSafely(app, wsReq, eventSocket(server));
server.close(1011, 'internal error');
} catch {
/* already closed */
}
});
if (ctx?.waitUntil) ctx.waitUntil(lifecycle); if (ctx?.waitUntil) ctx.waitUntil(lifecycle);
else void lifecycle; else void lifecycle;
+74 -24
View File
@@ -3,7 +3,7 @@ import { HttpError, NotFound } from '../signals';
import { renderError } from '../transformers'; import { renderError } from '../transformers';
import { isStreamResult, type PipelineResult } from '../pipeline'; import { isStreamResult, type PipelineResult } from '../pipeline';
import { buildSecurityHeaders, resolveCors, corsPreflightHeaders } from '../security'; import { buildSecurityHeaders, resolveCors, corsPreflightHeaders } from '../security';
import { matchRoute, allowedMethods, parseQuery } from './router'; import { resolveRoute, allowedMethods, normalizeRequestPath, parseQuery } from './router';
import { pickEncoder } from './stream'; import { pickEncoder } from './stream';
import type { RouteDef, HttpOptions } from './types'; import type { RouteDef, HttpOptions } from './types';
import type { StreamEncoder } from '../encoders'; import type { StreamEncoder } from '../encoders';
@@ -49,6 +49,61 @@ export function computeInjected(
return injected; return injected;
} }
function errorOutcome(
error: unknown,
req: NeutralRequest,
injected: Record<string, string>,
opts: HttpOptions | undefined,
headers: Record<string, string> = {},
): HandleResult {
const rendered = renderError(error, { method: req.method, url: req.url, headers: req.headers }, opts?.onError);
return {
injected,
outcome: {
kind: 'buffered',
status: rendered.status,
headers: { ...rendered.headers, ...headers },
body: req.method === 'HEAD' ? '' : rendered.body,
},
};
}
async function unmatchedOutcome(
routes: RouteDef[],
opts: HttpOptions | undefined,
req: NeutralRequest,
path: string,
injected: Record<string, string>,
): Promise<HandleResult> {
if ((req.method === 'GET' || req.method === 'HEAD') && opts?.static) {
const hit = await opts.static(path);
if (hit) {
return {
injected,
outcome: {
kind: 'buffered',
status: 200,
headers: { 'content-type': hit.contentType },
body: req.method === 'HEAD' ? '' : hit.body,
},
};
}
}
const allow = allowedMethods(routes, path);
if (req.method === 'OPTIONS' && allow.length) {
return {
injected,
outcome: { kind: 'buffered', status: 204, headers: { allow: allow.join(', ') }, body: '' },
};
}
const error = allow.length ? new HttpError(405, 'Method Not Allowed') : new NotFound('Not Found');
return errorOutcome(error, req, injected, opts, allow.length ? { allow: allow.join(', ') } : {});
}
/** /**
* Runtime-neutral request handler: security/CORS headers, preflight short-circuit, route match / 404 / 405, * Runtime-neutral request handler: security/CORS headers, preflight short-circuit, route match / 404 / 405,
* route-handler invocation with error rendering, and the buffered-vs-stream decision. Does no I/O — the * route-handler invocation with error rendering, and the buffered-vs-stream decision. Does no I/O — the
@@ -59,35 +114,22 @@ export async function handle(
opts: HttpOptions | undefined, opts: HttpOptions | undefined,
req: NeutralRequest, req: NeutralRequest,
): Promise<HandleResult | Preflight> { ): Promise<HandleResult | Preflight> {
const path = req.url.split('?')[0];
const injected = computeInjected(opts, req); const injected = computeInjected(opts, req);
let path: string;
try {
path = normalizeRequestPath(req.url.split('?')[0]);
} catch {
return errorOutcome(new HttpError(400, 'Bad Request'), req, injected, opts);
}
if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) { if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) {
return { preflight: corsPreflightHeaders(opts.cors, req) }; return { preflight: corsPreflightHeaders(opts.cors, req) };
} }
const matched = matchRoute(routes, req.method, path); const matched = resolveRoute(routes, req.method, path);
if (!matched) { if (!matched) return unmatchedOutcome(routes, opts, req, path, injected);
if ((req.method === 'GET' || req.method === 'HEAD') && opts?.static) {
const hit = await opts.static(path);
if (hit) {
const body = req.method === 'HEAD' ? '' : hit.body;
return {
injected,
outcome: { kind: 'buffered', status: 200, headers: { 'content-type': hit.contentType }, body },
};
}
}
// Path matches a route under a different method → 405 with Allow; otherwise 404.
const allow = allowedMethods(routes, path);
const err = allow.length ? new HttpError(405, 'Method Not Allowed') : new NotFound('Not Found');
const rendered = renderError(err, { method: req.method, url: req.url, headers: req.headers }, opts?.onError);
const headers = allow.length ? { ...rendered.headers, allow: allow.join(', ') } : rendered.headers;
return { injected, outcome: { kind: 'buffered', status: rendered.status, headers, body: rendered.body } };
}
let result: PipelineResult; let result: PipelineResult;
@@ -111,5 +153,13 @@ export async function handle(
return { injected, outcome: { kind: 'stream', headers: encoder.headers, stream: result.stream, encoder } }; return { injected, outcome: { kind: 'stream', headers: encoder.headers, stream: result.stream, encoder } };
} }
return { injected, outcome: { kind: 'buffered', status: result.status, headers: result.headers, body: result.body } }; return {
injected,
outcome: {
kind: 'buffered',
status: result.status,
headers: result.headers,
body: req.method === 'HEAD' ? '' : result.body,
},
};
} }
+242 -36
View File
@@ -1,63 +1,236 @@
import type { RouteDef, MatchedRoute } from './types'; import type { RouteDef, MatchedRoute } from './types';
/** export type CompiledSegment =
* Matches a route pattern against a request path. Supports static segments, `:param` (one segment), | { kind: 'static'; value: string }
* and a trailing `:name*` catch-all that captures the rest of the path (slashes included) into `params.name`. | { kind: 'param'; name: string; constraint?: RegExp; constraintSource?: string }
* @returns Extracted params (decoded) when the path matches, otherwise undefined. | { kind: 'catchAll'; name: string };
*/
export function matchPattern(pattern: string, path: string): Record<string, string> | undefined { /** Parsed route pattern reused by matching, specificity, ambiguity checks, and OpenAPI projection. */
export interface CompiledPattern {
source: string;
normalized: string;
shape: string;
segments: CompiledSegment[];
kinds: number[];
catchAll: boolean;
}
const compiledCache = new Map<string, CompiledPattern>();
const PARAM_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
const MAX_CONSTRAINT_LENGTH = 128;
/** Request-path syntax error. Adapters translate this to the standard 400 response envelope. */
export class InvalidRequestPathError extends Error {
constructor(message: string) {
super(message);
this.name = 'InvalidRequestPathError';
}
}
interface ConstraintToken {
length: number;
unbounded: boolean;
separator: boolean;
}
/** Reads one atom plus its optional quantifier from the deliberately small safe-regex subset. */
function readConstraintToken(source: string): ConstraintToken | undefined {
const atom = /^(?:\\[dDsSwW]|\\[.\-_/]|[A-Za-z0-9_.-]|\[(?:\\.|[^\]\\])+\])/u.exec(source)?.[0];
if (!atom) return undefined;
const rest = source.slice(atom.length);
const quantifier = /^(?:[+*?]|\{\d+(?:,\d*)?\})/u.exec(rest)?.[0] ?? '';
if (quantifier.startsWith('{')) assertBoundedQuantifier(quantifier);
return {
length: atom.length + quantifier.length,
unbounded: quantifier === '+' || quantifier === '*' || quantifier.endsWith(',}'),
separator: quantifier === '' && /^(?:\\[.\-_/]|[._-])$/u.test(atom),
};
}
/** Rejects nonsensical or excessively large counted quantifiers before RegExp compilation. */
function assertBoundedQuantifier(quantifier: string): void {
const [minText, maxText] = quantifier.slice(1, -1).split(',');
const min = Number(minText);
const max = maxText === undefined || maxText === '' ? min : Number(maxText);
if (min > max || max > 2048) throw new Error(`unsafe route constraint: invalid quantifier '${quantifier}'`);
}
/** Accepts only a linear, group-free regex subset to keep attacker-controlled segments ReDoS-safe. */
function assertSafeConstraint(source: string): void {
if (!source || source.length > MAX_CONSTRAINT_LENGTH)
throw new Error('unsafe route constraint: expression must contain 1-128 characters');
let offset = 0;
let previousUnbounded = false;
while (offset < source.length) {
const token = readConstraintToken(source.slice(offset));
if (!token) throw new Error(`unsafe route constraint: unsupported expression '${source}'`);
if (previousUnbounded && token.unbounded)
throw new Error(`unsafe route constraint: adjacent unbounded quantifiers in '${source}'`);
previousUnbounded = token.separator ? false : token.unbounded;
offset += token.length;
}
}
function assertParamName(name: string, pattern: string): void {
if (!PARAM_NAME.test(name)) throw new Error(`invalid route pattern '${pattern}': invalid parameter name '${name}'`);
}
function compileParam(segment: string, pattern: string): Extract<CompiledSegment, { kind: 'param' }> {
const constraintStart = segment.indexOf('(');
if (constraintStart < 0) {
const name = segment.slice(1);
assertParamName(name, pattern);
return { kind: 'param', name };
}
if (!segment.endsWith(')')) throw new Error(`invalid route pattern '${pattern}': malformed constraint`);
const name = segment.slice(1, constraintStart);
const constraintSource = segment.slice(constraintStart + 1, -1);
assertParamName(name, pattern);
assertSafeConstraint(constraintSource);
return {
kind: 'param',
name,
constraintSource,
constraint: new RegExp(`^(?:${constraintSource})$`, 'u'),
};
}
function compileSegments(pattern: string, rawSegments: string[]): CompiledSegment[] {
const names = new Set<string>();
const compiled: CompiledSegment[] = [];
for (let index = 0; index < rawSegments.length; index++) {
const raw = rawSegments[index];
let segment: CompiledSegment;
if (raw.startsWith(':') && raw.endsWith('*')) {
const name = raw.slice(1, -1);
assertParamName(name, pattern);
if (index !== rawSegments.length - 1)
throw new Error(`invalid route pattern '${pattern}': catch-all must be the final segment`);
segment = { kind: 'catchAll', name };
} else if (raw.startsWith(':')) {
segment = compileParam(raw, pattern);
} else {
segment = { kind: 'static', value: raw };
}
if (segment.kind !== 'static') {
if (names.has(segment.name))
throw new Error(`invalid route pattern '${pattern}': duplicate parameter '${segment.name}'`);
names.add(segment.name);
}
compiled.push(segment);
}
return compiled;
}
function segmentShape(segment: CompiledSegment): string {
if (segment.kind === 'static') return `s:${segment.value}`;
if (segment.kind === 'catchAll') return 'c';
return segment.constraintSource ? `r:${segment.constraintSource}` : 'p';
}
/** Compiles and validates one route pattern. Results are cached by source string. */
export function compilePattern(pattern: string): CompiledPattern {
const cached = compiledCache.get(pattern);
if (cached) return cached;
if (!pattern.startsWith('/')) throw new Error(`invalid route pattern '${pattern}': pattern must start with '/'`);
if (pattern.includes('//')) throw new Error(`invalid route pattern '${pattern}': repeated slash`);
const normalized = pattern.length > 1 && pattern.endsWith('/') ? pattern.slice(0, -1) : pattern;
const rawSegments = normalized === '/' ? [] : normalized.split('/').slice(1);
const segments = compileSegments(pattern, rawSegments);
const compiled: CompiledPattern = {
source: pattern,
normalized,
shape: segments.map(segmentShape).join('/'),
segments,
kinds: segments
.filter((segment) => segment.kind !== 'catchAll')
.map((segment) => (segment.kind === 'static' ? 3 : segment.constraint ? 2 : 1)),
catchAll: segments.at(-1)?.kind === 'catchAll',
};
compiledCache.set(pattern, compiled);
return compiled;
}
/** Applies the public trailing-slash policy and validates every segment's percent encoding. */
export function normalizeRequestPath(path: string): string {
if (!path.startsWith('/')) throw new InvalidRequestPathError('invalid request path: path must start with slash');
if (path.includes('//')) throw new InvalidRequestPathError('invalid request path: repeated slash');
const normalized = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;
try {
for (const segment of normalized.split('/').slice(1)) decodeURIComponent(segment);
} catch {
throw new InvalidRequestPathError('invalid request path: malformed path encoding');
}
return normalized;
}
function decodeSegment(value: string): string {
return decodeURIComponent(value);
}
function matchCompiled(compiled: CompiledPattern, path: string): Record<string, string> | undefined {
const pathSegs = path.split('/').filter(Boolean); const pathSegs = path.split('/').filter(Boolean);
const patternSegs = pattern.split('/').filter(Boolean);
const params: Record<string, string> = {}; const params: Record<string, string> = {};
for (let i = 0; i < patternSegs.length; i++) { for (let index = 0; index < compiled.segments.length; index++) {
const seg = patternSegs[i]; const segment = compiled.segments[index];
// Trailing catch-all: capture every remaining segment (possibly none) as one decoded value. if (segment.kind === 'catchAll') {
if (seg.startsWith(':') && seg.endsWith('*')) { params[segment.name] = pathSegs.slice(index).map(decodeSegment).join('/');
params[seg.slice(1, -1)] = pathSegs.slice(i).map(decodeURIComponent).join('/');
return params; return params;
} }
if (i >= pathSegs.length) return undefined; // pattern longer than path if (index >= pathSegs.length) return undefined;
if (seg.startsWith(':')) params[seg.slice(1)] = decodeURIComponent(pathSegs[i]); if (segment.kind === 'static') {
else if (seg !== pathSegs[i]) return undefined; if (segment.value !== pathSegs[index]) return undefined;
continue;
}
const value = decodeSegment(pathSegs[index]);
if (segment.constraint && !segment.constraint.test(value)) return undefined;
params[segment.name] = value;
} }
// No catch-all consumed the tail, so the lengths must match exactly. return compiled.segments.length === pathSegs.length ? params : undefined;
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. */ /** Matches a compiled segment pattern and returns its decoded parameters. */
function segScores(pattern: string): { catchAll: boolean; kinds: number[] } { export function matchPattern(pattern: string, path: string): Record<string, string> | undefined {
const kinds: number[] = []; return matchCompiled(compilePattern(pattern), path);
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. */ /** Orders matching patterns by exactness, then static/constrained/plain segment specificity. */
function moreSpecific(a: string, b: string): number { function moreSpecific(a: string, b: string): number {
const scoreA = segScores(a); const scoreA = compilePattern(a);
const scoreB = segScores(b); const scoreB = compilePattern(b);
if (scoreA.catchAll !== scoreB.catchAll) return scoreA.catchAll ? -1 : 1; if (scoreA.catchAll !== scoreB.catchAll) return scoreA.catchAll ? -1 : 1;
const length = Math.max(scoreA.kinds.length, scoreB.kinds.length); const length = Math.max(scoreA.kinds.length, scoreB.kinds.length);
for (let i = 0; i < length; i++) { for (let index = 0; index < length; index++) {
const kindA = scoreA.kinds[i] ?? -1; const kindA = scoreA.kinds[index] ?? -1;
const kindB = scoreB.kinds[i] ?? -1; const kindB = scoreB.kinds[index] ?? -1;
if (kindA !== kindB) return kindA - kindB; if (kindA !== kindB) return kindA - kindB;
} }
return 0; return 0;
} }
/** Finds the most specific route matching both method and path (static > param > catch-all; ties keep registration order). */ /** Finds the most specific route matching both method and path; ties keep registration order. */
export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined { export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined {
let best: MatchedRoute | undefined; let best: MatchedRoute | undefined;
let bestPattern = ''; let bestPattern = '';
@@ -76,11 +249,44 @@ export function matchRoute(routes: RouteDef[], method: string, path: string): Ma
return best; return best;
} }
/** Route resolution adds the one HTTP fallback the matcher supports: buffered GET serves HEAD. */
export interface ResolvedRoute extends MatchedRoute {
implicitHead: boolean;
}
export function resolveRoute(routes: RouteDef[], method: string, path: string): ResolvedRoute | undefined {
const explicit = matchRoute(routes, method, path);
if (explicit) return { ...explicit, implicitHead: false };
if (method !== 'HEAD') return undefined;
const fallback = matchRoute(
routes.filter((route) => route.transport === 'buffer'),
'GET',
path,
);
return fallback ? { ...fallback, implicitHead: true } : undefined;
}
const METHOD_ORDER = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
/** Lists the distinct HTTP methods whose pattern matches the path — used to build a 405 `Allow` header. */ /** Lists the distinct HTTP methods whose pattern matches the path — used to build a 405 `Allow` header. */
export function allowedMethods(routes: RouteDef[], path: string): string[] { export function allowedMethods(routes: RouteDef[], path: string): string[] {
const methods = new Set<string>(); const methods = new Set<string>();
for (const route of routes) if (matchPattern(route.pattern, path)) methods.add(route.method);
return [...methods]; for (const route of routes) {
if (!matchPattern(route.pattern, path)) continue;
methods.add(route.method);
if (route.method === 'GET' && route.transport === 'buffer') methods.add('HEAD');
}
if (methods.size) methods.add('OPTIONS');
return [...methods].sort((a, b) => {
const indexA = METHOD_ORDER.indexOf(a);
const indexB = METHOD_ORDER.indexOf(b);
return (
(indexA < 0 ? METHOD_ORDER.length : indexA) - (indexB < 0 ? METHOD_ORDER.length : indexB) || a.localeCompare(b)
);
});
} }
/** Parses a URL's query string into a flat string map (last value wins for repeated keys). */ /** Parses a URL's query string into a flat string map (last value wins for repeated keys). */
+8 -2
View File
@@ -5,7 +5,7 @@ import { isHttpError, HttpError } from '../signals';
import type { Bus } from '../bus'; import type { Bus } from '../bus';
import { buildSecurityHeaders, resolveCors } from '../security'; import { buildSecurityHeaders, resolveCors } from '../security';
import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart'; import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart';
import { matchRoute } from './router'; import { normalizeRequestPath, resolveRoute } from './router';
import { readBody, deriveSecure, deriveIp } from './request'; import { readBody, deriveSecure, deriveIp } from './request';
import { pipeStream } from './stream'; import { pipeStream } from './stream';
import { attachWs } from './ws'; import { attachWs } from './ws';
@@ -93,7 +93,13 @@ function createRequestHandler(cfg: HandlerConfig) {
// Mirror handle()'s own preflight/route-match decision here, so we only read the body // Mirror handle()'s own preflight/route-match decision here, so we only read the body
// (below) for a request that actually reaches a route handler — matching prior behaviour. // (below) for a request that actually reaches a route handler — matching prior behaviour.
const isPreflight = Boolean(opts?.cors && method === 'OPTIONS' && req.headers['access-control-request-method']); const isPreflight = Boolean(opts?.cors && method === 'OPTIONS' && req.headers['access-control-request-method']);
const matched = isPreflight ? undefined : matchRoute(routes, method, path); let matched: ReturnType<typeof resolveRoute>;
try {
matched = isPreflight ? undefined : resolveRoute(routes, method, normalizeRequestPath(path));
} catch {
matched = undefined; // handle() owns the standard 400 envelope and injected headers
}
let body: unknown; let body: unknown;
+18 -4
View File
@@ -6,11 +6,25 @@ import type { Bus } from '../bus';
const PING_MS = 15_000; const PING_MS = 15_000;
/** Selects the stream encoder for a transport, falling back to the client's `Accept` header for `stream`. */ /**
* 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 { export function pickEncoder(transport: Transport, accept: string): StreamEncoder {
if (transport === 'sse') return sseEncoder; const pick = STREAM_ENCODERS[transport];
if (transport === 'ndjson') return ndjsonEncoder; if (!pick) throw new Error(`transport '${transport}' does not produce an HTTP stream`);
return accept.includes('text/event-stream') ? sseEncoder : ndjsonEncoder;
return pick(accept);
} }
/** Pipes an async-iterable result to the response as an HTTP stream, with keep-alive pings and backpressure handling. */ /** Pipes an async-iterable result to the response as an HTTP stream, with keep-alive pings and backpressure handling. */
+7 -3
View File
@@ -1,9 +1,8 @@
import type http from 'http';
import type { Transport } from '../metadata'; import type { Transport } from '../metadata';
import type { PipelineResult } from '../pipeline'; import type { PipelineResult } from '../pipeline';
import type { ErrorRenderer } from '../transformers'; import type { ErrorRenderer } from '../transformers';
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security'; import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
import type { WsRequest } from './ws-core'; import type { WsRequest, WsSocket } from './ws-core';
import type { StaticResolver } from '../views'; import type { StaticResolver } from '../views';
/** Per-request size and timeout ceilings applied by the server. */ /** Per-request size and timeout ceilings applied by the server. */
@@ -74,5 +73,10 @@ export interface WsRouteDef {
/** Hook for a mesh gateway to take over WebSocket upgrades on a fixed path. */ /** Hook for a mesh gateway to take over WebSocket upgrades on a fixed path. */
export interface MeshControl { export interface MeshControl {
path: string; path: string;
handle(ws: any, req: http.IncomingMessage): void; /**
* 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>;
} }
+11 -3
View File
@@ -2,7 +2,7 @@ import type { StreamEncoder } from '../encoders';
import { handle, computeInjected, type HandleResult } from './core'; import { handle, computeInjected, type HandleResult } from './core';
import { mergeInjectedHeaders } from './headers'; import { mergeInjectedHeaders } from './headers';
import { parseRequestBody } from './server'; import { parseRequestBody } from './server';
import { matchRoute } from './router'; import { normalizeRequestPath, resolveRoute } from './router';
import { HttpError } from '../signals'; import { HttpError } from '../signals';
import { renderError, type ErrorRequest, type ErrorResponse } from '../transformers'; import { renderError, type ErrorRequest, type ErrorResponse } from '../transformers';
import type { RouteDef, HttpOptions, MatchedRoute } from './types'; import type { RouteDef, HttpOptions, MatchedRoute } from './types';
@@ -108,7 +108,8 @@ function outcomeToResponse(result: HandleResult): Response {
return new Response(asReadableStream(result.outcome.stream, result.outcome.encoder), { headers }); return new Response(asReadableStream(result.outcome.stream, result.outcome.encoder), { headers });
} }
return new Response(result.outcome.body, { status: result.outcome.status, headers }); const body = [204, 205, 304].includes(result.outcome.status) ? null : result.outcome.body;
return new Response(body, { status: result.outcome.status, headers });
} }
/** /**
@@ -123,7 +124,14 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
const url = new URL(request.url); const url = new URL(request.url);
const path = url.pathname + url.search; const path = url.pathname + url.search;
const headers = headersToRecord(request.headers); const headers = headersToRecord(request.headers);
const matched = matchRoute(routes, request.method, url.pathname); let matched: ReturnType<typeof resolveRoute>;
try {
matched = resolveRoute(routes, request.method, normalizeRequestPath(url.pathname));
} catch {
matched = undefined; // handle() renders the shared 400 response without reading a body
}
const secure = url.protocol === 'https:'; const secure = url.protocol === 'https:';
// Computed up-front from the same inputs `handle()` uses, so early-failure responses (413/400/501, // Computed up-front from the same inputs `handle()` uses, so early-failure responses (413/400/501,
// before a route handler even runs) carry the same security/CORS headers Node's writeHead patch // before a route handler even runs) carry the same security/CORS headers Node's writeHead patch
+162
View File
@@ -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
});
}
+19
View File
@@ -31,6 +31,25 @@ export function matchWsRoute(
.find((entry) => entry.params); .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. */ /** Registers the connection with the stream registry so it can be force-closed on shutdown. */
function trackConnection(socket: WsSocket, streams?: Set<() => void>): { closer: () => void } { function trackConnection(socket: WsSocket, streams?: Set<() => void>): { closer: () => void } {
const closer = () => { const closer = () => {
+13 -3
View File
@@ -1,7 +1,7 @@
import type http from 'http'; import type http from 'http';
import { channel } from '../channel'; import { channel } from '../channel';
import type { Bus } from '../bus'; import type { Bus } from '../bus';
import { runWsConnection, matchWsRoute, type WsSocket, type WsRequest } from './ws-core'; import { runWsConnection, matchWsRoute, trackUntil, type WsSocket, type WsRequest } from './ws-core';
import type { WsRouteDef, MeshControl } from './types'; import type { WsRouteDef, MeshControl } from './types';
/** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */ /** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */
@@ -30,6 +30,7 @@ function handleMeshUpgrade(
req: http.IncomingMessage, req: http.IncomingMessage,
socket: any, socket: any,
head: Buffer, head: Buffer,
streams?: Set<() => void>,
): boolean { ): boolean {
if (path !== meshControl.path) return false; if (path !== meshControl.path) return false;
@@ -38,7 +39,16 @@ function handleMeshUpgrade(
return true; return true;
} }
wss.handleUpgrade(req, socket, head, (ws: any) => meshControl.handle(ws, req)); // 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; return true;
} }
@@ -94,7 +104,7 @@ export function attachWs(
server.on('upgrade', (req, socket, head) => { server.on('upgrade', (req, socket, head) => {
const path = (req.url ?? '/').split('?')[0]; const path = (req.url ?? '/').split('?')[0];
if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head)) return; if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head, streams)) return;
const route = matchWsRoute(wsRoutes, path); const route = matchWsRoute(wsRoutes, path);
+3 -1
View File
@@ -6,7 +6,7 @@
import 'reflect-metadata'; import 'reflect-metadata';
/** Package version, replaced at publish time. */ /** Package version, replaced at publish time. */
export const VERSION = '26.7.0-beta.0'; export const VERSION = '26.8.0-beta.0';
// Application // Application
export { createApp } from './app'; export { createApp } from './app';
@@ -27,6 +27,7 @@ export {
Step, Step,
Route, Route,
Get, Get,
Head,
Module, Module,
Transformer, Transformer,
Sse, Sse,
@@ -36,6 +37,7 @@ export {
Put, Put,
Patch, Patch,
Delete, Delete,
Options,
Html, Html,
} from './metadata'; } from './metadata';
export type { Transport, HttpMethod } from './metadata'; export type { Transport, HttpMethod } from './metadata';
+171 -58
View File
@@ -1,8 +1,8 @@
import type { Bus } from '../bus'; import type { Bus } from '../bus';
import { HttpError } from '../signals'; import { HttpError } from '../signals';
import { encode, decode, type Manifest, type RequestEnvelope, type Frame } from './protocol'; import { connectSocket, type SocketCtor } from '../http/ws-adapter';
import type { WsSocket } from '../http/ws-core';
let connSeq = 0; // module-level: deterministic unique connection-id prefix (no Date.now/Math.random) 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(). */ /** Client handle to a remote mesh server: its manifest, an RPC caller, and a close(). */
export interface Link { export interface Link {
@@ -18,17 +18,15 @@ type PendingEntry = {
timer: ReturnType<typeof setTimeout>; timer: ReturnType<typeof setTimeout>;
}; };
function loadWs(): any { /**
// lazy/optional, like streams; the ws CJS export is the WebSocket class * Reject and clear every in-flight RPC — used when the link closes.
// eslint-disable-next-line @typescript-eslint/no-require-imports * 503, not a bare Error: a dead upstream is not "this service broke", and the status is what
return require('ws'); * tells a caller it may retry and an operator where to look. A bare Error renders as a 500.
} */
/** Reject and clear every in-flight RPC — used when the link closes. */
function rejectAllPending(pending: Map<string, PendingEntry>, reason: string): void { function rejectAllPending(pending: Map<string, PendingEntry>, reason: string): void {
for (const [, entry] of pending) { for (const [, entry] of pending) {
clearTimeout(entry.timer); clearTimeout(entry.timer);
entry.reject(new Error(reason)); entry.reject(new HttpError(503, reason));
} }
pending.clear(); pending.clear();
@@ -36,7 +34,7 @@ function rejectAllPending(pending: Map<string, PendingEntry>, reason: string): v
/** Register one RPC in `pending` by id, send its request, and reject it on timeout. */ /** Register one RPC in `pending` by id, send its request, and reject it on timeout. */
function sendRpc( function sendRpc(
ws: any, socket: WsSocket,
pending: Map<string, PendingEntry>, pending: Map<string, PendingEntry>,
id: string, id: string,
kind: 'scope' | 'route', kind: 'scope' | 'route',
@@ -44,36 +42,41 @@ function sendRpc(
ctx: RequestEnvelope, ctx: RequestEnvelope,
timeoutMs: number, timeoutMs: number,
): Promise<unknown> { ): 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) => { 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(() => { const timer = setTimeout(() => {
pending.delete(id); pending.delete(id);
rejectCall(new Error(`mesh rpc timeout: ${name}`)); rejectCall(new HttpError(504, `mesh rpc timeout: ${name}`));
}, timeoutMs); }, timeoutMs);
pending.set(id, { resolve: resolveCall, reject: rejectCall, timer }); pending.set(id, { resolve: resolveCall, reject: rejectCall, timer });
ws.send(encode({ type: 'rpc-req', id, kind, name, ctx })); socket.send(encode({ type: 'rpc-req', id, kind, name, ctx }));
}); });
} }
/** Assemble the client-facing Link once the manifest arrives. */ /** Assemble the client-facing Link once the manifest arrives. */
function buildLink( function buildLink(socket: WsSocket, pending: Map<string, PendingEntry>, manifest: Manifest, timeoutMs: number): Link {
ws: any, // ids only need to be unique within this link: `pending` is per-connection, so a
pending: Map<string, PendingEntry>, // per-link counter suffices (no module-global sequence, no test-order coupling).
manifest: Manifest,
connId: string,
timeoutMs: number,
): Link {
let counter = 0; let counter = 0;
return { return {
manifest, manifest,
rpc(kind, name, ctx) { rpc(kind, name, ctx) {
const id = `${connId}:${counter++}`; const id = String(counter++);
return sendRpc(ws, pending, id, kind, name, ctx, timeoutMs); return sendRpc(socket, pending, id, kind, name, ctx, timeoutMs);
}, },
close() { close() {
ws.close(); socket.close();
}, },
}; };
} }
@@ -97,50 +100,160 @@ function settleRpcResponse(
} }
} }
/** Open a WebSocket link to a mesh server, handshake with `secret`, and resolve once its manifest arrives. */ /** Default gap between heartbeat pings. Two missed rounds close the link. */
export function connectLink(args: { url: string; secret: string; timeoutMs?: number; bus?: Bus }): Promise<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 timeoutMs = args.timeoutMs ?? 30_000;
const WS = loadWs(); const { socket, opened } = connectSocket(args.url, args.Ctor ?? undefined);
const ws = new WS(args.url);
const pending = new Map<string, PendingEntry>(); const pending = new Map<string, PendingEntry>();
const connId = `c${connSeq++}`; let manifest = false;
let manifest: Manifest | undefined; let heartbeat: { stop: () => void; markAlive: () => void } | undefined;
return new Promise<Link>((resolve, reject) => { return new Promise<Link>((resolve, reject) => {
const connectTimer = setTimeout(() => { const connectTimer = setTimeout(() => {
ws.close(); socket.close();
reject(new Error(`mesh connect timeout: ${args.url}`)); reject(new Error(`mesh connect timeout: ${args.url}`));
}, timeoutMs); }, timeoutMs);
ws.on('open', () => ws.send(encode({ type: 'hello', secret: args.secret }))); const hs: Handshake = {
ws.on('error', (error: unknown) => reject(error)); url: args.url,
ws.on('close', () => { socket,
clearTimeout(connectTimer); pending,
args.bus?.emit('mesh:disconnect', { name: args.url }); timeoutMs,
rejectAllPending(pending, 'mesh link closed'); bus: args.bus,
if (!manifest) reject(new Error(`mesh handshake failed: ${args.url}`)); resolve,
}); reject,
onManifest: () => {
ws.on('message', (data: unknown) => { manifest = true;
let frame: Frame;
try {
frame = decode(String(data));
} catch {
return;
}
if (frame.type === 'manifest') {
manifest = { scopes: frame.scopes, routes: frame.routes };
clearTimeout(connectTimer); clearTimeout(connectTimer);
args.bus?.emit('mesh:connect', { name: args.url }); // started only once authenticated: an unauthenticated peer should not be pinging
resolve(buildLink(ws, pending, manifest, connId, timeoutMs)); heartbeat = startHeartbeat(socket, args.heartbeatMs ?? HEARTBEAT_MS);
return; },
} onPong: () => heartbeat?.markAlive(),
};
if (frame.type === 'rpc-res') { opened.then(
settleRpcResponse(pending, frame, args.bus); () => 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 */
}); });
}); });
} }
+72 -11
View File
@@ -1,3 +1,11 @@
/**
* 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. */ /** Serialized request context sent across the mesh for a scope or route RPC. */
export interface RequestEnvelope { export interface RequestEnvelope {
method: string; method: string;
@@ -23,28 +31,81 @@ export interface Manifest {
routes: RouteEntry[]; routes: RouteEntry[];
} }
/** Discriminated union of every message on the mesh wire. */ /**
* 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 = export type Frame =
| { type: 'hello'; secret: string } | { type: 'hello'; v: number; secret: string }
| { type: 'manifest'; scopes: ScopeEntry[]; routes: RouteEntry[] } | { type: 'manifest'; v: number; scopes: ScopeEntry[]; routes: RouteEntry[] }
| { type: 'rpc-req'; id: string; kind: 'scope' | 'route'; name: string; ctx: RequestEnvelope } | { 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: true; result: unknown }
| { type: 'rpc-res'; id: string; ok: false; error: { message: string; status?: number } }; | { type: 'rpc-res'; id: string; ok: false; error: { message: string; status?: number } }
| { type: 'ping' }
| { type: 'pong' };
const TYPES = new Set(['hello', 'manifest', 'rpc-req', 'rpc-res']); const isString = (value: unknown): value is string => typeof value === 'string';
const isNumber = (value: unknown): boolean => typeof value === 'number';
const isObject = (value: unknown): boolean => typeof value === 'object' && value !== null;
/** 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. */ /** Serialize a frame to a JSON wire string. */
export function encode(frame: Frame): string { export function encode(frame: Frame): string {
return JSON.stringify(frame); return JSON.stringify(frame);
} }
/** Parse a wire string into a frame, throwing if the `type` tag is unknown. */ /** 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 { export function decode(json: string): Frame {
const parsed = JSON.parse(json) as { type?: unknown }; 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 (typeof parsed.type !== 'string' || !TYPES.has(parsed.type)) { if (!check) throw new Error(`unknown frame type: ${String(type)}`);
throw new Error(`unknown frame type: ${String(parsed.type)}`);
}
return parsed as Frame; check(parsed, (why) => {
throw new Error(`malformed ${String(type)} frame: ${why}`);
});
return parsed as unknown as Frame;
} }
+108 -37
View File
@@ -1,8 +1,20 @@
import crypto from 'crypto'; // node: prefix, not a bare specifier: this is the mesh auth path, and on Deno/Bun a bare
// 'crypto' leans on node-compat resolution heuristics. Buffer + timingSafeEqual resolve
// under node-compat on both; edge/workerd is out of scope (see the cross-runtime spec).
import crypto from 'node:crypto';
import type { Bus } from '../bus'; import type { Bus } from '../bus';
import type { WsSocket } from '../http/ws-core';
import type { ResponseShape } from '../pipeline'; import type { ResponseShape } from '../pipeline';
import { isHttpError } from '../signals'; import { isHttpError } from '../signals';
import { encode, decode, type Manifest, type RequestEnvelope, type RouteEntry, type Frame } from './protocol'; import {
encode,
decode,
MESH_PROTOCOL_VERSION,
type Manifest,
type RequestEnvelope,
type RouteEntry,
type Frame,
} from './protocol';
/** WebSocket path where a teapot exposes its mesh control channel. */ /** WebSocket path where a teapot exposes its mesh control channel. */
export const MESH_CONTROL_PATH = '/__mesh__/control'; export const MESH_CONTROL_PATH = '/__mesh__/control';
@@ -49,18 +61,44 @@ function notExported(name: string): Error {
return error; return error;
} }
/** Validate an unauthenticated hello frame; reply with the manifest on success or close on mismatch. */ /**
function handleHandshake(ws: any, frame: Frame, deps: MeshControlDeps): boolean { * Validate an unauthenticated hello frame; reply with the manifest on success or close on mismatch.
if (frame.type === 'hello' && safeEqual(frame.secret, deps.secret)) { * The version is checked *before* the secret: a skewed peer is not an auth failure, and telling it
ws.send(encode({ type: 'manifest', scopes: deps.manifest.scopes, routes: deps.manifest.routes })); * "wrong secret" would send its operator hunting the wrong bug.
deps.bus?.emit('mesh:connect', { name: 'teapot' }); */
function handleHandshake(socket: WsSocket, frame: Frame, deps: MeshControlDeps): boolean {
if (frame.type !== 'hello') {
socket.close(1008);
return true; return false;
} }
ws.close(1008); 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; 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. */ /** Resolve an authenticated rpc-req against the exported scopes/routes, enforcing export gating. */
@@ -85,7 +123,7 @@ function resolveRpc(
/** Serve one authenticated rpc-req: resolve it and frame the ok/error response back to the peer. */ /** Serve one authenticated rpc-req: resolve it and frame the ok/error response back to the peer. */
async function handleRpc( async function handleRpc(
ws: any, socket: WsSocket,
frame: RpcReqFrame, frame: RpcReqFrame,
deps: MeshControlDeps, deps: MeshControlDeps,
exportedScopes: Set<string>, exportedScopes: Set<string>,
@@ -96,44 +134,77 @@ async function handleRpc(
try { try {
const result = await resolveRpc(frame, deps, exportedScopes, exportedRoutes); const result = await resolveRpc(frame, deps, exportedScopes, exportedRoutes);
ws.send(encode({ type: 'rpc-res', id, ok: true, result })); socket.send(encode({ type: 'rpc-res', id, ok: true, result }));
} catch (err) { } catch (err) {
const status = isHttpError(err) ? err.status : ((err as any)?.status ?? 500); const status = isHttpError(err) ? err.status : ((err as any)?.status ?? 500);
deps.bus?.emit('mesh:rpc:error', { name, error: err }); deps.bus?.emit('mesh:rpc:error', { name, error: err });
ws.send(encode({ type: 'rpc-res', id, ok: false, error: { message: (err as Error).message, status } })); socket.send(encode({ type: 'rpc-res', id, ok: false, error: { message: (err as Error).message, status } }));
} }
} }
/** Build a WebSocket handler that authenticates peers and serves scope/route RPCs from the manifest. */ /** Drive one control connection to completion: handshake, then serve RPCs until the socket ends. */
export function createMeshControl(deps: MeshControlDeps): { path: string; handle: (ws: any) => void } { 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 exportedScopes = new Set(deps.manifest.scopes.map((scope) => scope.token));
const exportedRoutes = new Set(deps.manifest.routes.map((route) => `${route.method} ${route.pattern}`)); const exportedRoutes = new Set(deps.manifest.routes.map((route) => `${route.method} ${route.pattern}`));
return { return {
path: MESH_CONTROL_PATH, path: MESH_CONTROL_PATH,
handle(ws: any) { /**
let authed = false; * Resolves when the connection ends, mirroring `runWsConnection` — so `app.upgrade` can await
ws.on('message', async (data: unknown) => { * the control channel's lifetime the same way it awaits a regular ws route's.
let frame: Frame; * `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.
try { */
frame = decode(String(data)); handle(socket: WsSocket): Promise<void> {
} catch { return serveFrames(socket, deps, exportedScopes, exportedRoutes);
return;
}
if (!authed) {
authed = handleHandshake(ws, frame, deps);
return;
}
if (frame.type !== 'rpc-req') return;
await handleRpc(ws, frame, deps, exportedScopes, exportedRoutes);
});
ws.on('close', () => deps.bus?.emit('mesh:disconnect', { name: 'teapot' }));
}, },
}; };
} }
+5 -1
View File
@@ -25,7 +25,7 @@ export interface StepMeta {
export: boolean; export: boolean;
} }
/** HTTP verbs supported by the route decorators. */ /** HTTP verbs supported by the route decorators. */
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; export type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS';
/** Wire transport a route responds with. */ /** Wire transport a route responds with. */
export type Transport = 'buffer' | 'sse' | 'ndjson' | 'negotiate' | 'ws'; export type Transport = 'buffer' | 'sse' | 'ndjson' | 'negotiate' | 'ws';
/** Metadata attached by a route decorator to a single handler method. */ /** Metadata attached by a route decorator to a single handler method. */
@@ -124,6 +124,8 @@ function routeDecorator(method: HttpMethod, transport: Transport) {
/** Declares a buffered `GET` route. */ /** Declares a buffered `GET` route. */
export const Get = routeDecorator('GET', 'buffer'); export const Get = routeDecorator('GET', 'buffer');
/** Declares a buffered `HEAD` route. */
export const Head = routeDecorator('HEAD', 'buffer');
/** Declares a buffered `POST` route. */ /** Declares a buffered `POST` route. */
export const Post = routeDecorator('POST', 'buffer'); export const Post = routeDecorator('POST', 'buffer');
/** Declares a buffered `PUT` route. */ /** Declares a buffered `PUT` route. */
@@ -132,6 +134,8 @@ export const Put = routeDecorator('PUT', 'buffer');
export const Patch = routeDecorator('PATCH', 'buffer'); export const Patch = routeDecorator('PATCH', 'buffer');
/** Declares a buffered `DELETE` route. */ /** Declares a buffered `DELETE` route. */
export const Delete = routeDecorator('DELETE', 'buffer'); export const Delete = routeDecorator('DELETE', 'buffer');
/** Declares a buffered `OPTIONS` route. */
export const Options = routeDecorator('OPTIONS', 'buffer');
/** Declares a `GET` route streamed as Server-Sent Events. */ /** Declares a `GET` route streamed as Server-Sent Events. */
export const Sse = routeDecorator('GET', 'sse'); export const Sse = routeDecorator('GET', 'sse');
/** Declares a `GET` route whose transport is content-negotiated at request time. */ /** Declares a `GET` route whose transport is content-negotiated at request time. */
+47 -24
View File
@@ -1,10 +1,12 @@
import type { ArgSpec } from './params'; import type { ArgSpec } from './params';
import type { Transport } from './metadata';
import { compilePattern } from './http/router';
/** Minimal per-route input the OpenAPI projection needs, derived from a route plan. */ /** Minimal per-route input the OpenAPI projection needs, derived from a route plan. */
export interface OpenApiRoute { export interface OpenApiRoute {
method: string; method: string;
pattern: string; pattern: string;
transport: string; transport: Transport;
args: ArgSpec[]; args: ArgSpec[];
} }
@@ -22,23 +24,37 @@ export interface OpenApiDoc {
paths: Record<string, Record<string, unknown>>; paths: Record<string, Record<string, unknown>>;
} }
type Parameter = { name: string; in: 'path' | 'query' | 'header'; required: boolean; schema: { type: 'string' } }; type Parameter = {
name: string;
in: 'path' | 'query' | 'header';
required: boolean;
schema: { type: 'string'; pattern?: string };
};
/** Converts a route pattern to an OpenAPI path template: `/users/:id` → `/users/{id}`, `:rest*` → `{rest}`. */ /** Converts a route pattern to an OpenAPI path template: `/users/:id` → `/users/{id}`, `:rest*` → `{rest}`. */
function templatePath(pattern: string): string { function templatePath(pattern: string): string {
const segments = pattern const segments = compilePattern(pattern).segments.map((segment) =>
.split('/') segment.kind === 'static' ? segment.value : `{${segment.name}}`,
.filter(Boolean) );
.map((seg) => (seg.startsWith(':') ? `{${seg.slice(1).replace(/\*$/, '')}}` : seg));
return `/${segments.join('/')}`; return `/${segments.join('/')}`;
} }
/** Every `:name` (and `:name*`) segment of a pattern becomes a required path parameter. */ /** Every `:name` (and `:name*`) segment of a pattern becomes a required path parameter. */
function pathParams(pattern: string): Parameter[] { function pathParams(pattern: string): Parameter[] {
return pattern return compilePattern(pattern).segments.flatMap((segment): Parameter[] => {
.split('/') if (segment.kind === 'static') return [];
.filter((seg) => seg.startsWith(':')) return [
.map((seg) => ({ name: seg.slice(1).replace(/\*$/, ''), in: 'path', required: true, schema: { type: 'string' } })); {
name: segment.name,
in: 'path',
required: true,
schema: {
type: 'string',
...(segment.kind === 'param' && segment.constraintSource ? { pattern: segment.constraintSource } : {}),
},
},
];
});
} }
/** Query and header parameters declared by the handler's `@query` / `@headers` / `@header` argument decorators. */ /** Query and header parameters declared by the handler's `@query` / `@headers` / `@header` argument decorators. */
@@ -55,17 +71,23 @@ function argParams(args: ArgSpec[]): Parameter[] {
return params; return params;
} }
/** The success/error responses documented for a route, keyed by transport and whether any input is validated. */ /**
function responses(route: OpenApiRoute): Record<string, unknown> { * The documented `200` per transport. `ws` is absent by construction — ws routes are not
const result: Record<string, unknown> = {}; * 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'>;
if (route.transport === 'sse') { const TRANSPORT_OK: Record<HttpTransport, Record<string, unknown>> = {
result['200'] = { description: 'Event stream', content: { 'text/event-stream': {} } }; buffer: { description: 'OK', content: { 'application/json': { schema: {} } } },
} else if (route.transport === 'ndjson' || route.transport === 'negotiate') { sse: { description: 'Event stream', content: { 'text/event-stream': {} } },
result['200'] = { description: 'Stream', content: { 'application/x-ndjson': {} } }; ndjson: { description: 'Stream', content: { 'application/x-ndjson': {} } },
} else { negotiate: { description: 'Stream', content: { 'application/x-ndjson': {} } },
result['200'] = { description: 'OK', content: { 'application/json': { schema: {} } } }; };
}
/** 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' }; if (route.args.some((arg) => arg.schema)) result['422'] = { description: 'Validation failed' };
result['500'] = { description: 'Internal Server Error' }; result['500'] = { description: 'Internal Server Error' };
@@ -73,9 +95,9 @@ function responses(route: OpenApiRoute): Record<string, unknown> {
} }
/** Builds a single OpenAPI operation object for a route. */ /** Builds a single OpenAPI operation object for a route. */
function operation(route: OpenApiRoute): Record<string, unknown> { function operation(route: OpenApiRoute, transport: HttpTransport): Record<string, unknown> {
const parameters = [...pathParams(route.pattern), ...argParams(route.args)]; const parameters = [...pathParams(route.pattern), ...argParams(route.args)];
const op: Record<string, unknown> = { responses: responses(route) }; const op: Record<string, unknown> = { responses: responses(route, transport) };
if (parameters.length) op.parameters = parameters; if (parameters.length) op.parameters = parameters;
@@ -95,9 +117,10 @@ export function buildOpenApi(routes: OpenApiRoute[], info?: OpenApiInfo): OpenAp
const paths: Record<string, Record<string, unknown>> = {}; const paths: Record<string, Record<string, unknown>> = {};
for (const route of routes) { for (const route of routes) {
if (route.transport === 'ws') continue; // not an HTTP request/response const transport = route.transport;
if (transport === 'ws') continue; // not an HTTP request/response; narrows to HttpTransport below
const path = templatePath(route.pattern); const path = templatePath(route.pattern);
(paths[path] ??= {})[route.method.toLowerCase()] = operation(route); (paths[path] ??= {})[route.method.toLowerCase()] = operation(route, transport);
} }
return { return {
+20 -7
View File
@@ -40,6 +40,25 @@ export function isStreamResult(result: PipelineResult): result is StreamResult {
return 'stream' in result; 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`. * 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`. * An async-iterable handler result becomes a stream; anything else is run through `transformer`.
@@ -59,13 +78,7 @@ export async function runPipeline(args: {
let context: any = { ...seed }; let context: any = { ...seed };
try { try {
for (const step of steps) { context = await runSteps(steps, context, bus);
bus.emit('request:step:enter', { name: step.name, scope: step.origin });
const output = await step.run(context);
context = { ...context, ...output };
bus.emit('request:step:leave', { name: step.name, scope: step.origin });
}
const result = await handler(context); const result = await handler(context);
const streaming = isAsyncIterable(result); const streaming = isAsyncIterable(result);
const contract = TRANSPORT_RETURN[transport]; const contract = TRANSPORT_RETURN[transport];
+8 -3
View File
@@ -1,11 +1,16 @@
import type { StandardIssue } from './standard-schema'; import type { StandardIssue } from './standard-schema';
/** Error carrying an HTTP status code and optional response body. Base of all signals. */ /**
* 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( constructor(
readonly status: number, readonly status: number,
message?: string, message?: string,
readonly body?: unknown, 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;
@@ -36,7 +41,7 @@ export class NotModified extends HttpError {
/** 302 redirect to `location`. */ /** 302 redirect to `location`. */
export class Redirect extends HttpError { export class Redirect extends HttpError {
constructor(readonly location: string) { constructor(readonly location: string) {
super(302); super(302, undefined, undefined, { location });
} }
} }
@@ -57,7 +62,7 @@ export class TransportMismatchError extends HttpError {
const expected = got === 'stream' ? 'return a value' : 'return an AsyncIterable'; const expected = got === 'stream' ? 'return a value' : 'return an AsyncIterable';
const fix = const fix =
got === 'stream' got === 'stream'
? 'buffered routes (@Get/@Post/@Put/@Patch/@Delete) must return a value — to stream, declare @Sse, @Stream, or @Ws' ? 'buffered routes (@Get/@Head/@Post/@Put/@Patch/@Delete/@Options) must return a value — to stream, declare @Sse, @Stream, or @Ws'
: 'streaming routes (@Sse/@Ws) must return an AsyncIterable (e.g. an async generator or channel())'; : 'streaming routes (@Sse/@Ws) must return an AsyncIterable (e.g. an async generator or channel())';
super(500, `Transport '${transport}'${where} must ${expected}, but the handler returned a ${got}. ${fix}.`); super(500, `Transport '${transport}'${where} must ${expected}, but the handler returned a ${got}. ${fix}.`);
} }
+2 -3
View File
@@ -1,4 +1,4 @@
import { isHttpError, Redirect, ValidationError } from './signals'; import { isHttpError, ValidationError } from './signals';
import type { TransformerFn } from './metadata'; import type { TransformerFn } from './metadata';
import { flattenPath } from './standard-schema'; import { flattenPath } from './standard-schema';
@@ -47,8 +47,7 @@ export function errorToResponse(error: unknown): ErrorResponse {
} }
if (isHttpError(error)) { if (isHttpError(error)) {
const headers: Record<string, string> = { 'content-type': 'application/json' }; const headers = { 'content-type': 'application/json', ...error.headers };
if (error instanceof Redirect) headers.location = error.location;
const payload = error.body !== undefined ? error.body : { error: error.message }; const payload = error.body !== undefined ? error.body : { error: error.message };
return { status: error.status, headers, body: JSON.stringify(payload) }; return { status: error.status, headers, body: JSON.stringify(payload) };
} }
+38 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect } from 'vitest';
import { createApp, Route, Ws, Module, ctx } from '../src/index'; import { createApp, Route, Ws, Module, ctx, Step, needs } from '../src/index';
import { channel } from '../src/channel'; import { channel } from '../src/channel';
import type { WsSocket, WsRequest } from '../src/http/ws-core'; import type { WsSocket, WsRequest } from '../src/http/ws-core';
@@ -16,6 +16,24 @@ class Rt {
class M {} class M {}
const app = createApp({ modules: [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() { function fakeSocket() {
const inbound = channel<unknown>(); const inbound = channel<unknown>();
const ac = new AbortController(); const ac = new AbortController();
@@ -46,6 +64,25 @@ describe('app.upgrade', () => {
expect(sent).toEqual(['echo:hi']); 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 () => { it('closes 1008 on an unknown ws path', async () => {
const { socket } = fakeSocket(); const { socket } = fakeSocket();
let closedCode: number | undefined; let closedCode: number | undefined;
+50
View File
@@ -40,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));
@@ -569,3 +583,39 @@ test('per-route maxBodyBytes overrides the server default', async () => {
server.close(); server.close();
}); });
describe('route table validation', () => {
it('rejects routes with the same method and effective pattern', () => {
@Route('/users')
class DuplicateCtl {
@Get('/:id') byId() {
return {};
}
@Get('/:name') byName() {
return {};
}
}
@Module({ mountpoint: '/api', controllers: [DuplicateCtl] })
class DuplicateModule {}
expect(() => createApp({ modules: [DuplicateModule] })).toThrow(
/ambiguous route GET.*\/api\/users\/:name.*DuplicateCtl\.byName.*DuplicateCtl\.byId/,
);
});
it('allows the same effective pattern under different methods', () => {
@Route('/users')
class MethodsCtl {
@Get('/:id') get() {
return {};
}
@Post('/:name') post() {
return {};
}
}
@Module({ mountpoint: '/api', controllers: [MethodsCtl] })
class MethodsModule {}
expect(() => createApp({ modules: [MethodsModule] })).not.toThrow();
});
});
+84
View File
@@ -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);
}
});
+50
View File
@@ -0,0 +1,50 @@
import { afterEach, expect, it, vi } from 'vitest';
import type { App } from '../src/app/types';
import { serveDeno } from '../src/deno';
afterEach(() => {
vi.unstubAllGlobals();
});
it('snapshots connection metadata before Deno invalidates the upgraded request', async () => {
let upgraded = false;
let handler: ((request: Request, info: unknown) => Response | Promise<Response>) | undefined;
const socket = {
readyState: 1,
binaryType: '',
send: vi.fn(),
close: vi.fn(),
addEventListener: vi.fn(),
};
vi.stubGlobal('Deno', {
serve: (_options: unknown, next: typeof handler) => {
handler = next;
return { finished: Promise.resolve(), shutdown: vi.fn() };
},
upgradeWebSocket: () => {
upgraded = true;
return { socket, response: new Response() };
},
});
const upgrade = vi.fn().mockResolvedValue(undefined);
serveDeno({ upgrade } as unknown as App);
const info = {
get remoteAddr() {
if (upgraded) throw new TypeError('Request closed');
return { hostname: '127.0.0.1', port: 1234, transport: 'tcp' };
},
};
const request = new Request('http://localhost/socket?token=x', {
headers: { upgrade: 'websocket', 'x-test': 'yes' },
});
expect(() => handler!(request, info)).not.toThrow();
await vi.waitFor(() =>
expect(upgrade).toHaveBeenCalledWith(
expect.objectContaining({ url: '/socket?token=x', ip: '127.0.0.1' }),
expect.any(Object),
),
);
});
+170
View File
@@ -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);
}
});
+108
View File
@@ -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();
}
});
+23 -4
View File
@@ -110,17 +110,36 @@ describe('app.fetch trustProxy gates x-forwarded-for', () => {
}); });
}); });
describe('app.fetch mesh gating (live `booted` read)', () => { describe('app.fetch on a mesh app', () => {
it('throws before listen() and starts working after listen() finalizes', async () => { // Previously this asserted fetch() *threw* until listen() ran, which made mesh Node-only:
// Deno/Bun/edge serve through app.fetch and can never call listen() (it builds an http.Server).
// The boot gate now finalizes the mesh graph on first use, whoever triggers it.
it('serves without ever calling listen()', async () => {
const meshApp = createApp({ modules: [MeshModule], experimental: true, mesh: { secret: 's3cr3t' } }); const meshApp = createApp({ modules: [MeshModule], experimental: true, mesh: { secret: 's3cr3t' } });
await expect(meshApp.fetch(new Request('http://x/api/mesh/ping'))).rejects.toThrow(/unavailable before listen/); const res = await meshApp.fetch(new Request('http://x/api/mesh/ping'));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ pong: true });
await meshApp.close();
});
it('does not re-boot when listen() follows a fetch', async () => {
const meshApp = createApp({ modules: [MeshModule], experimental: true, mesh: { secret: 's3cr3t' } });
let booted = 0;
meshApp.bus.on('boot:provider:start', () => {
booted += 1;
});
await meshApp.fetch(new Request('http://x/api/mesh/ping'));
const bootsAfterFetch = booted;
const server = await meshApp.listen(0); const server = await meshApp.listen(0);
try { try {
const res = await meshApp.fetch(new Request('http://x/api/mesh/ping')); const res = await meshApp.fetch(new Request('http://x/api/mesh/ping'));
expect(res.status).toBe(200); expect(res.status).toBe(200);
expect(await res.json()).toEqual({ pong: true }); // listen() shares fetch's memoized gate: provider factories must not run twice
expect(booted).toBe(bootsAfterFetch);
} finally { } finally {
server.close(); server.close();
} }
+50
View File
@@ -0,0 +1,50 @@
import 'reflect-metadata';
import { describe, expect, it, vi } from 'vitest';
import { createApp, Step, Route, Get, Module, needs } from '../src/index';
// Builds a module with an n-deep chain: s1..sn (each needs the previous) + a route that @needs the last.
function deepModule(n: number) {
const steps = Array.from({ length: n }, (_, i) => {
const k = i + 1;
@Step({ provides: `s${k}`, needs: k > 1 ? [`s${k - 1}`] : [] })
class S { run() { return { [`s${k}`]: k }; } }
return S;
});
@Route('/')
class C { @Get('/deep') deep(@needs(`s${n}`) s: number) { return { s }; } }
@Module({ mountpoint: '/', steps, controllers: [C] })
class M {}
return M;
}
describe('deep-graph warning', () => {
it('warns at boot when a route resolves to more than 20 steps', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
createApp({ modules: [deepModule(25)] });
expect(warn).toHaveBeenCalledWith(expect.stringContaining('25 steps'));
warn.mockRestore();
});
it('stays quiet under the threshold', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
createApp({ modules: [deepModule(10)] });
expect(warn).not.toHaveBeenCalled();
warn.mockRestore();
});
it('warnGraphDepth: false silences it', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
createApp({ modules: [deepModule(25)], warnGraphDepth: false });
expect(warn).not.toHaveBeenCalled();
warn.mockRestore();
});
it('warnGraphDepth tunes the threshold', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
createApp({ modules: [deepModule(10)], warnGraphDepth: 5 });
expect(warn).toHaveBeenCalledWith(expect.stringContaining('10 steps'));
warn.mockRestore();
});
});
+71
View File
@@ -0,0 +1,71 @@
// Not a test — a Node-hosted mesh peer, spawned by mesh-interop.test.ts. Deno's test runner
// only discovers *.test.ts, so this file is ignored by `deno test`.
//
// It exists so the interop claim is tested rather than reasoned about: Deno<->Deno passing
// says nothing about a Node teapot serving a Deno teacup, which is the actual deployment
// shape once mesh spans runtimes. Node's side uses the `ws` package (WebSocketServer +
// nodeSocket); Deno's uses its global WebSocket. Only a real cross-process run exercises both.
//
// Modes:
// teapot -> exports scopes, prints {"port":N}, serves until killed
// teacup <controlUrl> -> consumes the remote scopes, prints {"ok":true,"body":{...}}
import 'reflect-metadata';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index';
const SECRET = process.env.MESH_SECRET ?? 's3cr3t';
@Provider({ provides: 'config', export: true })
class Config {
provide() {
return { config: { region: 'mx', runtime: 'node' } };
}
}
@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 [mode, controlUrl] = process.argv.slice(2);
async function main(): Promise<void> {
if (mode === 'teapot') {
const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const server = await app.listen(0);
console.log(JSON.stringify({ port: (server.address() as { port: number }).port }));
return; // stays alive on the open server until the parent kills it
}
if (mode === 'teacup') {
const app = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl, secret: SECRET }], timeoutMs: 5000 },
});
const res = await app.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } }));
const body = await res.json();
console.log(JSON.stringify({ ok: res.status === 200, body }));
await app.close();
process.exit(0);
}
throw new Error(`unknown mode: ${mode}`);
}
main().catch((err: unknown) => {
console.log(JSON.stringify({ ok: false, error: String((err as Error).message) }));
process.exit(1);
});
+1 -1
View File
@@ -5,7 +5,7 @@ import { createHttpServer, type MeshControl } from '../../src/http';
describe('mesh control upgrade', () => { describe('mesh control upgrade', () => {
it('routes the reserved path to meshControl.handle and leaves wsRoutes intact', async () => { it('routes the reserved path to meshControl.handle and leaves wsRoutes intact', async () => {
let handled = false; let handled = false;
const meshControl: MeshControl = { path: '/__mesh__/control', handle: (ws) => { handled = true; ws.send('hi'); } }; const meshControl: MeshControl = { path: '/__mesh__/control', handle: async (ws) => { handled = true; ws.send('hi'); } };
const server = createHttpServer([], [], undefined, meshControl); const server = createHttpServer([], [], undefined, meshControl);
await new Promise<void>((r) => server.listen(0, r)); await new Promise<void>((r) => server.listen(0, r));
const port = (server.address() as any).port; const port = (server.address() as any).port;
+121
View File
@@ -0,0 +1,121 @@
import { describe, it, expect } from 'vitest';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index';
const SECRET = 's3cr3t';
@Provider({ provides: 'config', export: true })
class Config {
provide() {
return { config: { region: 'mx' } };
}
}
@Step({ provides: 'auth', needs: [], export: true })
class Auth {
run() {
return { auth: { token: 'ok' } };
}
}
@Route('/svc')
class SvcCtl {
@Get('/ping', { export: true })
ping() {
return { pong: true };
}
}
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth], controllers: [SvcCtl] })
class TeapotModule {}
@Route('/local')
class LocalCtl {
@Get('/who')
who(@needs('auth') auth: any) {
return { auth };
}
}
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
const controlUrl = (server: any) => `ws://127.0.0.1:${(server.address() as any).port}/__mesh__/control`;
/**
* What a teacup answers once its teapot is gone. The status is the whole point: a dead upstream
* is not "I broke" (500) — it is "my dependency is unavailable" (503), which is what tells an
* operator where to look and what a caller may retry.
*/
describe('mesh link failure', () => {
it('answers 503 on a remote step once the teapot is gone', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(tServer), secret: SECRET }] },
});
const ok = await teacup.fetch(new Request('http://x/api/local/who'));
expect(ok.status).toBe(200);
await teapot.close();
await new Promise((r) => setTimeout(r, 50));
const down = await teacup.fetch(new Request('http://x/api/local/who'));
expect(down.status).toBe(503);
await teacup.close();
});
it('answers 503 on a proxied remote route once the teapot is gone', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(tServer), secret: SECRET }] },
});
const ok = await teacup.fetch(new Request('http://x/api/svc/ping'));
expect(ok.status).toBe(200);
await teapot.close();
await new Promise((r) => setTimeout(r, 50));
const down = await teacup.fetch(new Request('http://x/api/svc/ping'));
expect(down.status).toBe(503);
await teacup.close();
});
it('keeps serving an app-scope remote from cache after the link drops', async () => {
// Not a bug, but worth pinning: an app-scope export is resolved once and memoised, so it
// survives its teapot — with a value that can go stale. Reconciling on reconnect is a
// known gap (see the mesh guide), and this test is what would catch it changing by accident.
@Route('/cached')
class CachedCtl {
@Get('/cfg')
cfg(@needs('config') config: any) {
return { config };
}
}
@Module({ mountpoint: '/api', controllers: [CachedCtl] })
class CachedModule {}
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const teacup = createApp({
modules: [CachedModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(tServer), secret: SECRET }] },
});
expect((await teacup.fetch(new Request('http://x/api/cached/cfg'))).status).toBe(200);
await teapot.close();
await new Promise((r) => setTimeout(r, 50));
const after = await teacup.fetch(new Request('http://x/api/cached/cfg'));
expect(after.status).toBe(200); // cached, so still answering
expect(await after.json()).toEqual({ config: { region: 'mx' } });
await teacup.close();
});
});
+308
View File
@@ -0,0 +1,308 @@
import { describe, it, expect } from 'vitest';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index';
import { channel } from '../../src/channel';
import { encode, decode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol';
import type { WsSocket, WsRequest } from '../../src/http/ws-core';
const SECRET = 's3cr3t';
@Provider({ provides: 'config', export: true })
class Config {
provide() {
return { config: { region: 'mx' } };
}
}
@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 {}
@Route('/plain')
class PlainCtl {
@Get('/ok')
ok() {
return { ok: true };
}
}
@Module({ mountpoint: '/', controllers: [PlainCtl] })
class PlainModule {}
const teapotUrl = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`;
/** A neutral socket, exactly what serveDeno/serveBun hand to app.upgrade. */
const fakePeer = () => {
const inbound = channel<unknown>();
const ac = new AbortController();
const sent: any[] = [];
const closed: { code?: number; reason?: string }[] = [];
const socket: WsSocket = {
inbound,
abort: ac.signal,
isOpen: true,
send: (data: string) => {
sent.push(decode(data));
},
close: (code, reason) => {
closed.push({ code, reason });
inbound.close();
ac.abort();
},
terminate: () => ac.abort(),
};
return { socket, sent, closed, inbound };
};
const controlReq = (): WsRequest => ({ url: '/__mesh__/control', headers: {}, protocol: 'http', ip: '' });
/**
* A mesh teacup driven purely through `app.fetch` — the entry point Deno/Bun/edge use.
* `listen()` is never called on the teacup, because on those runtimes it cannot be:
* it builds a Node http.Server.
*/
describe('mesh over app.fetch (no listen)', () => {
it('boots the mesh graph on the first request and resolves remote scopes', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const url = teapotUrl((tServer.address() as any).port);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url, secret: SECRET }] },
});
const res = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } }));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ config: { region: 'mx' }, auth: { token: 'abc' } });
await teacup.close();
tServer.close();
});
it('boots exactly once across concurrent first requests', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const url = teapotUrl((tServer.address() as any).port);
let connects = 0;
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url, secret: SECRET }] },
});
teacup.bus.on('mesh:connect', () => {
connects += 1;
});
const hit = () => teacup.fetch(new Request('http://x/api/local/who'));
const all = await Promise.all([hit(), hit(), hit()]);
expect(all.map((r) => r.status)).toEqual([200, 200, 200]);
expect(connects).toBe(1); // the boot gate is memoized: three racing requests splice once
await teacup.close();
tServer.close();
});
it('serves the remote scope in inspect() once a request has booted the graph', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const url = teapotUrl((tServer.address() as any).port);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url, secret: SECRET }] },
});
await teacup.fetch(new Request('http://x/api/local/who'));
const chain = teacup.inspect('/api/local/who').map((line) => `${line.kind}:${line.name}`);
// the remote provider and step spliced into the local route's chain
expect(chain).toContain('provider:config');
expect(chain).toContain('step:auth');
expect(teacup.graph().nodes.some((n) => n.name === 'config')).toBe(true);
await teacup.close();
tServer.close();
});
it('closes the teapot links, even with no server to hang the close off', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const url = teapotUrl((tServer.address() as any).port);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url, secret: SECRET }] },
});
const disconnects: string[] = [];
teacup.bus.on('mesh:disconnect', (p) => disconnects.push(p.name));
await teacup.fetch(new Request('http://x/api/local/who'));
expect(disconnects).toEqual([]);
// listen() never ran, so there is no server whose 'close' could reap the links
await teacup.close();
await new Promise((r) => setTimeout(r, 50));
expect(disconnects).toEqual([url]);
tServer.close();
});
it('resolves the graph via ready() without serving a request', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const url = teapotUrl((tServer.address() as any).port);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url, secret: SECRET }] },
});
// a mesh graph is not knowable without asking the teapots, so it throws until resolved
expect(() => teacup.graph()).toThrow(/until a mesh app has booted/);
await teacup.ready();
expect(teacup.graph().nodes.some((n) => n.name === 'config')).toBe(true);
expect(teacup.inspect('/api/local/who').map((l) => `${l.kind}:${l.name}`)).toContain('provider:config');
expect(teacup.explain('/api/local/who')).toBeTruthy();
await teacup.close();
tServer.close();
});
it('ready() resolves the graph but does NOT boot providers', async () => {
// the point of ready() over a full boot: a devtool asking for the graph must not run
// provider factories and open their connections as a side effect
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const url = teapotUrl((tServer.address() as any).port);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url, secret: SECRET }] },
});
const booted: string[] = [];
teacup.bus.on('boot:provider:start', (p) => booted.push(p.name));
await teacup.ready();
expect(teacup.graph().nodes.length).toBeGreaterThan(0); // graph is resolved
expect(booted).toEqual([]); // and nothing was booted to get it
await teacup.fetch(new Request('http://x/api/local/who'));
expect(booted.length).toBeGreaterThan(0); // serving does boot them
await teacup.close();
tServer.close();
});
it('ready() is memoized and shared with the boot: a later fetch does not re-splice', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const url = teapotUrl((tServer.address() as any).port);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url, secret: SECRET }] },
});
let connects = 0;
teacup.bus.on('mesh:connect', () => {
connects += 1;
});
await Promise.all([teacup.ready(), teacup.ready()]);
await teacup.fetch(new Request('http://x/api/local/who'));
await teacup.ready();
expect(connects).toBe(1);
await teacup.close();
tServer.close();
});
it('surfaces a failed mesh boot as a request error, not a silent success', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const url = teapotUrl((tServer.address() as any).port);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url, secret: 'WRONG' }], timeoutMs: 800 },
});
await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow();
await teacup.close();
tServer.close();
});
});
/**
* A teapot *exporting* over app.upgrade — the path serveDeno/serveBun drive. Without this the
* control channel only existed on Node's server.on('upgrade'), so a teapot could not run off Node
* and "mesh on 3 runtimes" would have meant consuming only.
*/
describe('mesh control over app.upgrade (no listen)', () => {
it('serves the handshake to a peer that never touched a Node server', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const peer = fakePeer();
void teapot.upgrade(controlReq(), peer.socket);
peer.inbound.push(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: SECRET }));
await new Promise((r) => setTimeout(r, 20));
expect(peer.sent[0]).toMatchObject({
type: 'manifest',
v: MESH_PROTOCOL_VERSION,
scopes: expect.arrayContaining([{ token: 'config', scope: 'app' }]),
});
await teapot.close();
});
it('rejects a bad secret over app.upgrade too', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const peer = fakePeer();
void teapot.upgrade(controlReq(), peer.socket);
peer.inbound.push(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: 'WRONG' }));
await new Promise((r) => setTimeout(r, 20));
expect(peer.sent).toEqual([]);
expect(peer.closed[0].code).toBe(1008);
await teapot.close();
});
it('refuses the reserved path explicitly on an app that exports nothing', async () => {
// a plain, self-contained app: the path is reserved regardless, so say so rather than
// let it fall through to the generic "no matching ws route"
const plain = createApp({ modules: [PlainModule] });
const peer = fakePeer();
await plain.upgrade(controlReq(), peer.socket);
expect(peer.closed[0].code).toBe(1008);
expect(peer.closed[0].reason).toMatch(/mesh control channel not enabled/i);
});
});
+86
View File
@@ -0,0 +1,86 @@
import { describe, it, expect } from 'vitest';
import { WebSocketServer } from 'ws';
import { connectLink } from '../../src/mesh/link';
import { encode, decode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol';
const V = MESH_PROTOCOL_VERSION;
const env = { method: 'GET', params: {}, query: {}, body: undefined, headers: {} };
/**
* A teapot that handshakes and answers RPCs, and optionally ignores pings — the shape of a
* half-open link: TCP still looks alive, the peer is not. Without a heartbeat a teacup only
* finds out when a request pays the full rpc timeout.
*/
function startTeapot(opts: { answerPings: boolean }) {
const wss = new WebSocketServer({ port: 0 });
const seen: string[] = [];
wss.on('connection', (ws) => {
ws.on('message', (data) => {
const frame = decode(data.toString());
seen.push(frame.type);
if (frame.type === 'hello') {
ws.send(encode({ type: 'manifest', v: V, scopes: [{ token: 'auth', scope: 'request' }], routes: [] }));
}
if (frame.type === 'ping' && opts.answerPings) ws.send(encode({ type: 'pong' }));
if (frame.type === 'rpc-req') ws.send(encode({ type: 'rpc-res', id: frame.id, ok: true, result: { got: 1 } }));
});
});
const port = (wss.address() as any).port;
return { url: `ws://127.0.0.1:${port}/__mesh__/control`, seen, close: () => wss.close() };
}
describe('mesh heartbeat', () => {
it('pings the teapot and keeps the link alive while it pongs', async () => {
const t = startTeapot({ answerPings: true });
const link = await connectLink({ url: t.url, secret: 'good', heartbeatMs: 30 });
await new Promise((r) => setTimeout(r, 120));
expect(t.seen.filter((f) => f === 'ping').length).toBeGreaterThan(1);
expect(await link.rpc('scope', 'auth', env)).toEqual({ got: 1 }); // still usable
link.close();
t.close();
});
it('closes the link when the teapot stops answering pings', async () => {
// the half-open case: the socket never errors, the peer just stops talking
const t = startTeapot({ answerPings: false });
const link = await connectLink({ url: t.url, secret: 'good', heartbeatMs: 30, timeoutMs: 10_000 });
await new Promise((r) => setTimeout(r, 200));
// 503 immediately from the dead-link guard, not a 10s wait on the rpc timeout
await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 });
t.close();
});
it('emits mesh:disconnect when the heartbeat gives up', async () => {
const t = startTeapot({ answerPings: false });
const seen: string[] = [];
const bus = { emit: (e: string, p: any) => seen.push(`${e}:${p.name}`), on: () => () => {} } as any;
const link = await connectLink({ url: t.url, secret: 'good', heartbeatMs: 30, bus });
await new Promise((r) => setTimeout(r, 200));
expect(seen.some((s) => s.startsWith('mesh:disconnect'))).toBe(true);
link.close();
t.close();
});
it('does not ping before the handshake completes', async () => {
const t = startTeapot({ answerPings: true });
const link = await connectLink({ url: t.url, secret: 'good', heartbeatMs: 30 });
// hello must be first on the wire: an unauthenticated peer has no business pinging
expect(t.seen[0]).toBe('hello');
link.close();
t.close();
});
});
+173 -1
View File
@@ -1,4 +1,4 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect, vi } from 'vitest';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index'; import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index';
const SECRET = 's3cr3t'; const SECRET = 's3cr3t';
@@ -23,6 +23,59 @@ class LocalCtl {
@Module({ mountpoint: '/api', controllers: [LocalCtl] }) @Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {} class TeacupModule {}
// Two teapots exporting the SAME route and no scopes — a scope clash would throw first
// (setRunner enforces unique tokens), which would hide the route clash under test.
@Route('/dup')
class DupCtl {
@Get('/ping', { export: true })
ping() {
return { pong: true };
}
}
@Module({ mountpoint: '/api', controllers: [DupCtl] })
class DupTeapotModule {}
@Route('/shape')
class ParamIdCtl {
@Get('/:id', { export: true })
get() {
return { from: 'id' };
}
}
@Module({ mountpoint: '/api', controllers: [ParamIdCtl] })
class ParamIdTeapotModule {}
@Route('/shape')
class ParamNameCtl {
@Get('/:name', { export: true })
get() {
return { from: 'name' };
}
}
@Module({ mountpoint: '/api', controllers: [ParamNameCtl] })
class ParamNameTeapotModule {}
@Route('/c')
class PlainCtl {
@Get('/ok')
ok() {
return { ok: true };
}
}
@Module({ mountpoint: '/', controllers: [PlainCtl] })
class PlainTeacupModule {}
// A teacup declaring a route locally at the same path a teapot exports it.
@Route('/dup')
class ShadowCtl {
@Get('/ping')
ping() {
return { from: 'local' };
}
}
@Module({ mountpoint: '/api', controllers: [ShadowCtl] })
class ShadowTeacupModule {}
describe('mesh skeleton integration', () => { describe('mesh skeleton integration', () => {
it('teacup resolves remote app-scope + request-scope into a local handler', async () => { it('teacup resolves remote app-scope + request-scope into a local handler', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
@@ -52,6 +105,125 @@ describe('mesh skeleton integration', () => {
s.close(); s.close();
}); });
it('refuses to boot when two teapots export the same route, naming both', async () => {
// No load balancing exists yet, so picking one silently would be a wrong answer that
// callers could come to depend on — and it would make adding LB later a breaking change.
const a = createApp({ modules: [DupTeapotModule], experimental: true, mesh: { secret: SECRET } });
const b = createApp({ modules: [DupTeapotModule], experimental: true, mesh: { secret: SECRET } });
const aServer = await a.listen(0);
const bServer = await b.listen(0);
const url = (s: any) => `ws://127.0.0.1:${(s.address() as any).port}/__mesh__/control`;
const teacup = createApp({
modules: [PlainTeacupModule],
experimental: true,
mesh: {
teapots: [
{ url: url(aServer), secret: SECRET },
{ url: url(bServer), secret: SECRET },
],
},
});
await expect(teacup.fetch(new Request('http://x/c/ok'))).rejects.toThrow(/GET \/api\/dup\/ping/);
await expect(teacup.fetch(new Request('http://x/c/ok'))).rejects.toThrow(/load balancing/i);
aServer.close();
bServer.close();
});
it('refuses ambiguous remote routes that differ only by parameter name', async () => {
const a = createApp({ modules: [ParamIdTeapotModule], experimental: true, mesh: { secret: SECRET } });
const b = createApp({ modules: [ParamNameTeapotModule], experimental: true, mesh: { secret: SECRET } });
const aServer = await a.listen(0);
const bServer = await b.listen(0);
const url = (s: any) => `ws://127.0.0.1:${(s.address() as any).port}/__mesh__/control`;
const teacup = createApp({
modules: [PlainTeacupModule],
experimental: true,
mesh: { teapots: [{ url: url(aServer), secret: SECRET }, { url: url(bServer), secret: SECRET }] },
});
try {
await expect(teacup.ready()).rejects.toThrow(/ambiguous remote route.*GET \/api\/shape\/:name/i);
} finally {
await teacup.close();
aServer.close();
bServer.close();
}
});
it('accepts the same route from a single teapot (regression: no false positive)', async () => {
const a = createApp({ modules: [DupTeapotModule], experimental: true, mesh: { secret: SECRET } });
const aServer = await a.listen(0);
const url = `ws://127.0.0.1:${(aServer.address() as any).port}/__mesh__/control`;
const teacup = createApp({
modules: [PlainTeacupModule],
experimental: true,
mesh: { teapots: [{ url, secret: SECRET }] },
});
const res = await teacup.fetch(new Request('http://x/api/dup/ping'));
expect(await res.json()).toEqual({ pong: true });
await teacup.close();
aServer.close();
});
it('gives a local route precedence over a remote one, and says so', async () => {
// Local-wins is the design: your own code beats an imported one, and it is how you
// override a teapot. But it used to be an accident of [...local, ...remote] ordering
// with nothing said, so a shadowed export looked like a broken teapot.
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const teapot = createApp({ modules: [DupTeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const url = `ws://127.0.0.1:${(tServer.address() as any).port}/__mesh__/control`;
const teacup = createApp({
modules: [ShadowTeacupModule],
experimental: true,
mesh: { teapots: [{ url, secret: SECRET }] },
});
try {
const res = await teacup.fetch(new Request('http://x/api/dup/ping'));
expect(await res.json()).toEqual({ from: 'local' }); // local wins, not the teapot's {pong:true}
const warned = warn.mock.calls.map((c) => String(c[0])).join('\n');
expect(warned).toMatch(/GET \/api\/dup\/ping/);
expect(warned).toMatch(/local/i);
expect(warned).toContain(url); // which teapot got shadowed
} finally {
warn.mockRestore();
await teacup.close();
tServer.close();
}
});
it('does not warn when a remote route has no local twin', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const teapot = createApp({ modules: [DupTeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const url = `ws://127.0.0.1:${(tServer.address() as any).port}/__mesh__/control`;
const teacup = createApp({
modules: [PlainTeacupModule],
experimental: true,
mesh: { teapots: [{ url, secret: SECRET }] },
});
try {
await teacup.fetch(new Request('http://x/c/ok'));
const shadowWarnings = warn.mock.calls.filter((c) => String(c[0]).includes('precedence'));
expect(shadowWarnings).toEqual([]);
} finally {
warn.mockRestore();
await teacup.close();
tServer.close();
}
});
it('rejects a bad secret (teacup boot fails)', async () => { it('rejects a bad secret (teacup boot fails)', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0); const tPort = (tServer.address() as any).port; const tServer = await teapot.listen(0); const tPort = (tServer.address() as any).port;
+64 -4
View File
@@ -1,7 +1,10 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect } from 'vitest';
import { WebSocketServer } from 'ws'; import WS, { WebSocketServer } from 'ws';
import { connectLink } from '../../src/mesh/link'; import { connectLink } from '../../src/mesh/link';
import { encode, decode } from '../../src/mesh/protocol'; import { loadWebSocketCtor, type SocketCtor } from '../../src/http/ws-adapter';
import { encode, decode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol';
const V = MESH_PROTOCOL_VERSION;
const env = { method: 'GET', params: {}, query: {}, body: undefined, headers: {} }; const env = { method: 'GET', params: {}, query: {}, body: undefined, headers: {} };
@@ -13,7 +16,7 @@ function startTeapot(secret = 'good') {
ws.on('message', (d) => { ws.on('message', (d) => {
const f = decode(d.toString()); const f = decode(d.toString());
if (!authed) { if (!authed) {
if (f.type === 'hello' && f.secret === secret) { authed = true; ws.send(encode({ type: 'manifest', scopes: [{ token: 'auth', scope: 'request' }], routes: [] })); } if (f.type === 'hello' && f.secret === secret) { authed = true; ws.send(encode({ type: 'manifest', v: V, scopes: [{ token: 'auth', scope: 'request' }], routes: [] })); }
else ws.close(1008); else ws.close(1008);
return; return;
} }
@@ -33,7 +36,7 @@ function startSilentTeapot(secret = 'good') {
wss.on('connection', (ws) => { wss.on('connection', (ws) => {
ws.on('message', (d) => { ws.on('message', (d) => {
const f = decode(d.toString()); const f = decode(d.toString());
if (f.type === 'hello' && f.secret === secret) ws.send(encode({ type: 'manifest', scopes: [], routes: [] })); if (f.type === 'hello' && f.secret === secret) ws.send(encode({ type: 'manifest', v: V, scopes: [], routes: [] }));
// ignore rpc-req entirely // ignore rpc-req entirely
}); });
}); });
@@ -41,7 +44,64 @@ function startSilentTeapot(secret = 'good') {
return { url: `ws://127.0.0.1:${port}/__mesh__/control`, close: () => wss.close() }; return { url: `ws://127.0.0.1:${port}/__mesh__/control`, close: () => wss.close() };
} }
// teapot running a future protocol: handshakes, but answers with a skewed manifest
function startSkewedTeapot() {
const wss = new WebSocketServer({ port: 0 });
wss.on('connection', (ws) => {
ws.on('message', () => ws.send(encode({ type: 'manifest', v: V + 1, scopes: [], routes: [] } as any)));
});
const port = (wss.address() as any).port;
return { url: `ws://127.0.0.1:${port}/__mesh__/control`, close: () => wss.close() };
}
/**
* Both client implementations, exercised on whatever Node runs the suite. `ws` is always in the
* list: it is the Node 18-21 path, and on a modern CI the platform global would otherwise be the
* only one ever covered — the fallback would rot unnoticed until someone ran the declared floor.
*/
const platform = (globalThis as { WebSocket?: SocketCtor }).WebSocket;
const CTORS: [string, SocketCtor][] = [['the ws package (Node < 22 path)', WS as unknown as SocketCtor]];
if (platform) CTORS.push(['the platform global WebSocket', platform]);
describe('WebSocket client implementations', () => {
it.each(CTORS)('handshakes and serves RPC over %s', async (_label, Ctor) => {
const t = startTeapot();
const link = await connectLink({ url: t.url, secret: 'good', Ctor });
expect(link.manifest.scopes).toEqual([{ token: 'auth', scope: 'request' }]);
expect(await link.rpc('scope', 'auth', env)).toEqual({ got: 'auth' });
link.close();
t.close();
});
it('prefers the platform global when it exists, else falls back to the ws package', () => {
expect(loadWebSocketCtor()).toBe(platform ?? (WS as unknown as SocketCtor));
});
});
describe('connectLink', () => { describe('connectLink', () => {
it('sends its protocol version in the hello', async () => {
const seen: any[] = [];
const wss = new WebSocketServer({ port: 0 });
wss.on('connection', (ws) =>
ws.on('message', (d) => {
seen.push(decode(d.toString()));
ws.send(encode({ type: 'manifest', v: V, scopes: [], routes: [] }));
}),
);
const url = `ws://127.0.0.1:${(wss.address() as any).port}/__mesh__/control`;
const link = await connectLink({ url, secret: 'good' });
expect(seen[0]).toMatchObject({ type: 'hello', v: V });
link.close();
wss.close();
});
it('refuses a teapot on a different protocol version', async () => {
const t = startSkewedTeapot();
await expect(connectLink({ url: t.url, secret: 'good', timeoutMs: 500 })).rejects.toThrow(/version/i);
t.close();
});
it('handshakes and exposes the manifest', async () => { it('handshakes and exposes the manifest', async () => {
const t = startTeapot(); const t = startTeapot();
const link = await connectLink({ url: t.url, secret: 'good' }); const link = await connectLink({ url: t.url, secret: 'good' });
+65 -6
View File
@@ -1,16 +1,22 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect } from 'vitest';
import { encode, decode, type Frame, type RequestEnvelope } from '../../src/mesh/protocol'; import { encode, decode, MESH_PROTOCOL_VERSION, type Frame, type RequestEnvelope } from '../../src/mesh/protocol';
const env: RequestEnvelope = { method: 'GET', params: { id: '1' }, query: {}, body: undefined, headers: {} }; const env: RequestEnvelope = { method: 'GET', params: { id: '1' }, query: {}, body: undefined, headers: {} };
const V = MESH_PROTOCOL_VERSION;
describe('protocol codec', () => { describe('protocol codec', () => {
it('round-trips each frame type', () => { it('round-trips each frame type', () => {
const frames: Frame[] = [ const frames: Frame[] = [
{ type: 'hello', secret: 's3cr3t' }, { type: 'hello', v: V, secret: 's3cr3t' },
{ type: 'manifest', scopes: [{ token: 'auth', scope: 'request' }], routes: [{ method: 'GET', pattern: '/u/:id' }] }, {
{ type: 'rpc-req', id: 'c1:1', kind: 'scope', name: 'auth', ctx: env }, type: 'manifest',
{ type: 'rpc-res', id: 'c1:1', ok: true, result: { id: 'u1' } }, v: V,
{ type: 'rpc-res', id: 'c1:2', ok: false, error: { message: 'no', status: 401 } }, scopes: [{ token: 'auth', scope: 'request' }],
routes: [{ method: 'GET', pattern: '/u/:id' }],
},
{ type: 'rpc-req', id: '1', kind: 'scope', name: 'auth', ctx: env },
{ type: 'rpc-res', id: '1', ok: true, result: { id: 'u1' } },
{ type: 'rpc-res', id: '2', ok: false, error: { message: 'no', status: 401 } },
]; ];
for (const f of frames) expect(decode(encode(f))).toEqual(f); for (const f of frames) expect(decode(encode(f))).toEqual(f);
}); });
@@ -22,4 +28,57 @@ describe('protocol codec', () => {
it('throws on unknown frame type', () => { it('throws on unknown frame type', () => {
expect(() => decode(JSON.stringify({ type: 'bogus' }))).toThrow(/unknown frame/i); expect(() => decode(JSON.stringify({ type: 'bogus' }))).toThrow(/unknown frame/i);
}); });
it.each(['constructor', 'toString', '__proto__', 'hasOwnProperty'])(
'treats inherited Object property %s as an unknown type, not a validator',
(type) => {
// `type` is peer-controlled; a bare SHAPE[type] lookup would walk the prototype chain
expect(() => decode(JSON.stringify({ type }))).toThrow(/unknown frame/i);
},
);
it('throws on a non-string type tag', () => {
expect(() => decode(JSON.stringify({ type: 42 }))).toThrow(/unknown frame/i);
expect(() => decode(JSON.stringify({}))).toThrow(/unknown frame/i);
});
});
describe('protocol versioning', () => {
it('carries the protocol version on the handshake frames', () => {
const hello = decode(encode({ type: 'hello', v: V, secret: 's' }));
const manifest = decode(encode({ type: 'manifest', v: V, scopes: [], routes: [] }));
expect(hello).toMatchObject({ v: V });
expect(manifest).toMatchObject({ v: V });
});
it('rejects a handshake frame with no version — an unversioned peer is not decodable', () => {
expect(() => decode(JSON.stringify({ type: 'hello', secret: 's' }))).toThrow(/malformed hello/i);
expect(() => decode(JSON.stringify({ type: 'manifest', scopes: [], routes: [] }))).toThrow(/malformed manifest/i);
});
});
describe('protocol field validation', () => {
// decode is the trust boundary: past it, teapot.ts feeds frames straight into
// resolveScope/resolveRoute. A bad shape must die here, not downstream.
it.each([
['hello without secret', { type: 'hello', v: V }],
['hello with non-string secret', { type: 'hello', v: V, secret: 42 }],
['manifest with non-array scopes', { type: 'manifest', v: V, scopes: 'nope', routes: [] }],
['rpc-req without id', { type: 'rpc-req', kind: 'scope', name: 'auth', ctx: env }],
['rpc-req without ctx', { type: 'rpc-req', id: '1', kind: 'scope', name: 'auth' }],
['rpc-req with unknown kind', { type: 'rpc-req', id: '1', kind: 'bogus', name: 'auth', ctx: env }],
['rpc-req without name', { type: 'rpc-req', id: '1', kind: 'scope', ctx: env }],
['rpc-res without id', { type: 'rpc-res', ok: true, result: 1 }],
['rpc-res with non-boolean ok', { type: 'rpc-res', id: '1', ok: 'yes' }],
['rpc-res error without an error payload', { type: 'rpc-res', id: '1', ok: false }],
])('rejects %s', (_label, frame) => {
expect(() => decode(JSON.stringify(frame))).toThrow(/malformed/i);
});
it('accepts a valid rpc-req unchanged', () => {
const frame: Frame = { type: 'rpc-req', id: '1', kind: 'route', name: '/u/:id', ctx: env };
expect(decode(encode(frame))).toEqual(frame);
});
}); });
+128 -43
View File
@@ -1,15 +1,45 @@
import { describe, it, expect, vi } from 'vitest'; import { describe, it, expect, vi } from 'vitest';
import { EventEmitter } from 'events';
import { buildManifest, createMeshControl } from '../../src/mesh/teapot'; import { buildManifest, createMeshControl } from '../../src/mesh/teapot';
import { encode, decode } from '../../src/mesh/protocol'; import { encode, decode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol';
import { channel } from '../../src/channel';
import type { WsSocket } from '../../src/http/ws-core';
import { Unauthorized } from '../../src/signals'; import { Unauthorized } from '../../src/signals';
const fakeWs = () => { const V = MESH_PROTOCOL_VERSION;
const ws: any = new EventEmitter();
ws.sent = []; /** Lets the control loop drain: it consumes `inbound` asynchronously and does not await RPCs. */
ws.send = (s: string) => ws.sent.push(decode(s)); const settle = () => new Promise((resolve) => setTimeout(resolve, 5));
ws.close = vi.fn();
return ws; /**
* A fake neutral WsSocket — the same capability `nodeSocket` builds on Node and `app.upgrade`
* hands over on Deno/Bun. `close` also ends `inbound`, mirroring a real socket's close.
*/
const fakeSocket = () => {
const inbound = channel<unknown>();
const ac = new AbortController();
const sent: any[] = [];
const close = vi.fn((_code?: number, _reason?: string) => {
inbound.close();
ac.abort();
});
const socket: WsSocket = {
inbound,
abort: ac.signal,
isOpen: true,
send: (data: string) => {
sent.push(decode(data));
},
close,
terminate: () => ac.abort(),
};
/** Deliver a frame the way a peer would, then let the loop process it. */
const deliver = async (frame: unknown) => {
inbound.push(encode(frame as never));
await settle();
};
return { socket, sent, close, deliver, inbound };
}; };
describe('buildManifest', () => { describe('buildManifest', () => {
@@ -22,63 +52,118 @@ describe('buildManifest', () => {
}); });
describe('createMeshControl', () => { describe('createMeshControl', () => {
const manifest = buildManifest({ providers: ['config'], steps: ['auth'], routes: [{ method: 'GET', pattern: '/u/:id' }] }); const manifest = buildManifest({
const make = (over: Partial<Parameters<typeof createMeshControl>[0]> = {}) => createMeshControl({ providers: ['config'],
secret: 'good', manifest, steps: ['auth'],
resolveScope: async (name) => ({ resolved: name }), routes: [{ method: 'GET', pattern: '/u/:id' }],
resolveRoute: async () => ({ status: 200, headers: {}, body: 'route-body' }),
...over,
}); });
const make = (over: Partial<Parameters<typeof createMeshControl>[0]> = {}) =>
createMeshControl({
secret: 'good',
manifest,
resolveScope: async (name) => ({ resolved: name }),
resolveRoute: async () => ({ status: 200, headers: {}, body: 'route-body' }),
...over,
});
it('exposes the reserved control path', () => { it('exposes the reserved control path', () => {
expect(make().path).toBe('/__mesh__/control'); expect(make().path).toBe('/__mesh__/control');
}); });
it('rejects a bad secret and closes', () => { it('rejects a bad secret and closes', async () => {
const ws = fakeWs(); make().handle(ws); const t = fakeSocket();
ws.emit('message', encode({ type: 'hello', secret: 'wrong' })); make().handle(t.socket);
expect(ws.close).toHaveBeenCalledWith(1008); await t.deliver({ type: 'hello', v: V, secret: 'wrong' });
expect(ws.sent).toEqual([]); expect(t.close).toHaveBeenCalledWith(1008);
expect(t.sent).toEqual([]);
}); });
it('answers a good hello with the manifest', () => { it('answers a good hello with the manifest, stamped with the protocol version', async () => {
const ws = fakeWs(); make().handle(ws); const t = fakeSocket();
ws.emit('message', encode({ type: 'hello', secret: 'good' })); make().handle(t.socket);
expect(ws.sent[0]).toMatchObject({ type: 'manifest', scopes: manifest.scopes }); await t.deliver({ type: 'hello', v: V, secret: 'good' });
expect(t.sent[0]).toMatchObject({ type: 'manifest', v: V, scopes: manifest.scopes });
});
it('rejects a version-skewed peer before checking its secret, naming both versions', async () => {
const t = fakeSocket();
make().handle(t.socket);
// correct secret, wrong protocol: must still be refused — and not as an auth failure
await t.deliver({ type: 'hello', v: V + 1, secret: 'good' });
expect(t.sent).toEqual([]);
const [code, reason] = t.close.mock.calls[0];
expect(code).toBe(1008);
expect(reason).toContain(String(V));
expect(reason).toContain(String(V + 1));
});
it('refuses a version-skewed peer even when its secret is also wrong', async () => {
const t = fakeSocket();
make().handle(t.socket);
await t.deliver({ type: 'hello', v: V + 1, secret: 'wrong' });
expect(t.sent).toEqual([]);
expect(t.close).toHaveBeenCalled();
}); });
it('does NOT process rpc before handshake', async () => { it('does NOT process rpc before handshake', async () => {
const ws = fakeWs(); make().handle(ws); const t = fakeSocket();
ws.emit('message', encode({ type: 'rpc-req', id: '1', kind: 'scope', name: 'config', ctx: {} as any })); make().handle(t.socket);
await new Promise((r) => setTimeout(r, 5)); await t.deliver({ type: 'rpc-req', id: '1', kind: 'scope', name: 'config', ctx: {} });
expect(ws.sent).toEqual([]); expect(t.sent).toEqual([]);
}); });
it('resolves an exported scope after handshake', async () => { it('resolves an exported scope after handshake', async () => {
const ws = fakeWs(); make().handle(ws); const t = fakeSocket();
ws.emit('message', encode({ type: 'hello', secret: 'good' })); make().handle(t.socket);
ws.emit('message', encode({ type: 'rpc-req', id: '7', kind: 'scope', name: 'config', ctx: {} as any })); await t.deliver({ type: 'hello', v: V, secret: 'good' });
await new Promise((r) => setTimeout(r, 5)); await t.deliver({ type: 'rpc-req', id: '7', kind: 'scope', name: 'config', ctx: {} });
expect(ws.sent.find((f: any) => f.type === 'rpc-res')).toEqual({ type: 'rpc-res', id: '7', ok: true, result: { resolved: 'config' } }); expect(t.sent.find((f: any) => f.type === 'rpc-res')).toEqual({
type: 'rpc-res',
id: '7',
ok: true,
result: { resolved: 'config' },
});
}); });
it('rejects an unexported scope', async () => { it('rejects an unexported scope', async () => {
const ws = fakeWs(); make().handle(ws); const t = fakeSocket();
ws.emit('message', encode({ type: 'hello', secret: 'good' })); make().handle(t.socket);
ws.emit('message', encode({ type: 'rpc-req', id: '8', kind: 'scope', name: 'secretsvc', ctx: {} as any })); await t.deliver({ type: 'hello', v: V, secret: 'good' });
await new Promise((r) => setTimeout(r, 5)); await t.deliver({ type: 'rpc-req', id: '8', kind: 'scope', name: 'secretsvc', ctx: {} });
const res: any = ws.sent.find((f: any) => f.type === 'rpc-res'); const res: any = t.sent.find((f: any) => f.type === 'rpc-res');
expect(res.ok).toBe(false); expect(res.ok).toBe(false);
expect(res.error.status).toBe(403); expect(res.error.status).toBe(403);
}); });
it('propagates a thrown HttpError status in the error frame', async () => { it('propagates a thrown HttpError status in the error frame', async () => {
const ws = fakeWs(); const t = fakeSocket();
make({ resolveScope: async () => { throw new Unauthorized('nope'); } }).handle(ws); make({
ws.emit('message', encode({ type: 'hello', secret: 'good' })); resolveScope: async () => {
ws.emit('message', encode({ type: 'rpc-req', id: '9', kind: 'scope', name: 'config', ctx: {} as any })); throw new Unauthorized('nope');
await new Promise((r) => setTimeout(r, 5)); },
const res: any = ws.sent.find((f: any) => f.type === 'rpc-res'); }).handle(t.socket);
await t.deliver({ type: 'hello', v: V, secret: 'good' });
await t.deliver({ type: 'rpc-req', id: '9', kind: 'scope', name: 'config', ctx: {} });
const res: any = t.sent.find((f: any) => f.type === 'rpc-res');
expect(res).toMatchObject({ id: '9', ok: false, error: { message: 'nope', status: 401 } }); expect(res).toMatchObject({ id: '9', ok: false, error: { message: 'nope', status: 401 } });
}); });
it('serves overlapping RPCs concurrently rather than head-of-line blocking', async () => {
// the loop must not await handleRpc: a slow call would otherwise stall every later one.
// fast is delivered second but resolves first, which can only happen if they overlap.
const t = fakeSocket();
make({
resolveScope: async (name) => {
if (name === 'config') await new Promise((r) => setTimeout(r, 30));
return { resolved: name };
},
}).handle(t.socket);
await t.deliver({ type: 'hello', v: V, secret: 'good' });
t.inbound.push(encode({ type: 'rpc-req', id: 'slow', kind: 'scope', name: 'config', ctx: {} as never }));
t.inbound.push(encode({ type: 'rpc-req', id: 'fast', kind: 'scope', name: 'auth', ctx: {} as never }));
await new Promise((r) => setTimeout(r, 60));
const ids = t.sent.filter((f: any) => f.type === 'rpc-res').map((f: any) => f.id);
expect(ids).toEqual(['fast', 'slow']);
});
}); });
+13 -1
View File
@@ -3,7 +3,7 @@ import { expect, test, describe, it } from 'vitest';
import { import {
Provider, Step, Route, Get, Module, Provider, Step, Route, Get, Module,
getProviderMeta, getStepMeta, getRoutes, getModuleMeta, getProviderMeta, getStepMeta, getRoutes, getModuleMeta,
Sse, Ws, Stream, Post, Sse, Ws, Stream, Post, Head, Options,
} from '../src/metadata'; } from '../src/metadata';
@Provider({ provides: 'db', needs: ['config'] }) @Provider({ provides: 'db', needs: ['config'] })
@@ -54,6 +54,18 @@ describe('stream route decorators', () => {
}); });
}); });
describe('HEAD and OPTIONS decorators', () => {
it('records both as buffered methods', () => {
class Methods {
@Head('/resource') head() {}
@Options('/resource') options() {}
}
const byName = Object.fromEntries(getRoutes(Methods).map((route) => [route.handlerName, route]));
expect(byName.head).toMatchObject({ method: 'HEAD', transport: 'buffer', path: '/resource' });
expect(byName.options).toMatchObject({ method: 'OPTIONS', transport: 'buffer', path: '/resource' });
});
});
describe('mesh export flags', () => { describe('mesh export flags', () => {
it('providers/steps carry export (default false)', () => { it('providers/steps carry export (default false)', () => {
@Provider({ provides: 'config', export: true }) class C { provide() { return {}; } } @Provider({ provides: 'config', export: true }) class C { provide() { return {}; } }
+25 -2
View File
@@ -1,7 +1,7 @@
import 'reflect-metadata'; import 'reflect-metadata';
import { describe, it, expect } from 'vitest'; import { describe, it, expect } from 'vitest';
import { createApp } from '../src/app'; import { createApp } from '../src/app';
import { Route, Get, Post, Ws, Module } from '../src/metadata'; import { Route, Get, Head, Options, Post, Ws, Module } from '../src/metadata';
import { param, query, headers, body } from '../src/params'; import { param, query, headers, body } from '../src/params';
const numSchema = { const numSchema = {
@@ -14,7 +14,13 @@ const numSchema = {
@Route('/users') @Route('/users')
class Users { class Users {
@Get('/:id') get(@param('id') _id: string, @query('expand') _e: string, @headers('x-trace') _t: string) { @Get('/:id(\\d+)') get(@param('id') _id: string, @query('expand') _e: string, @headers('x-trace') _t: string) {
return {};
}
@Head('/:id(\\d+)') head() {
return {};
}
@Options('/:id(\\d+)') options() {
return {}; return {};
} }
@Post('/') create(@body() _b: unknown) { @Post('/') create(@body() _b: unknown) {
@@ -52,6 +58,23 @@ describe('app.openapi()', () => {
expect(byName).toEqual({ id: 'path', expand: 'query', 'x-trace': 'header' }); expect(byName).toEqual({ id: 'path', expand: 'query', 'x-trace': 'header' });
}); });
it('projects a constrained param into schema.pattern', () => {
const op = doc.paths['/api/users/{id}'].get as any;
expect(op.parameters).toContainEqual({
name: 'id',
in: 'path',
required: true,
schema: { type: 'string', pattern: '\\d+' },
});
});
it('includes explicit HEAD and OPTIONS without inventing automatic operations', () => {
expect(doc.paths['/api/users/{id}'].head).toBeDefined();
expect(doc.paths['/api/users/{id}'].options).toBeDefined();
expect(doc.paths['/api/users/search'].head).toBeUndefined();
expect(doc.paths['/api/users/search'].options).toBeUndefined();
});
it('marks routes that take a body with requestBody', () => { it('marks routes that take a body with requestBody', () => {
const op = doc.paths['/api/users'].post as any; const op = doc.paths['/api/users'].post as any;
expect(op.requestBody.content['application/json']).toBeDefined(); expect(op.requestBody.content['application/json']).toBeDefined();
+33
View File
@@ -0,0 +1,33 @@
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
interface PackageMetadata {
readonly repository?: {
readonly type?: string;
readonly url?: string;
};
readonly bugs?: {
readonly url?: string;
};
readonly homepage?: string;
}
const packageJson = JSON.parse(readFileSync(resolve(process.cwd(), 'package.json'), 'utf8')) as PackageMetadata;
describe('package publication metadata', () => {
it('links npm provenance to the public GitHub repository', () => {
expect(packageJson.repository).toEqual({
type: 'git',
url: 'git+https://github.com/Expressive-Tea/green-tea.git',
});
});
it('links npm consumers to support and documentation', () => {
expect(packageJson.bugs).toEqual({
url: 'https://github.com/Expressive-Tea/green-tea/issues',
});
expect(packageJson.homepage).toBe('https://green-tea.expressive-tea.io/docs/');
});
});
+48 -1
View File
@@ -1,6 +1,6 @@
import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import type { Server } from 'http'; import type { Server } from 'http';
import { createApp, Provider, Route, Get, Post, Module, needs, body, Sse } from '../src/index'; import { createApp, Provider, Route, Get, Head, Options, Post, Module, needs, body, Sse } from '../src/index';
@Provider({ provides: 'db' }) @Provider({ provides: 'db' })
class Db { class Db {
@@ -22,6 +22,21 @@ class Ctl {
yield { n: 2 }; yield { n: 2 };
})(); })();
} }
@Get('/implicit-head') implicitHead() {
return { from: 'get' };
}
@Get('/explicit-head') explicitHeadGet() {
return { from: 'get' };
}
@Head('/explicit-head') explicitHead() {
return { from: 'head' };
}
@Get('/explicit-options') explicitOptionsGet() {
return { from: 'get' };
}
@Options('/explicit-options') explicitOptions() {
return { from: 'options' };
}
} }
@Module({ mountpoint: '/', providers: [Db], controllers: [Ctl] }) @Module({ mountpoint: '/', providers: [Db], controllers: [Ctl] })
class M {} class M {}
@@ -78,6 +93,38 @@ describe('Node vs app.fetch parity (Node is truth)', () => {
expect(web.status).toBe(node.status); expect(web.status).toBe(node.status);
expect(norm(web.headers)).toEqual(norm(node.headers)); expect(norm(web.headers)).toEqual(norm(node.headers));
}); });
it('implicit and explicit HEAD return no body in both adapters', async () => {
for (const path of ['/api/implicit-head', '/api/explicit-head']) {
const { node, web } = await both(path, { method: 'HEAD' });
expect(node.status).toBe(200);
expect(web.status).toBe(node.status);
expect(await node.text()).toBe('');
expect(await web.text()).toBe('');
}
});
it('automatic OPTIONS is 204 with the same canonical Allow header', async () => {
const { node, web } = await both('/api/x', { method: 'OPTIONS' });
expect(node.status).toBe(204);
expect(web.status).toBe(204);
expect(node.headers.get('allow')).toBe('GET, HEAD, OPTIONS');
expect(web.headers.get('allow')).toBe(node.headers.get('allow'));
});
it('explicit OPTIONS route runs normally', async () => {
const { node, web } = await both('/api/explicit-options', { method: 'OPTIONS' });
expect(node.status).toBe(200);
expect(web.status).toBe(200);
expect(await node.json()).toEqual({ from: 'options' });
expect(await web.json()).toEqual({ from: 'options' });
});
it('rejects repeated slashes and malformed encoding with secure 400 responses', async () => {
for (const path of ['/api//x', '/api/%E0%A4%A']) {
const { node, web } = await both(path);
expect(node.status).toBe(400);
expect(web.status).toBe(400);
expect(node.headers.get('x-content-type-options')).toBe('nosniff');
expect(web.headers.get('x-content-type-options')).toBe('nosniff');
}
});
it('SSE first two events', async () => { it('SSE first two events', async () => {
const nodeText = await (await fetch(base + '/api/s')).text(); const nodeText = await (await fetch(base + '/api/s')).text();
const webText = await (await app.fetch(new Request(base + '/api/s'))).text(); const webText = await (await app.fetch(new Request(base + '/api/s'))).text();
+34 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it, test, vi } from 'vitest'; import { describe, expect, it, test, vi } from 'vitest';
import { runPipeline, isStreamResult } from '../src/pipeline'; import { runPipeline, runSteps, isStreamResult } from '../src/pipeline';
import { Bus } from '../src/bus'; import { Bus } from '../src/bus';
import { JsonTransformer } from '../src/transformers'; import { JsonTransformer } from '../src/transformers';
import { Unauthorized } from '../src/signals'; import { Unauthorized } from '../src/signals';
@@ -100,3 +100,36 @@ describe('runPipeline transport enforcement', () => {
expect(isStreamResult(res)).toBe(true); expect(isStreamResult(res)).toBe(true);
}); });
}); });
describe('runSteps accumulation', () => {
// A chain where step k reads s{k-1} and provides s{k} = s{k-1} + 1: proves each
// step observes the previous ones' output (the graph's whole point).
const chain = (n: number) =>
Array.from({ length: n }, (_, i) => {
const k = i + 1;
return { name: `s${k}`, origin: 'mod', run: (ctx: any) => ({ [`s${k}`]: (ctx[`s${k - 1}`] ?? 0) + 1 }) };
});
it('each step sees prior outputs; the final context holds them all', async () => {
const ctx = await runSteps(chain(50), {}, new Bus());
expect(ctx.s1).toBe(1);
expect(ctx.s50).toBe(50); // 50 only lands if every step saw the previous
expect(Object.keys(ctx)).toHaveLength(50);
});
// Regression guard for the O(n^2) context merge (was `context = { ...context, ...output }`,
// which handed every step a freshly copied object — quadratic in the step count). The fix
// accumulates into ONE object in place, so every step must observe the same instance.
it('accumulates into a single object in place — never a per-step copy', async () => {
const seen: unknown[] = [];
const steps = Array.from({ length: 6 }, (_, i) => ({
name: `s${i}`,
origin: 'mod',
run: (ctx: any) => { seen.push(ctx); return { [`k${i}`]: i }; },
}));
const out = await runSteps(steps, { req: {} }, new Bus());
for (const ctx of seen) expect(ctx).toBe(seen[0]); // a spread would hand each step a new object
expect(out).toBe(seen[0]); // and the returned context is that same accumulator
expect((out as any).k5).toBe(5);
});
});
+77 -4
View File
@@ -1,5 +1,12 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect } from 'vitest';
import { matchPattern, matchRoute, allowedMethods } from '../src/http/router'; import {
compilePattern,
matchPattern,
matchRoute,
resolveRoute,
allowedMethods,
normalizeRequestPath,
} from '../src/http/router';
import type { RouteDef } from '../src/http/types'; import type { RouteDef } from '../src/http/types';
const route = (method: string, pattern: string): RouteDef => ({ const route = (method: string, pattern: string): RouteDef => ({
@@ -10,6 +17,11 @@ const route = (method: string, pattern: string): RouteDef => ({
}); });
describe('matchPattern', () => { describe('matchPattern', () => {
it('matches the root pattern only at root', () => {
expect(matchPattern('/', '/')).toEqual({});
expect(matchPattern('/', '/users')).toBeUndefined();
});
it('matches static and :param segments, decoding params', () => { it('matches static and :param segments, decoding params', () => {
expect(matchPattern('/users/:id', '/users/a%20b')).toEqual({ id: 'a b' }); expect(matchPattern('/users/:id', '/users/a%20b')).toEqual({ id: 'a b' });
expect(matchPattern('/users/:id', '/users')).toBeUndefined(); expect(matchPattern('/users/:id', '/users')).toBeUndefined();
@@ -24,6 +36,46 @@ describe('matchPattern', () => {
it(':name* matches zero remaining segments as an empty string', () => { it(':name* matches zero remaining segments as an empty string', () => {
expect(matchPattern('/files/:path*', '/files')).toEqual({ path: '' }); expect(matchPattern('/files/:path*', '/files')).toEqual({ path: '' });
}); });
it('matches safe constraints against the complete decoded segment', () => {
expect(matchPattern('/users/:id(\\d+)', '/users/42')).toEqual({ id: '42' });
expect(matchPattern('/users/:id(\\d+)', '/users/42x')).toBeUndefined();
expect(matchPattern('/posts/:slug([a-z0-9_-]+)', '/posts/green-tea_26')).toEqual({ slug: 'green-tea_26' });
expect(matchPattern('/build/:version(\\d{2}\\.\\d{1,2})', '/build/26.8')).toEqual({ version: '26.8' });
});
});
describe('compilePattern', () => {
it('records a stable shape independent of parameter names', () => {
expect(compilePattern('/users/:id').shape).toBe(compilePattern('/users/:name').shape);
expect(compilePattern('/users/:id(\\d+)').shape).not.toBe(compilePattern('/users/:id').shape);
});
it.each([
'/files/:rest*/tail',
'/users/:',
'/users/:id/:id',
'/users//:id',
'/users/:id((a+)+)',
'/users/:id((?=a)a)',
'/users/:id(\\1)',
'/users/:id(a|b)',
])('rejects invalid or unsafe pattern %s', (pattern) => {
expect(() => compilePattern(pattern)).toThrow(/invalid route pattern|unsafe route constraint/);
});
});
describe('normalizeRequestPath', () => {
it('treats one trailing slash as equivalent and preserves root', () => {
expect(normalizeRequestPath('/users')).toBe('/users');
expect(normalizeRequestPath('/users/')).toBe('/users');
expect(normalizeRequestPath('/')).toBe('/');
});
it('rejects repeated slashes and malformed percent encoding', () => {
expect(() => normalizeRequestPath('/users//42')).toThrow(/repeated slash/);
expect(() => normalizeRequestPath('/users/%E0%A4%A')).toThrow(/malformed path encoding/);
});
}); });
describe('matchRoute precedence', () => { describe('matchRoute precedence', () => {
@@ -34,6 +86,12 @@ describe('matchRoute precedence', () => {
expect(matchRoute(routes, 'GET', '/a/x/y')?.def.pattern).toBe('/a/:rest*'); expect(matchRoute(routes, 'GET', '/a/x/y')?.def.pattern).toBe('/a/:rest*');
}); });
it('constrained params beat unconstrained params regardless of registration order', () => {
const routes = [route('GET', '/users/:value'), route('GET', '/users/:id(\\d+)')];
expect(matchRoute(routes, 'GET', '/users/42')?.def.pattern).toBe('/users/:id(\\d+)');
expect(matchRoute(routes, 'GET', '/users/diego')?.def.pattern).toBe('/users/:value');
});
it('returns undefined when no pattern matches the path', () => { it('returns undefined when no pattern matches the path', () => {
expect(matchRoute([route('GET', '/a')], 'GET', '/b')).toBeUndefined(); expect(matchRoute([route('GET', '/a')], 'GET', '/b')).toBeUndefined();
}); });
@@ -44,9 +102,24 @@ describe('matchRoute precedence', () => {
}); });
describe('allowedMethods (405 support)', () => { describe('allowedMethods (405 support)', () => {
it('lists distinct methods whose pattern matches the path', () => { it('lists methods in canonical order with implicit HEAD and OPTIONS', () => {
const routes = [route('GET', '/a'), route('POST', '/a'), route('GET', '/b')]; const routes = [route('POST', '/a'), route('GET', '/a'), route('GET', '/b')];
expect(allowedMethods(routes, '/a').sort()).toEqual(['GET', 'POST']); expect(allowedMethods(routes, '/a')).toEqual(['GET', 'HEAD', 'POST', 'OPTIONS']);
expect(allowedMethods(routes, '/nope')).toEqual([]); expect(allowedMethods(routes, '/nope')).toEqual([]);
}); });
}); });
describe('resolveRoute', () => {
it('prefers explicit HEAD and otherwise falls back to buffered GET', () => {
const explicit = [route('GET', '/a'), route('HEAD', '/a')];
expect(resolveRoute(explicit, 'HEAD', '/a')).toMatchObject({ implicitHead: false, def: { method: 'HEAD' } });
const fallback = resolveRoute([route('GET', '/a')], 'HEAD', '/a');
expect(fallback).toMatchObject({ implicitHead: true, def: { method: 'GET' } });
});
it('does not use a streaming GET as implicit HEAD', () => {
const streaming = { ...route('GET', '/a'), transport: 'sse' as const };
expect(resolveRoute([streaming], 'HEAD', '/a')).toBeUndefined();
});
});
+8 -1
View File
@@ -1,6 +1,13 @@
import { expect, test } from 'vitest'; import { expect, test } from 'vitest';
import { VERSION } from '../src/index'; import { Head, Options, VERSION, type HttpMethod } from '../src/index';
test('package loads and exposes a CalVer VERSION', () => { test('package loads and exposes a CalVer VERSION', () => {
expect(VERSION).toMatch(/^\d{2}\.\d{1,2}\.\d+(-beta\.\d+)?$/); expect(VERSION).toMatch(/^\d{2}\.\d{1,2}\.\d+(-beta\.\d+)?$/);
}); });
test('public barrel exports HEAD and OPTIONS route decorators', () => {
const methods: HttpMethod[] = ['HEAD', 'OPTIONS'];
expect(Head).toBeTypeOf('function');
expect(Options).toBeTypeOf('function');
expect(methods).toEqual(['HEAD', 'OPTIONS']);
});
+17
View File
@@ -0,0 +1,17 @@
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
const workflow = readFileSync(resolve(process.cwd(), '.github/workflows/stage.yml'), 'utf8');
describe('Verdaccio staging workflow', () => {
it('replaces mutable prereleases only from release branches', () => {
expect(workflow).toContain("branches: ['release/**']");
expect(workflow).toContain('npm audit');
expect(workflow).toContain('npm run prepublishOnly');
expect(workflow).toContain('npm unpublish');
expect(workflow).toContain('npm publish --ignore-scripts');
expect(workflow).not.toContain('scripts/staging-integrity.ts');
});
});
+5 -5
View File
@@ -187,7 +187,7 @@ describe('CORS', () => {
expect(r.headers.get('access-control-allow-credentials')).toBe('true'); expect(r.headers.get('access-control-allow-credentials')).toBe('true');
}); });
it('disallowed origin → no allow-origin; bare OPTIONS (no ACRM) → 405 Allow for an existing path', async () => { it('disallowed origin → no allow-origin; bare OPTIONS (no ACRM) → automatic 204 Allow', async () => {
@Route('/') class C { @Get('/x') x() { return { ok: 1 }; } } @Route('/') class C { @Get('/x') x() { return { ok: 1 }; } }
@Module({ mountpoint: '/', controllers: [C] }) class CMod {} @Module({ mountpoint: '/', controllers: [C] }) class CMod {}
app = createApp({ modules: [CMod], cors: { origins: 'https://a.com' } }); app = createApp({ modules: [CMod], cors: { origins: 'https://a.com' } });
@@ -195,11 +195,11 @@ describe('CORS', () => {
const port = (server.address() as any).port; const port = (server.address() as any).port;
const r = await fetch(`http://127.0.0.1:${port}/x`, { headers: { origin: 'https://evil.com' } }); const r = await fetch(`http://127.0.0.1:${port}/x`, { headers: { origin: 'https://evil.com' } });
expect(r.headers.get('access-control-allow-origin')).toBeNull(); expect(r.headers.get('access-control-allow-origin')).toBeNull();
// A bare OPTIONS (no Access-Control-Request-Method) isn't a CORS preflight; the path exists // A bare OPTIONS (no Access-Control-Request-Method) isn't a CORS preflight; the router
// under GET, so the router answers 405 with an Allow header rather than 404. // answers it automatically and advertises the explicit + implicit methods.
const bare = await fetch(`http://127.0.0.1:${port}/x`, { method: 'OPTIONS' }); const bare = await fetch(`http://127.0.0.1:${port}/x`, { method: 'OPTIONS' });
expect(bare.status).toBe(405); expect(bare.status).toBe(204);
expect(bare.headers.get('allow')).toContain('GET'); expect(bare.headers.get('allow')).toBe('GET, HEAD, OPTIONS');
}); });
it("merges a handler's Title-Case Vary with CORS's Origin", async () => { it("merges a handler's Title-Case Vary with CORS's Origin", async () => {
+17 -1
View File
@@ -3,9 +3,24 @@ import starlight from '@astrojs/starlight';
// Docs site for @green-tea/core. Content lives in src/content/docs/**. // Docs site for @green-tea/core. Content lives in src/content/docs/**.
export default defineConfig({ export default defineConfig({
site: 'https://green-tea.dev', site: 'https://green-tea.expressive-tea.io',
base: '/docs',
integrations: [ integrations: [
starlight({ starlight({
// GoatCounter — same site code as the marketing site, so /docs traffic lands in
// the same dashboard and referrer paths stay comparable.
head: [
{
tag: 'script',
attrs: {
'data-goatcounter': 'https://greentea.goatcounter.com/count',
async: true,
src: '//gc.zgo.at/count.js',
},
},
],
// Let the content-backed 404.md own /404; otherwise Astro also injects a conflicting route.
disable404Route: true,
title: 'Green Tea.', title: 'Green Tea.',
description: 'A zen, opinionated, type-safe framework — your API is a graph, not a chain.', description: 'A zen, opinionated, type-safe framework — your API is a graph, not a chain.',
logo: { src: './src/assets/logo.svg', alt: 'Green Tea' }, logo: { src: './src/assets/logo.svg', alt: 'Green Tea' },
@@ -30,6 +45,7 @@ export default defineConfig({
{ {
label: 'Guides', label: 'Guides',
items: [ items: [
{ label: 'The matcha CLI', slug: 'guides/cli' },
{ label: 'Routing', slug: 'guides/routing' }, { label: 'Routing', slug: 'guides/routing' },
{ label: 'Dependency injection', slug: 'guides/dependency-injection' }, { label: 'Dependency injection', slug: 'guides/dependency-injection' },
{ label: 'Argument decorators', slug: 'guides/arguments' }, { label: 'Argument decorators', slug: 'guides/arguments' },
+161 -174
View File
@@ -6,35 +6,35 @@
"": { "": {
"name": "green-tea-docs", "name": "green-tea-docs",
"dependencies": { "dependencies": {
"@astrojs/starlight": "^0.41.3", "@astrojs/starlight": "^0.41.6",
"astro": "^7.0.6", "astro": "^7.1.6",
"sharp": "^0.35.3" "sharp": "^0.35.3"
} }
}, },
"node_modules/@astrojs/compiler-binding": { "node_modules/@astrojs/compiler-binding": {
"version": "0.3.0", "version": "0.3.2",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding/-/compiler-binding-0.3.0.tgz", "resolved": "https://registry.npmjs.org/@astrojs/compiler-binding/-/compiler-binding-0.3.2.tgz",
"integrity": "sha512-zlsOT5COD9hRwplJCgQhS21unxON5AKirf0vgt1ijXwuseYIaZdm2ZOpF8fsz+DY9EyXx+I/ukxtg7uoBep68A==", "integrity": "sha512-8w/9CWmYrAJJ8N0SY3O43ws2BgxoW6u3QsD8u2mE140lMYAlwh+tlNoUeSBq22wVheFuiBbR212l6ixZ2IIgCQ==",
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": "^20.19.0 || >=22.12.0" "node": "^20.19.0 || >=22.12.0"
}, },
"optionalDependencies": { "optionalDependencies": {
"@astrojs/compiler-binding-darwin-arm64": "0.3.0", "@astrojs/compiler-binding-darwin-arm64": "0.3.2",
"@astrojs/compiler-binding-darwin-x64": "0.3.0", "@astrojs/compiler-binding-darwin-x64": "0.3.2",
"@astrojs/compiler-binding-linux-arm64-gnu": "0.3.0", "@astrojs/compiler-binding-linux-arm64-gnu": "0.3.2",
"@astrojs/compiler-binding-linux-arm64-musl": "0.3.0", "@astrojs/compiler-binding-linux-arm64-musl": "0.3.2",
"@astrojs/compiler-binding-linux-x64-gnu": "0.3.0", "@astrojs/compiler-binding-linux-x64-gnu": "0.3.2",
"@astrojs/compiler-binding-linux-x64-musl": "0.3.0", "@astrojs/compiler-binding-linux-x64-musl": "0.3.2",
"@astrojs/compiler-binding-wasm32-wasi": "0.3.0", "@astrojs/compiler-binding-wasm32-wasi": "0.3.2",
"@astrojs/compiler-binding-win32-arm64-msvc": "0.3.0", "@astrojs/compiler-binding-win32-arm64-msvc": "0.3.2",
"@astrojs/compiler-binding-win32-x64-msvc": "0.3.0" "@astrojs/compiler-binding-win32-x64-msvc": "0.3.2"
} }
}, },
"node_modules/@astrojs/compiler-binding-darwin-arm64": { "node_modules/@astrojs/compiler-binding-darwin-arm64": {
"version": "0.3.0", "version": "0.3.2",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-darwin-arm64/-/compiler-binding-darwin-arm64-0.3.0.tgz", "resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-darwin-arm64/-/compiler-binding-darwin-arm64-0.3.2.tgz",
"integrity": "sha512-3n0uu+uJpnCq8b4JFi3uGDsIisAvHctxSmH+cIO9Gbei1H1Y1QXaYboXyiWJugUmprr3OEYP7+LdodzpVFzLMQ==", "integrity": "sha512-MM8tn8CSimcfytaOla4b6acN8mKWiL/rlAA1fpT3/Wl7dNGSE4y8FjTN/zJVNnb63CsLWG5zZwCt01TXtDKh9g==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -48,9 +48,9 @@
} }
}, },
"node_modules/@astrojs/compiler-binding-darwin-x64": { "node_modules/@astrojs/compiler-binding-darwin-x64": {
"version": "0.3.0", "version": "0.3.2",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-darwin-x64/-/compiler-binding-darwin-x64-0.3.0.tgz", "resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-darwin-x64/-/compiler-binding-darwin-x64-0.3.2.tgz",
"integrity": "sha512-scxNGKjOBydMo1QR4LtK0FMgh7ubQomJDv953nz2msQFkPKke/0FpPv/cQM0T/kuZdReZQFU8Oz3iOrP/6WHEg==", "integrity": "sha512-2lXOlzf8xb7jLomRsf/aswh61/NnGusynB2OwFkK6k4pmOtpfXMYnG0PLfXrEvxXYj69NdCnmUYXtHDd+JOOag==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -64,9 +64,9 @@
} }
}, },
"node_modules/@astrojs/compiler-binding-linux-arm64-gnu": { "node_modules/@astrojs/compiler-binding-linux-arm64-gnu": {
"version": "0.3.0", "version": "0.3.2",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-arm64-gnu/-/compiler-binding-linux-arm64-gnu-0.3.0.tgz", "resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-arm64-gnu/-/compiler-binding-linux-arm64-gnu-0.3.2.tgz",
"integrity": "sha512-NZrWLolVUANmrnl0zrFK/Sx5Sock1gEUT49ALfMTTCA5Ya2ec/BoJXMIg4KgE+wZcrdXJ8e+WyEhM7YLk/FJkA==", "integrity": "sha512-BmU3kWj7qnLrd4vzm49zFEPJ5oFnn1tCT4Vt9hZbqdU5Cmb8GZl7fn6VFsnNfe7B18a2gIFtVzbLINtYl5kBjQ==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -80,9 +80,9 @@
} }
}, },
"node_modules/@astrojs/compiler-binding-linux-arm64-musl": { "node_modules/@astrojs/compiler-binding-linux-arm64-musl": {
"version": "0.3.0", "version": "0.3.2",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-arm64-musl/-/compiler-binding-linux-arm64-musl-0.3.0.tgz", "resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-arm64-musl/-/compiler-binding-linux-arm64-musl-0.3.2.tgz",
"integrity": "sha512-PjwRmKgMFDsFhg82g0poXlIY8Qn3fMA3hXjaR0coJWJzTJsRH9ATU0j2ocigjtU1h3vL/yR7yLUxGj/lTCq73g==", "integrity": "sha512-f0heT9ZZEseSu5bHCeb80eL2DH07ArE6U9xi1WT/PEusNjzPmEr3GJsjG1tRLo5VYUUYX7h3ScaqGmGrMOVGmw==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -96,9 +96,9 @@
} }
}, },
"node_modules/@astrojs/compiler-binding-linux-x64-gnu": { "node_modules/@astrojs/compiler-binding-linux-x64-gnu": {
"version": "0.3.0", "version": "0.3.2",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-x64-gnu/-/compiler-binding-linux-x64-gnu-0.3.0.tgz", "resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-x64-gnu/-/compiler-binding-linux-x64-gnu-0.3.2.tgz",
"integrity": "sha512-Dr69VJYlnSfyL8gzELW6S4mE41P7TDPn1IKjwMnjdZ7+dxgJI50oMLFSk1LVe26bHmWB3ktuh8fDVK1THI9e9A==", "integrity": "sha512-M8fOUt0itRpqiGyoEA/ij184s8O+hqbCz3+YozRusOOM3osgGljpDThhbKAJjqh82wOo6FioQ4w8PBvU1XMD5Q==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -112,9 +112,9 @@
} }
}, },
"node_modules/@astrojs/compiler-binding-linux-x64-musl": { "node_modules/@astrojs/compiler-binding-linux-x64-musl": {
"version": "0.3.0", "version": "0.3.2",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-x64-musl/-/compiler-binding-linux-x64-musl-0.3.0.tgz", "resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-x64-musl/-/compiler-binding-linux-x64-musl-0.3.2.tgz",
"integrity": "sha512-AEt+bRw8PfImCcyRH1lpXVB8CdmQ1K/wPo5u99iec4/U/XdNvQZ715YVuNzIJpbJXelgQeZ5H2+Ea7XwRyWY5g==", "integrity": "sha512-/Kebk8sO6HnLeSd691JkaAPfN7CqR9/KEXmWvyNPkaKNGmj8rTZ/lf2uXtnPu92Lan84UrKdIKVPy1fSo2encQ==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -128,25 +128,25 @@
} }
}, },
"node_modules/@astrojs/compiler-binding-wasm32-wasi": { "node_modules/@astrojs/compiler-binding-wasm32-wasi": {
"version": "0.3.0", "version": "0.3.2",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-wasm32-wasi/-/compiler-binding-wasm32-wasi-0.3.0.tgz", "resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-wasm32-wasi/-/compiler-binding-wasm32-wasi-0.3.2.tgz",
"integrity": "sha512-U80tA1j8V6LjhiTZzVCtG4E8hrNVVNXDGV5fCgJ94q8FU9CPH+XwdDDhLzBybfWhKfyItXmQiZNRPTiPCYTpVg==", "integrity": "sha512-pUA6xbcOSB7DhfzIArB8BCAkFfAIqriiR7zl5zOStd6oU2G0kIKj+GUdGnyXyhfiv881Hffyk5tC0mR18sDjDw==",
"cpu": [ "cpu": [
"wasm32" "wasm32"
], ],
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"dependencies": { "dependencies": {
"@napi-rs/wasm-runtime": "^1.1.6" "@napi-rs/wasm-runtime": "^1.2.0"
}, },
"engines": { "engines": {
"node": ">=14.0.0" "node": ">=14.0.0"
} }
}, },
"node_modules/@astrojs/compiler-binding-win32-arm64-msvc": { "node_modules/@astrojs/compiler-binding-win32-arm64-msvc": {
"version": "0.3.0", "version": "0.3.2",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-win32-arm64-msvc/-/compiler-binding-win32-arm64-msvc-0.3.0.tgz", "resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-win32-arm64-msvc/-/compiler-binding-win32-arm64-msvc-0.3.2.tgz",
"integrity": "sha512-CpY1RII2r1XMpOUVD1VR/F2wtuRsiOCkFULS10Khyj8/DFZMtxVuUCAWGw+CW2Ka0h6eP3Xc1CA+glFlvXMPxA==", "integrity": "sha512-ESruf+6Qkl1trHUFxI6GSf6t52j8yN2kCNSzMWdzt7V/T09tFHrYzrVaJQohb2C9bJUH76pNvX6Zb51+xCQc9Q==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -160,9 +160,9 @@
} }
}, },
"node_modules/@astrojs/compiler-binding-win32-x64-msvc": { "node_modules/@astrojs/compiler-binding-win32-x64-msvc": {
"version": "0.3.0", "version": "0.3.2",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-win32-x64-msvc/-/compiler-binding-win32-x64-msvc-0.3.0.tgz", "resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-win32-x64-msvc/-/compiler-binding-win32-x64-msvc-0.3.2.tgz",
"integrity": "sha512-qmFbs769oeeGrRebAnCW7aBk8m71vf85W/dX/jddfx5Z06/w0wf7TZCfJPOX1Fld2t+4N+iXzfGEJG+zJQ+bzg==", "integrity": "sha512-wzzVrEbOwbsLWOdEbocskjMRx2aZPxJ7ZbmL+jnpBamFwmigm+2M/wzuM6JWncocgYwLic1csSpalBh96kQKXA==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -176,12 +176,12 @@
} }
}, },
"node_modules/@astrojs/compiler-rs": { "node_modules/@astrojs/compiler-rs": {
"version": "0.3.0", "version": "0.3.2",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-rs/-/compiler-rs-0.3.0.tgz", "resolved": "https://registry.npmjs.org/@astrojs/compiler-rs/-/compiler-rs-0.3.2.tgz",
"integrity": "sha512-J2qEVHtIDjEM9TxwmwuebOGmZNwhKu/dR7P7qBpnJKGmBBX0vdweQ/4cEXhj8fBbWVUB5V12xWChri3CgKNULQ==", "integrity": "sha512-xlx/T7JovIKduu4ucbTQUxQ5+Q8wxkHxhLjnZk3VlJbhbQ9RLvvuDk1p2YYFYFQ5y14dVm3FGGO4isQXa4F+Tg==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@astrojs/compiler-binding": "0.3.0" "@astrojs/compiler-binding": "0.3.2"
}, },
"engines": { "engines": {
"node": ">=22.12.0" "node": ">=22.12.0"
@@ -203,41 +203,33 @@
"unified": "^11.0.5" "unified": "^11.0.5"
} }
}, },
"node_modules/@astrojs/markdown-remark": { "node_modules/@astrojs/markdown-satteri": {
"version": "7.2.1", "version": "0.3.5",
"resolved": "https://registry.npmjs.org/@astrojs/markdown-remark/-/markdown-remark-7.2.1.tgz", "resolved": "https://registry.npmjs.org/@astrojs/markdown-satteri/-/markdown-satteri-0.3.5.tgz",
"integrity": "sha512-jPVNIqTvk+yKviikszv/Y1U4jGUSKpp/Nw48QZV4qjWgp70j4Lkq3lhSDRbWwCfgKvEyO9GHuVbV1dM2WYXy1w==", "integrity": "sha512-CvWVEFAbay7YO+i9SaqDJubipA5ckiVB89QWoMJ5XC0m5CtFg8JwZ7Kau6X9sYY7FZURH0w2l03ISH2jOS/RDQ==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@astrojs/internal-helpers": "0.10.1", "@astrojs/internal-helpers": "0.10.2",
"@astrojs/prism": "4.0.2", "@astrojs/prism": "4.0.2",
"github-slugger": "^2.0.0", "github-slugger": "^2.0.0",
"hast-util-from-html": "^2.0.3", "hast-util-from-html": "^2.0.3",
"hast-util-to-text": "^4.0.2", "satteri": "^0.9.1"
"mdast-util-definitions": "^6.0.0",
"rehype-raw": "^7.0.0",
"rehype-stringify": "^10.0.1",
"remark-gfm": "^4.0.1",
"remark-parse": "^11.0.0",
"remark-rehype": "^11.1.2",
"remark-smartypants": "^3.0.2",
"unified": "^11.0.5",
"unist-util-remove-position": "^5.0.0",
"unist-util-visit": "^5.1.0",
"unist-util-visit-parents": "^6.0.2",
"vfile": "^6.0.3"
} }
}, },
"node_modules/@astrojs/markdown-satteri": { "node_modules/@astrojs/markdown-satteri/node_modules/@astrojs/internal-helpers": {
"version": "0.3.3", "version": "0.10.2",
"resolved": "https://registry.npmjs.org/@astrojs/markdown-satteri/-/markdown-satteri-0.3.3.tgz", "resolved": "https://registry.npmjs.org/@astrojs/internal-helpers/-/internal-helpers-0.10.2.tgz",
"integrity": "sha512-Lje33Ittd8UQGgbIIWQvhPkj5X5c4b1sZnZWX3JQV/AWpfbuQGxVi2ONt6+ScydcwfR4egilslEWyczMclrJ1g==", "integrity": "sha512-yt7fMgPYqSM4Tmr+taTW6Per+hjJ8Pk6lA1PAcDyqzOt8HzJ6Kje5WzCxA2Sd+9wsUW7uhkLeoTMK0cXPwH9rQ==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@astrojs/internal-helpers": "0.10.1", "@types/hast": "^3.0.4",
"@astrojs/prism": "4.0.2", "@types/mdast": "^4.0.4",
"github-slugger": "^2.0.0", "js-yaml": "^4.3.0",
"satteri": "^0.9.1" "picomatch": "^4.0.4",
"retext-smartypants": "^6.2.0",
"shiki": "^4.0.2",
"smol-toml": "^1.6.0",
"unified": "^11.0.5"
} }
}, },
"node_modules/@astrojs/mdx": { "node_modules/@astrojs/mdx": {
@@ -274,6 +266,31 @@
} }
} }
}, },
"node_modules/@astrojs/mdx/node_modules/@astrojs/markdown-remark": {
"version": "7.2.1",
"resolved": "https://registry.npmjs.org/@astrojs/markdown-remark/-/markdown-remark-7.2.1.tgz",
"integrity": "sha512-jPVNIqTvk+yKviikszv/Y1U4jGUSKpp/Nw48QZV4qjWgp70j4Lkq3lhSDRbWwCfgKvEyO9GHuVbV1dM2WYXy1w==",
"license": "MIT",
"dependencies": {
"@astrojs/internal-helpers": "0.10.1",
"@astrojs/prism": "4.0.2",
"github-slugger": "^2.0.0",
"hast-util-from-html": "^2.0.3",
"hast-util-to-text": "^4.0.2",
"mdast-util-definitions": "^6.0.0",
"rehype-raw": "^7.0.0",
"rehype-stringify": "^10.0.1",
"remark-gfm": "^4.0.1",
"remark-parse": "^11.0.0",
"remark-rehype": "^11.1.2",
"remark-smartypants": "^3.0.2",
"unified": "^11.0.5",
"unist-util-remove-position": "^5.0.0",
"unist-util-visit": "^5.1.0",
"unist-util-visit-parents": "^6.0.2",
"vfile": "^6.0.3"
}
},
"node_modules/@astrojs/prism": { "node_modules/@astrojs/prism": {
"version": "4.0.2", "version": "4.0.2",
"resolved": "https://registry.npmjs.org/@astrojs/prism/-/prism-4.0.2.tgz", "resolved": "https://registry.npmjs.org/@astrojs/prism/-/prism-4.0.2.tgz",
@@ -298,9 +315,9 @@
} }
}, },
"node_modules/@astrojs/starlight": { "node_modules/@astrojs/starlight": {
"version": "0.41.3", "version": "0.41.6",
"resolved": "https://registry.npmjs.org/@astrojs/starlight/-/starlight-0.41.3.tgz", "resolved": "https://registry.npmjs.org/@astrojs/starlight/-/starlight-0.41.6.tgz",
"integrity": "sha512-8xsG6UpK581TJmtOc7/pnxHKEbP16rV06VLWaVa7FOyE/VEwnaHOsLtL+miifCEfuiuv0Wn+j8u3JSluRQesMQ==", "integrity": "sha512-Dt0/wY2JbFGUpxMgclw1j2Iqks2GG0LHYKgP7TfBXsFrs4LIbKvQ596lzyhXLz6nFcnPdIB9ZRFyDJeuVcx3Ug==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@astrojs/markdown-satteri": "^0.3.2", "@astrojs/markdown-satteri": "^0.3.2",
@@ -344,16 +361,15 @@
} }
}, },
"node_modules/@astrojs/telemetry": { "node_modules/@astrojs/telemetry": {
"version": "3.3.2", "version": "3.3.3",
"resolved": "https://registry.npmjs.org/@astrojs/telemetry/-/telemetry-3.3.2.tgz", "resolved": "https://registry.npmjs.org/@astrojs/telemetry/-/telemetry-3.3.3.tgz",
"integrity": "sha512-j8DNruA8ors99Al39RYZPJK4DC1bKkoNm93mAMuBhY9TCNC4R8n1q7ovFnJ5qhGh5Lsh7pa1gpQVpYpsJPeTHQ==", "integrity": "sha512-C1TLn5sPJr0x4vk56piHWKbnqlEB8BKyte5Y45V02U+D7BGO5eMqZDH5aPjnkXQWJggvmsTXxH03QMZ9NgWLzQ==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"ci-info": "^4.4.0", "ci-info": "^4.4.0",
"dset": "^3.1.4", "dset": "^3.1.4",
"is-docker": "^4.0.0", "is-docker": "^4.0.0",
"is-wsl": "^3.1.1", "package-manager-detector": "^1.6.0"
"which-pm-runs": "^1.1.0"
}, },
"engines": { "engines": {
"node": "18.20.8 || ^20.3.0 || >=22.0.0" "node": "18.20.8 || ^20.3.0 || >=22.0.0"
@@ -1625,21 +1641,24 @@
} }
}, },
"node_modules/@napi-rs/wasm-runtime": { "node_modules/@napi-rs/wasm-runtime": {
"version": "1.1.6", "version": "1.2.2",
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.6.tgz", "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.2.tgz",
"integrity": "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==", "integrity": "sha512-JfB4kuJQjaoHuCTseIINHtHWeJnvgEcxjwA5t/Y00ZgaOO1Crz3fjT/p8kT28zA/Caz7oiUMn3d6H2yOVCVwuw==",
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"dependencies": { "dependencies": {
"@tybys/wasm-util": "^0.10.3" "@tybys/wasm-util": "^0.10.3"
}, },
"engines": {
"node": "^20.19.0 || ^22.13.0 || >=23.5.0"
},
"funding": { "funding": {
"type": "github", "type": "github",
"url": "https://github.com/sponsors/Brooooooklyn" "url": "https://github.com/sponsors/Brooooooklyn"
}, },
"peerDependencies": { "peerDependencies": {
"@emnapi/core": "^1.7.1", "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.3",
"@emnapi/runtime": "^1.7.1" "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.3"
} }
}, },
"node_modules/@oslojs/encoding": { "node_modules/@oslojs/encoding": {
@@ -2359,15 +2378,15 @@
} }
}, },
"node_modules/astro": { "node_modules/astro": {
"version": "7.0.6", "version": "7.1.6",
"resolved": "https://registry.npmjs.org/astro/-/astro-7.0.6.tgz", "resolved": "https://registry.npmjs.org/astro/-/astro-7.1.6.tgz",
"integrity": "sha512-Myw0sFia+zs/Y0yqfZEsUYXfDPh3ELcLf1f0Q/qQzVXBh/af1qO62WNT+P89DCcfGVV51nMoQhEfkBYqJmoUOQ==", "integrity": "sha512-83x9rYbHazMaZkYrAFRVZXSQx2moFkz0F7cjTDUF3GWfS0a3p2vZXG1ZdhV86rStHApQCodBJW+XTD37xISIrQ==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@astrojs/compiler-rs": "^0.3.0", "@astrojs/compiler-rs": "^0.3.2",
"@astrojs/internal-helpers": "0.10.1", "@astrojs/internal-helpers": "0.10.2",
"@astrojs/markdown-satteri": "0.3.3", "@astrojs/markdown-satteri": "0.3.5",
"@astrojs/telemetry": "3.3.2", "@astrojs/telemetry": "3.3.3",
"@capsizecss/unpack": "^4.0.0", "@capsizecss/unpack": "^4.0.0",
"@clack/prompts": "^1.1.0", "@clack/prompts": "^1.1.0",
"@oslojs/encoding": "^1.1.0", "@oslojs/encoding": "^1.1.0",
@@ -2378,7 +2397,7 @@
"ci-info": "^4.4.0", "ci-info": "^4.4.0",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"common-ancestor-path": "^2.0.0", "common-ancestor-path": "^2.0.0",
"cookie": "^1.1.1", "cookie": "^2.0.1",
"devalue": "^5.8.1", "devalue": "^5.8.1",
"diff": "^8.0.3", "diff": "^8.0.3",
"dset": "^3.1.4", "dset": "^3.1.4",
@@ -2390,12 +2409,12 @@
"github-slugger": "^2.0.0", "github-slugger": "^2.0.0",
"html-escaper": "3.0.3", "html-escaper": "3.0.3",
"http-cache-semantics": "^4.2.0", "http-cache-semantics": "^4.2.0",
"js-yaml": "^4.1.1", "js-yaml": "^4.3.0",
"jsonc-parser": "^3.3.1", "jsonc-parser": "^3.3.1",
"magic-string": "^0.30.21", "magic-string": "^1.0.0",
"magicast": "^0.5.2", "magicast": "^0.5.2",
"mrmime": "^2.0.1", "mrmime": "^2.0.1",
"neotraverse": "^0.6.18", "neotraverse": "^1.0.1",
"obug": "^2.1.1", "obug": "^2.1.1",
"p-limit": "^7.3.0", "p-limit": "^7.3.0",
"p-queue": "^9.1.0", "p-queue": "^9.1.0",
@@ -2434,7 +2453,7 @@
"sharp": "^0.34.0 || ^0.35.0" "sharp": "^0.34.0 || ^0.35.0"
}, },
"peerDependencies": { "peerDependencies": {
"@astrojs/markdown-remark": "7.2.1" "@astrojs/markdown-remark": "7.2.2"
}, },
"peerDependenciesMeta": { "peerDependenciesMeta": {
"@astrojs/markdown-remark": { "@astrojs/markdown-remark": {
@@ -2455,6 +2474,31 @@
"astro": "^4.0.0-beta || ^5.0.0-beta || ^3.3.0 || ^6.0.0-beta || ^7.0.0" "astro": "^4.0.0-beta || ^5.0.0-beta || ^3.3.0 || ^6.0.0-beta || ^7.0.0"
} }
}, },
"node_modules/astro/node_modules/@astrojs/internal-helpers": {
"version": "0.10.2",
"resolved": "https://registry.npmjs.org/@astrojs/internal-helpers/-/internal-helpers-0.10.2.tgz",
"integrity": "sha512-yt7fMgPYqSM4Tmr+taTW6Per+hjJ8Pk6lA1PAcDyqzOt8HzJ6Kje5WzCxA2Sd+9wsUW7uhkLeoTMK0cXPwH9rQ==",
"license": "MIT",
"dependencies": {
"@types/hast": "^3.0.4",
"@types/mdast": "^4.0.4",
"js-yaml": "^4.3.0",
"picomatch": "^4.0.4",
"retext-smartypants": "^6.2.0",
"shiki": "^4.0.2",
"smol-toml": "^1.6.0",
"unified": "^11.0.5"
}
},
"node_modules/astro/node_modules/magic-string": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.1.0.tgz",
"integrity": "sha512-kS3VHe0nEPST2saQV4Rbkchcd3UBRkVTQHo1D3h/ZTwFDhai/mfKkmtPAtD129EOI7K3HlHIsFOt0WrI2/oU9g==",
"license": "MIT",
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
"node_modules/axobject-query": { "node_modules/axobject-query": {
"version": "4.1.0", "version": "4.1.0",
"resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz", "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz",
@@ -2633,12 +2677,12 @@
} }
}, },
"node_modules/cookie": { "node_modules/cookie": {
"version": "1.1.1", "version": "2.0.1",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", "resolved": "https://registry.npmjs.org/cookie/-/cookie-2.0.1.tgz",
"integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", "integrity": "sha512-yuToqVvRrj6pfDXREyQAAv8SkAEk/8GS3jQRTiUMm66TVtBYmqQeoEjL2Lmq8Rpo6271vH76InTChTitEAm65w==",
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=18" "node": ">=22"
}, },
"funding": { "funding": {
"type": "opencollective", "type": "opencollective",
@@ -3779,39 +3823,6 @@
"url": "https://github.com/sponsors/wooorm" "url": "https://github.com/sponsors/wooorm"
} }
}, },
"node_modules/is-inside-container": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/is-inside-container/-/is-inside-container-1.0.0.tgz",
"integrity": "sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA==",
"license": "MIT",
"dependencies": {
"is-docker": "^3.0.0"
},
"bin": {
"is-inside-container": "cli.js"
},
"engines": {
"node": ">=14.16"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/is-inside-container/node_modules/is-docker": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/is-docker/-/is-docker-3.0.0.tgz",
"integrity": "sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ==",
"license": "MIT",
"bin": {
"is-docker": "cli.js"
},
"engines": {
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/is-plain-obj": { "node_modules/is-plain-obj": {
"version": "4.1.0", "version": "4.1.0",
"resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz", "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz",
@@ -3824,25 +3835,10 @@
"url": "https://github.com/sponsors/sindresorhus" "url": "https://github.com/sponsors/sindresorhus"
} }
}, },
"node_modules/is-wsl": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-3.1.1.tgz",
"integrity": "sha512-e6rvdUCiQCAuumZslxRJWR/Doq4VpPR82kqclvcS0efgt430SlGIk05vdCN58+VrzgtIcfNODjozVielycD4Sw==",
"license": "MIT",
"dependencies": {
"is-inside-container": "^1.0.0"
},
"engines": {
"node": ">=16"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/js-yaml": { "node_modules/js-yaml": {
"version": "4.3.0", "version": "4.3.1",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.1.tgz",
"integrity": "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==", "integrity": "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==",
"funding": [ "funding": [
{ {
"type": "github", "type": "github",
@@ -5267,9 +5263,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/nanoid": { "node_modules/nanoid": {
"version": "3.3.15", "version": "3.3.16",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.15.tgz", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz",
"integrity": "sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA==", "integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==",
"funding": [ "funding": [
{ {
"type": "github", "type": "github",
@@ -5285,9 +5281,9 @@
} }
}, },
"node_modules/neotraverse": { "node_modules/neotraverse": {
"version": "0.6.18", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/neotraverse/-/neotraverse-0.6.18.tgz", "resolved": "https://registry.npmjs.org/neotraverse/-/neotraverse-1.0.1.tgz",
"integrity": "sha512-Z4SmBUweYa09+o6pG+eASabEpP6QkQ70yHj351pQoEXIs8uHbaU2DWVmzBANKgflPa47A50PtB2+NgRpQvr7vA==", "integrity": "sha512-WmmLty1YWwJl9yZi77v2dVIV6X2kuYV8YYBI/G3LWGKdGHmHUvL1z7FW0iDvEvGAwNEoc5x1tOOOyDnf5jJw/w==",
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">= 10" "node": ">= 10"
@@ -5533,9 +5529,9 @@
} }
}, },
"node_modules/postcss": { "node_modules/postcss": {
"version": "8.5.16", "version": "8.5.25",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.16.tgz", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.25.tgz",
"integrity": "sha512-vuwillviilfKZsg0VGj5R/YwwcHx4SLsIOI/7K6mQkWx+l5cUHTjj5g0AasTBcyXsbfTgrwsUNmVUb5xVwyPwg==", "integrity": "sha512-DTPx3RWSSnWyzLxQnlH0rJP+EW5ekl16ZU4/psbIhA0e53kJfdgaN5vKM+xP7yJtXVu+nfdVFmlgFDEKAe4Pyw==",
"funding": [ "funding": [
{ {
"type": "opencollective", "type": "opencollective",
@@ -5552,7 +5548,7 @@
], ],
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"nanoid": "^3.3.12", "nanoid": "^3.3.16",
"picocolors": "^1.1.1", "picocolors": "^1.1.1",
"source-map-js": "^1.2.1" "source-map-js": "^1.2.1"
}, },
@@ -6264,9 +6260,9 @@
} }
}, },
"node_modules/svgo": { "node_modules/svgo": {
"version": "4.0.1", "version": "4.0.2",
"resolved": "https://registry.npmjs.org/svgo/-/svgo-4.0.1.tgz", "resolved": "https://registry.npmjs.org/svgo/-/svgo-4.0.2.tgz",
"integrity": "sha512-XDpWUOPC6FEibaLzjfe0ucaV0YrOjYotGJO1WpF0Zd+n6ZGEQUsSugaoLq9QkEZtAfQIxT42UChcssDVPP3+/w==", "integrity": "sha512-ekx94z1rRc5LDi6oSUaeRnYhd0UOJxdtQCL2rF8xpWxD3TPAsISWOrxezqGovqS38GRZOdpDfvQe3ts6F7nsng==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"commander": "^11.1.0", "commander": "^11.1.0",
@@ -6807,15 +6803,6 @@
"url": "https://github.com/sponsors/wooorm" "url": "https://github.com/sponsors/wooorm"
} }
}, },
"node_modules/which-pm-runs": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/which-pm-runs/-/which-pm-runs-1.1.0.tgz",
"integrity": "sha512-n1brCuqClxfFfq/Rb0ICg9giSZqCS+pLtccdag6C2HyufBrh3fBOiy9nb6ggRMvWOVH5GrdJskj5iGTZNxd7SA==",
"license": "MIT",
"engines": {
"node": ">=4"
}
},
"node_modules/xxhash-wasm": { "node_modules/xxhash-wasm": {
"version": "1.1.0", "version": "1.1.0",
"resolved": "https://registry.npmjs.org/xxhash-wasm/-/xxhash-wasm-1.1.0.tgz", "resolved": "https://registry.npmjs.org/xxhash-wasm/-/xxhash-wasm-1.1.0.tgz",
+2 -2
View File
@@ -8,8 +8,8 @@
"preview": "astro preview" "preview": "astro preview"
}, },
"dependencies": { "dependencies": {
"@astrojs/starlight": "^0.41.3", "@astrojs/starlight": "^0.41.6",
"astro": "^7.0.6", "astro": "^7.1.6",
"sharp": "^0.35.3" "sharp": "^0.35.3"
} }
} }
+11
View File
@@ -0,0 +1,11 @@
---
title: Page not found
description: "The requested Green Tea documentation page does not exist."
template: splash
hero:
tagline: The documentation page you requested could not be found.
actions:
- text: Back to documentation
link: /docs/
icon: right-arrow
---
+2 -2
View File
@@ -3,7 +3,7 @@ title: The typed flow core
description: "The functional flow API where the compile-time dependency guarantee lives." description: "The functional flow API where the compile-time dependency guarantee lives."
--- ---
The [decorator layer](/guides/dependency-injection/) validates the graph at **boot**. The functional core, `flow`, validates it in the **type checker** — before the program ever runs. The [decorator layer](/docs/guides/dependency-injection/) validates the graph at **boot**. The functional core, `flow`, validates it in the **type checker** — before the program ever runs.
```typescript ```typescript
import { flow } from '@green-tea/core'; import { flow } from '@green-tea/core';
@@ -21,4 +21,4 @@ This is the strongest guarantee green-tea offers: the type *is* the dependency c
`npm run typecheck` in the repo includes a type-level test that asserts this accumulation behaves — a step that reads a missing key is expected to fail compilation. `npm run typecheck` in the repo includes a type-level test that asserts this accumulation behaves — a step that reads a missing key is expected to fail compilation.
::: :::
See [The dependency graph](/concepts/the-graph/) for how both layers describe the same model. See [The dependency graph](/docs/concepts/the-graph/) for how both layers describe the same model.
@@ -27,14 +27,14 @@ class Authenticate { /* ... */ }
- **No ordering bugs.** There's no positional `app.use()` sequence to get wrong; the sort is the order. - **No ordering bugs.** There's no positional `app.use()` sequence to get wrong; the sort is the order.
- **Each route runs only its slice.** A route runs the transitive closure of what its handler `@needs` (plus always-run observer steps) — an auth step doesn't run on a public route. - **Each route runs only its slice.** A route runs the transitive closure of what its handler `@needs` (plus always-run observer steps) — an auth step doesn't run on a public route.
- **Boot fails loudly.** If a handler needs a key nothing provides, `createApp` throws at boot with a "did you mean…?" hint — you never serve `undefined`. - **Boot fails loudly.** If a handler needs a key nothing provides, `createApp` throws at boot with a "did you mean…?" hint — you never serve `undefined`.
- **You can read it.** `app.explain(route)` prints the ordered chain with origins; `app.graph()` / `GET /__graph__` render it as a diagram. See [Graph introspection](/guides/introspection/). - **You can read it.** `app.explain(route)` prints the ordered chain with origins; `app.graph()` / `GET /__graph__` render it as a diagram. See [Graph introspection](/docs/guides/introspection/).
## Two layers ## Two layers
green-tea exposes the graph two ways: green-tea exposes the graph two ways:
1. **The typed functional core, [`flow`](/concepts/flow/)** — the compile-time guarantee. A handler that reads `ctx.user` fails to **compile** if no step produces `user`. 1. **The typed functional core, [`flow`](/docs/concepts/flow/)** — the compile-time guarantee. A handler that reads `ctx.user` fails to **compile** if no step produces `user`.
2. **The declarative decorator layer** — `@Provider` / `@Step` / `@Module` / `@Route` / `@Get` plus [argument decorators](/guides/arguments/). Emits runtime metadata, builds and sorts the graph, and validates at boot. 2. **The declarative decorator layer** — `@Provider` / `@Step` / `@Module` / `@Route` / `@Get` plus [argument decorators](/docs/guides/arguments/). Emits runtime metadata, builds and sorts the graph, and validates at boot.
Both describe the same graph; pick the ergonomics you want. Both describe the same graph; pick the ergonomics you want.
+18 -7
View File
@@ -3,7 +3,16 @@ title: Getting started
description: Install green-tea, configure TypeScript decorators, and build your first graph-based route. description: Install green-tea, configure TypeScript decorators, and build your first graph-based route.
--- ---
## Install ## Scaffold it
The fastest path is [matcha](/docs/guides/cli/), green-tea's CLI. It writes a project that runs on the first command — no wiring, no config:
```bash
matcha new my-api # --runtime node (default) | deno | bun
cd my-api && matcha run
```
## Or install by hand
```bash ```bash
npm install @green-tea/core reflect-metadata npm install @green-tea/core reflect-metadata
@@ -12,7 +21,9 @@ npm install ws # WebSocket routes (@Ws) and mesh
npm install busboy # multipart/form-data file uploads npm install busboy # multipart/form-data file uploads
``` ```
green-tea targets **Node ≥ 18** and uses **legacy** TypeScript decorators. Enable them in your `tsconfig.json`: green-tea runs on **Node ≥ 18, Deno, Bun, and the edge** — the same app, you only swap the entry point. This guide uses Node; see [runtimes](/docs/guides/runtimes/) for the others and for what the edge can't offer.
green-tea uses **legacy** TypeScript decorators. Enable them in your `tsconfig.json`:
```json ```json
{ {
@@ -24,7 +35,7 @@ green-tea targets **Node ≥ 18** and uses **legacy** TypeScript decorators. Ena
} }
``` ```
You do **not** need `emitDecoratorMetadata` — green-tea records argument positions explicitly. See [Why legacy decorators](/concepts/the-graph/#why-legacy-decorators) for the rationale. You do **not** need `emitDecoratorMetadata` — green-tea records argument positions explicitly. See [Why legacy decorators](/docs/concepts/the-graph/#why-legacy-decorators) for the rationale.
## Your first app ## Your first app
@@ -78,7 +89,7 @@ The handler asked for `user` via `@needs('user')`. If nothing in the graph produ
## Where to next ## Where to next
- [The dependency graph](/concepts/the-graph/) — the mental model behind everything. - [The dependency graph](/docs/concepts/the-graph/) — the mental model behind everything.
- [Dependency injection](/guides/dependency-injection/) — providers, steps, and modules in depth. - [Dependency injection](/docs/guides/dependency-injection/) — providers, steps, and modules in depth.
- [Argument decorators](/guides/arguments/) — everything a handler can inject. - [Argument decorators](/docs/guides/arguments/) — everything a handler can inject.
- [Streaming & real-time](/guides/streaming/) — SSE, WebSocket, and ndjson from one primitive. - [Streaming & real-time](/docs/guides/streaming/) — SSE, WebSocket, and ndjson from one primitive.
+7 -7
View File
@@ -34,7 +34,7 @@ getUser(@needs('user') user: any, @param('id') id: string) {
} }
``` ```
See [Dependency injection](/guides/dependency-injection/) for how `needs`/`provides` build the See [Dependency injection](/docs/guides/dependency-injection/) for how `needs`/`provides` build the
graph. graph.
## `@ctx` — the whole context ## `@ctx` — the whole context
@@ -94,7 +94,7 @@ needs a name to say which route param it binds. `@body(Schema)`, `@query(Schema)
object. object.
::: :::
A failing schema short-circuits the request with **422**. See [Validation](/guides/validation/) A failing schema short-circuits the request with **422**. See [Validation](/docs/guides/validation/)
for the full contract (fail-fast order, error shape, async schemas, and caveats). for the full contract (fail-fast order, error shape, async schemas, and caveats).
## Multipart access asymmetry ## Multipart access asymmetry
@@ -138,11 +138,11 @@ echo(@inbound() incoming: AsyncIterable<string>) {
} }
``` ```
See [Streaming](/guides/streaming/) for SSE, WebSocket duplex, and channels. See [Streaming](/docs/guides/streaming/) for SSE, WebSocket duplex, and channels.
## Where to go next ## Where to go next
- How injected values are produced: [Dependency injection](/guides/dependency-injection/). - How injected values are produced: [Dependency injection](/docs/guides/dependency-injection/).
- The mental model: [The graph](/concepts/the-graph/). - The mental model: [The graph](/docs/concepts/the-graph/).
- Validating and coercing injected values: [Validation](/guides/validation/). - Validating and coercing injected values: [Validation](/docs/guides/validation/).
- The full API surface: [Decorator reference](/reference/decorators/). - The full API surface: [Decorator reference](/docs/reference/decorators/).
+79
View File
@@ -0,0 +1,79 @@
---
title: The matcha CLI
description: "Scaffold, run, and generate green-tea apps from a single native binary."
---
**matcha** scaffolds green-tea projects, runs them in watch mode, and generates pieces already wired into your graph. It is a native binary — installing the CLI needs no JS runtime, and it only reaches for yours when it runs or type-checks your project.
That is deliberate: green-tea runs on Node, Deno, Bun, and the edge, so its tool shouldn't be bound to one of them.
## Install
```bash
curl -fsSL https://raw.githubusercontent.com/Expressive-Tea/matcha/main/install.sh | sh
```
Downloads a checksum-verified prebuilt binary into `~/.local/bin`. Environment variables go on the `sh` side of the pipe:
```bash
curl -fsSL …/install.sh | MATCHA_VERSION=v26.7.0 MATCHA_INSTALL_DIR=/usr/local/bin sh
```
From source, if you have Rust:
```bash
cargo install --git https://github.com/Expressive-Tea/matcha
```
## Scaffold — `matcha new`
```bash
matcha new my-api # Node (the default)
matcha new my-api --runtime deno # or deno | bun
matcha new my-api --template-url gh:owner/repo # any git template
```
The starter is alive on the first run: it serves an `index.html` and streams a rotating zen message over `@Sse('/zen')`. Open the browser and something is already moving — you are editing a working app, not assembling one.
Only the entry point and the config differ between runtimes. The `src/` tree is identical, which is the same portability the framework promises.
## Run — `matcha run`
```bash
matcha run
```
Detects the runtime and starts a watch loop. First match wins:
1. `matcha.toml` — an explicit `runtime = "node" | "deno" | "bun"`
2. `deno.json` / `deno.jsonc` → deno
3. `bun.lockb` / `bun.lock` → bun
4. `package.json` → node
Edge is a deploy target, not a `matcha run` target.
## Generate — `matcha create`
```bash
matcha create controller Users
matcha create step Authenticate
matcha create provider Database
matcha create module Billing
matcha create controller Users --check # type-check with your runtime afterward
```
Writes the file **and wires it in** — into the right `@Module` array, or into `createApp({ modules })` for a module.
## Extend — `matcha add`
```bash
matcha add sse # or: stream | buffer
```
Inserts a handler of that shape into your controller.
## How the edits stay safe
`create` and `add` edit your TypeScript with [tree-sitter](https://tree-sitter.github.io), not string splicing or regex. Edits are **idempotent** — running the same command twice doesn't duplicate anything — and they **revert themselves** if the result wouldn't parse. A generator that corrupts your source is worse than no generator.
One case it deliberately refuses: if `modules` is a variable (`modules: MODULES`) rather than an array literal, `create module` won't add a second `modules` key. Duplicate keys parse cleanly, so nothing would fail — it would just silently shadow your value. It tells you instead.
@@ -138,9 +138,9 @@ receive `undefined`. Boot fails loudly, so you never serve `undefined`.
## Where to go next ## Where to go next
- New to green-tea? Start with [Getting started](/getting-started/). - New to green-tea? Start with [Getting started](/docs/getting-started/).
- The mental model behind all of this: [The graph](/concepts/the-graph/). - The mental model behind all of this: [The graph](/docs/concepts/the-graph/).
- Everything a handler can inject: [Argument decorators](/guides/arguments/) and the - Everything a handler can inject: [Argument decorators](/docs/guides/arguments/) and the
[decorator reference](/reference/decorators/). [decorator reference](/docs/reference/decorators/).
- Coerce and validate injected values with Standard Schema: [Validation](/guides/validation/). - Coerce and validate injected values with Standard Schema: [Validation](/docs/guides/validation/).
- Declare `@Sse` and return an `AsyncIterable` to push data over time: [Streaming](/guides/streaming/). - Declare `@Sse` and return an `AsyncIterable` to push data over time: [Streaming](/docs/guides/streaming/).
+4 -4
View File
@@ -46,12 +46,12 @@ throw new HttpError(409, 'conflict', { code: 'DUP_EMAIL', field: 'email' });
Not everything should be JSON. Pass `onError` to `createApp` to render errors however you like — HTML, [RFC 7807](https://www.rfc-editor.org/rfc/rfc7807), content-negotiated, anything. It receives the error and the request, and returns a response — or `undefined` to fall back to the default JSON. Not everything should be JSON. Pass `onError` to `createApp` to render errors however you like — HTML, [RFC 7807](https://www.rfc-editor.org/rfc/rfc7807), content-negotiated, anything. It receives the error and the request, and returns a response — or `undefined` to fall back to the default JSON.
```typescript ```typescript
import { isHttpError } from '@green-tea/core'; import { HttpError } from '@green-tea/core';
const app = createApp({ const app = createApp({
modules: [ApiModule], modules: [ApiModule],
onError(error, req) { onError(error, req) {
const status = isHttpError(error) ? error.status : 500; const status = error instanceof HttpError ? error.status : 500;
// negotiate: HTML for browsers, JSON for API clients // negotiate: HTML for browsers, JSON for API clients
if (String(req.headers.accept).includes('text/html')) { if (String(req.headers.accept).includes('text/html')) {
return { status, headers: { 'content-type': 'text/html' }, body: `<h1>${status}</h1>` }; return { status, headers: { 'content-type': 'text/html' }, body: `<h1>${status}</h1>` };
@@ -61,8 +61,8 @@ const app = createApp({
}); });
``` ```
`onError` intercepts **every** HTTP error response — handler/step throws, a `404` for an unmatched route, `405`, a `413` (body too large), and a `400` (malformed body) — so your error surface is consistent across the whole app. Streaming and WebSocket errors are out of scope (they surface as an error frame or a WebSocket close code, not a response body). `onError` intercepts **every** HTTP error response — handler/step throws, a `404` for an unmatched route, `405`, a `413` (body too large), and a `400` (malformed body, repeated slash, or malformed path encoding) — so your error surface is consistent across the whole app. HEAD error responses keep the same status and headers but suppress the body. Streaming and WebSocket errors are out of scope (they surface as an error frame or a WebSocket close code, not a response body).
:::note :::note
Errors are also observable without changing the response: subscribe to `request:step:error` (and `stream:error`) on [`app.bus`](/guides/plugins/) to log or trace them. Errors are also observable without changing the response: subscribe to `request:step:error` (and `stream:error`) on [`app.bus`](/docs/guides/plugins/) to log or trace them.
::: :::
+4 -4
View File
@@ -37,7 +37,7 @@ class AboutController {
} }
``` ```
Reading a file needs a filesystem, so this mode is Node/Deno/Bun only — see [Runtimes](/guides/runtimes/) for the edge alternative. Reading a file needs a filesystem, so this mode is Node/Deno/Bun only — see [Runtimes](/docs/guides/runtimes/) for the edge alternative.
### 3. Render a template — Node/Deno/Bun ### 3. Render a template — Node/Deno/Bun
@@ -67,7 +67,7 @@ Same filesystem requirement as file mode: Node/Deno/Bun only.
`string`; `@Html('file.html', { template: true })` returns the data object rendered into the `string`; `@Html('file.html', { template: true })` returns the data object rendered into the
template; `@Html('file.html')` (no template) ignores the return entirely — annotate it `: void` template; `@Html('file.html')` (no template) ignores the return entirely — annotate it `: void`
by convention, e.g. `page(@needs('x')): void {}`. Returning an `AsyncIterable` from any `@Html` by convention, e.g. `page(@needs('x')): void {}`. Returning an `AsyncIterable` from any `@Html`
handler is the same buffered-route mismatch as any other `@Get`/`@Post`/`@Put`/`@Patch`/`@Delete` handler is the same buffered-route mismatch as any other `@Get`/`@Head`/`@Post`/`@Put`/`@Patch`/`@Delete`/`@Options`
handler: a 500 `TransportMismatchError`, not a silent raw stream. handler: a 500 `TransportMismatchError`, not a silent raw stream.
::: :::
@@ -134,7 +134,7 @@ const app3 = createApp({ modules: [ApiModule], static: '/srv/site' }); // absolu
- **Declared routes always win.** Static is only consulted when nothing matched, so `@Get('/api/ping')` is never shadowed by a file at `public/api/ping`. - **Declared routes always win.** Static is only consulted when nothing matched, so `@Get('/api/ping')` is never shadowed by a file at `public/api/ping`.
- Path traversal (`../`, encoded or not) is rejected — a request can't escape the static root. - Path traversal (`../`, encoded or not) is rejected — a request can't escape the static root.
Like the file/template modes of `@Html`, `static` needs a filesystem: it's Node/Deno/Bun only. Configuring it on an edge runtime throws at `createApp()` time — see [Runtimes](/guides/runtimes/). Like the file/template modes of `@Html`, `static` needs a filesystem: it's Node/Deno/Bun only. Configuring it on an edge runtime throws at `createApp()` time — see [Runtimes](/docs/guides/runtimes/).
## The boot rule ## The boot rule
@@ -145,7 +145,7 @@ Like the file/template modes of `@Html`, `static` needs a filesystem: it's Node/
@Html @Html
ticks() { /* ... */ } ticks() { /* ... */ }
// throws at createApp(): "@Html on GET /ticks is not allowed — // throws at createApp(): "@Html on GET /ticks is not allowed —
// @Html only supports buffered GET/POST routes (not SSE/WS/PUT/PATCH/DELETE)" // @Html only supports buffered GET/POST routes (not SSE/WS/HEAD/PUT/PATCH/DELETE/OPTIONS)"
``` ```
`@Html` and `@Transformer` also can't be combined on the same handler — pick one: `@Html` and `@Transformer` also can't be combined on the same handler — pick one:
@@ -3,7 +3,7 @@ title: Graph introspection
description: "explain, graph, toMermaid, and the graph endpoint." description: "explain, graph, toMermaid, and the graph endpoint."
--- ---
Because the request/boot pipeline is an explicit [dependency graph](/concepts/the-graph/), Because the request/boot pipeline is an explicit [dependency graph](/docs/concepts/the-graph/),
you can inspect it directly — visualize the whole thing, or explain exactly which nodes a you can inspect it directly — visualize the whole thing, or explain exactly which nodes a
single route runs. single route runs.
+80 -2
View File
@@ -7,10 +7,23 @@ description: "Distributed dependency injection over a secret-gated WebSocket con
Mesh is **alpha** — its API and wire protocol may change between releases, and discovery, load-balancing, and failover are not built. It is gated behind an explicit opt-in: `createApp({ mesh, experimental: true })`, and `createApp` **throws** if you configure `mesh` without `experimental: true`. **Don't ship mesh to production yet.** Mesh is **alpha** — its API and wire protocol may change between releases, and discovery, load-balancing, and failover are not built. It is gated behind an explicit opt-in: `createApp({ mesh, experimental: true })`, and `createApp` **throws** if you configure `mesh` without `experimental: true`. **Don't ship mesh to production yet.**
::: :::
A **teacup** can depend on a token that physically lives on another node — a **teapot**. `@needs('billing')` resolves the same whether `billing` runs in this process or on a remote one. There's no gRPC layer or message-pattern DSL: there's the [graph](/concepts/the-graph/), and some nodes happen to live elsewhere. A **teacup** can depend on a token that physically lives on another node — a **teapot**. `@needs('billing')` resolves the same whether `billing` runs in this process or on a remote one. There's no gRPC layer or message-pattern DSL: there's the [graph](/docs/concepts/the-graph/), and some nodes happen to live elsewhere.
Exports are opt-in (`export: true`) and the control channel is gated by a shared secret. Exports are opt-in (`export: true`) and the control channel is gated by a shared secret.
## What runs where
Mesh runs on **Node, Deno and Bun**, as both teapot and teacup, in any combination — a Deno teapot can serve a Node teacup. The wire is JSON over a WebSocket, so peers only have to agree on the protocol version, not the runtime.
**Edge (Cloudflare Workers) is not supported.** The teapot's secret comparison uses `node:crypto`'s `timingSafeEqual`, which workerd's `nodejs_compat` does not provide.
You do **not** need `listen()`. The graph boots on first use, so `Deno.serve`/`Bun.serve` work through `app.fetch`/`app.upgrade` like any other route:
```typescript
serveDeno(teapot, { port: 3002 }); // control channel served via app.upgrade
serveBun(teacup, { port: 3003 }); // teapots connected on the first request
```
## Node A — teapot (exposes `config`, `auth`, and a route) ## Node A — teapot (exposes `config`, `auth`, and a route)
```typescript ```typescript
@@ -60,7 +73,72 @@ await teacup.listen(3003);
- A **provider** export is **app-scope** — resolved once and cached. - A **provider** export is **app-scope** — resolved once and cached.
- A **step** export is **request-scope** — one RPC per request, carrying the request envelope. - A **step** export is **request-scope** — one RPC per request, carrying the request envelope.
Remote tokens become synthetic nodes in the local graph with RPC-backed runners, so the rest of the pipeline is unchanged. For non-mesh apps `createApp` stays synchronous; mesh apps defer graph finalization to `listen()` so remote scopes can join first. Remote tokens become synthetic nodes in the local graph with RPC-backed runners, so the rest of the pipeline is unchanged. For non-mesh apps `createApp` stays synchronous; a mesh app defers graph finalization until it boots — connecting to teapots is network I/O — and boots on whichever comes first: `app.fetch`, `app.upgrade` or `listen()`. Whoever triggers it, it happens once.
## Inspecting a mesh graph
`inspect()`, `graph()` and `explain()` are synchronous, but a mesh graph is not knowable until its teapots have been asked — so on a mesh app they throw until the graph is resolved. `await app.ready()` resolves it:
```typescript
await app.ready(); // connects the teapots; a no-op on a non-mesh app
app.graph(); // now includes the remote scopes
```
Write those two lines and your code works against either kind of app without knowing which it got. `ready()` deliberately does **not** boot providers — resolving the graph and being ready to serve are different things, and drawing a diagram should not open your database connections. Serving (`fetch`/`upgrade`/`listen`) boots them too and shares the same memoized step, so calling both never resolves the graph twice.
The dev routes (`/__graph__`, `/__openapi__`) need none of this: a request boots the app before the route runs.
## Buffered routes only
Mesh proxies **buffered** endpoints. `@Sse`, `@Stream` and `@Ws` routes are not exportable: a remote route is registered as `transport: 'buffer'`, and a handler that returns an `AsyncIterable` over a mesh call fails with `cannot proxy a streaming route`. Streams are a live socket between client and server; there is no meaningful way to relay one through an RPC hop today.
## One teapot per route
A route must be exported by exactly **one** teapot. If two export the same method and effective match shape — including patterns that differ only by parameter name, such as `/:id` and `/:name` — boot **fails**, naming both patterns and both teapots:
```
mesh: ambiguous remote route 'GET /api/shape/:name' from ws://b/__mesh__/control
conflicts with 'GET /api/shape/:id' from ws://a/__mesh__/control — load balancing
across teapots is not implemented yet, so green-tea will not choose one for you.
```
This is a hard error rather than a silent pick because there is no load balancing to fall back on: choosing one would be an arbitrary answer you could come to depend on. Scope tokens (`@Provider`/`@Step`) are unique for the same reason — and balancing them would be meaningless anyway, since an app-scope export is resolved once and cached.
**Local routes win.** If you declare a route locally *and* import the same effective method/shape from a teapot, yours takes precedence — that is how you override a teapot — and green-tea warns so a shadowed export doesn't look like a broken one:
```
[green-tea] mesh: route 'GET /api/svc/ping' is exported by teapot ws://a/… but also
declared locally — the local route takes precedence and the remote one will not be
reached. Remove one if that is not what you meant.
```
## When a teapot goes away
A dead upstream is not a broken service, and the status says which:
| What happened | Status |
| --- | --- |
| The link is down (closed, or the heartbeat gave up) | **503** Service Unavailable |
| The link is up but the teapot didn't answer in `timeoutMs` | **504** Gateway Timeout |
| The teapot answered with an error | whatever it said |
503 arrives **immediately** — a closed socket cannot deliver the frame, so waiting `timeoutMs` (30s by default) would just make the caller pay for a verdict already known.
Each teacup pings its teapots every `heartbeatMs` (15s by default) and closes a link after two unanswered rounds. This is what catches a **half-open** connection — a dropped route, a killed container, a NAT that timed out — where the socket still looks open with nobody home. Without it, a teacup only finds out on the next request, which pays the full timeout first.
```typescript
mesh: { teapots: [...], heartbeatMs: 5000 } // notice sooner, chatter more
```
Ping and pong are ordinary mesh frames rather than WebSocket protocol pings, because the platform `WebSocket` on Deno and Bun does not expose `ws.ping()` — a protocol-level heartbeat could not work on every runtime mesh supports.
**An app-scope export survives its teapot.** It is resolved once and memoised, so a provider keeps answering from cache after the link drops — with a value that can go stale. Reconnect reconciliation is a known gap.
## Protocol version
Peers are separate processes on separate deploy cadences, so the wire is versioned: `MESH_PROTOCOL_VERSION` travels in the `hello` and `manifest` frames, and a mismatch is refused on both sides with both versions named. A teapot checks the version **before** the secret — a skewed peer is not an authentication failure, and reporting it as one would send you hunting the wrong bug.
Bump the version and old peers refuse the connection loudly instead of misreading a frame.
:::note[Skeleton limitations (by design)] :::note[Skeleton limitations (by design)]
No discovery, load-balancing, or failover yet; app-scope remote values are not reconciled on reconnect; the request envelope omits `req.url`. No discovery, load-balancing, or failover yet; app-scope remote values are not reconciled on reconnect; the request envelope omits `req.url`.
+6 -4
View File
@@ -3,7 +3,7 @@ title: OpenAPI
description: "Generate a structural OpenAPI 3.1 document from the route graph." description: "Generate a structural OpenAPI 3.1 document from the route graph."
--- ---
Because the request pipeline is [data you can read](/concepts/the-graph/), green-tea can project it — the same way it renders [Mermaid/DOT](/guides/introspection/), it emits **OpenAPI**. Because the request pipeline is [data you can read](/docs/concepts/the-graph/), green-tea can project it — the same way it renders [Mermaid/DOT](/docs/guides/introspection/), it emits **OpenAPI**.
## `app.openapi()` ## `app.openapi()`
@@ -15,14 +15,16 @@ const spec = app.openapi({ title: 'My API', version: '1.0.0' });
It reads the routes and handler signatures and produces, for each route: It reads the routes and handler signatures and produces, for each route:
- the **path**, templated — `/users/:id` → `/users/{id}`, catch-all `:path*` → `{path}`; - the **path**, templated — `/users/:id` → `/users/{id}`, constrained `:id(\d+)` → `{id}`, catch-all `:path*` → `{path}`;
- the **method**; - the **explicitly declared method**, including `@Head` and `@Options`;
- **parameters** — path params from the pattern, plus query/header params from the handler's `@query` / `@headers` / `@header` decorators; - **parameters** — path params from the pattern, plus query/header params from the handler's `@query` / `@headers` / `@header` decorators;
- a **request body** entry for routes that read `@body()`; - a **request body** entry for routes that read `@body()`;
- the systematic **responses** — `200`, a `422` when any argument is schema-validated, and `500`. - the systematic **responses** — `200`, a `422` when any argument is schema-validated, and `500`.
WebSocket routes are omitted (they aren't request/response). WebSocket routes are omitted (they aren't request/response).
A constrained path parameter remains a string parameter and carries its route expression as `schema.pattern`. Only declared operations appear: implicit HEAD and automatic OPTIONS fallbacks are runtime conveniences and are not invented in the OpenAPI document.
## Serve it — `devOpenapi` ## Serve it — `devOpenapi`
Opt in to a `GET /__openapi__` endpoint that returns the document as JSON — point Swagger UI, Redoc, or a codegen client at it: Opt in to a `GET /__openapi__` endpoint that returns the document as JSON — point Swagger UI, Redoc, or a codegen client at it:
@@ -36,6 +38,6 @@ const app = createApp({ modules: [ApiModule], devOpenapi: true });
This is a **structural** spec: paths, methods, parameters, which routes take a body, and the standard error responses. What it does **not** include yet: This is a **structural** spec: paths, methods, parameters, which routes take a body, and the standard error responses. What it does **not** include yet:
- **Request/response body schemas.** [Standard Schema](/guides/validation/) (zod/valibot/arktype) validates input but does not expose a JSON Schema representation, so body shapes are documented generically. Parameter types default to `string`. - **Request/response body schemas.** [Standard Schema](/docs/guides/validation/) (zod/valibot/arktype) validates input but does not expose a JSON Schema representation, so body shapes are documented generically. Parameter types default to `string`.
Full schemas — declared and enforced on the way out via a `@Produce(schema)` decorator that also validates responses — are on the roadmap for the stable release. For beta, the structural document already drives Swagger UI, client codegen, and API diffing. Full schemas — declared and enforced on the way out via a `@Produce(schema)` decorator that also validates responses — are on the roadmap for the stable release. For beta, the structural document already drives Swagger UI, client codegen, and API diffing.
+3 -3
View File
@@ -30,7 +30,7 @@ and the framework computes where that node lands.
Because execution is per-route (a route runs only the transitive closure of its handler's Because execution is per-route (a route runs only the transitive closure of its handler's
`@needs`), a plugin step that should run on **every** route must produce nothing — add it `@needs`), a plugin step that should run on **every** route must produce nothing — add it
with `provides: []`. A step that produces no token has nothing to gate on, so the framework with `provides: []`. A step that produces no token has nothing to gate on, so the framework
runs it unconditionally. See [The graph](/concepts/the-graph/) for how the closure is runs it unconditionally. See [The graph](/docs/concepts/the-graph/) for how the closure is
computed. computed.
::: :::
@@ -42,7 +42,7 @@ mesh activity without touching the pipeline itself:
```typescript ```typescript
api.bus.on('boot:provider:ready', (p: any) => { /* ... */ }); api.bus.on('boot:provider:ready', (p: any) => { /* ... */ });
api.bus.on('request:step:enter', (p: any) => { /* ... */ }); api.bus.on('request:step:enter', (p: any) => { /* ... */ });
api.bus.on('request:step:exit', (p: any) => { /* ... */ }); api.bus.on('request:step:leave', (p: any) => { /* ... */ });
``` ```
The full event vocabulary: The full event vocabulary:
@@ -55,4 +55,4 @@ The full event vocabulary:
Observation is read-only: handlers see the event payload but can't alter control flow. To Observation is read-only: handlers see the event payload but can't alter control flow. To
change behavior, contribute a node to your scope — see change behavior, contribute a node to your scope — see
[Dependency injection](/guides/dependency-injection/). [Dependency injection](/docs/guides/dependency-injection/).
+24 -14
View File
@@ -1,6 +1,6 @@
--- ---
title: Routing title: Routing
description: "Route patterns, the catch-all, specificity precedence, and 405 handling." description: "Route constraints, specificity, HEAD and OPTIONS semantics, and path validation."
--- ---
Routes are declared with method decorators on a `@Route`-prefixed controller. Patterns are matched **by segment**. Routes are declared with method decorators on a `@Route`-prefixed controller. Patterns are matched **by segment**.
@@ -9,7 +9,7 @@ Routes are declared with method decorators on a `@Route`-prefixed controller. Pa
| Decorator | Method / transport | | Decorator | Method / transport |
|---|---| |---|---|
| `@Get` `@Post` `@Put` `@Patch` `@Delete` | buffered HTTP response | | `@Get` `@Head` `@Post` `@Put` `@Patch` `@Delete` `@Options` | buffered HTTP response |
| `@Sse` | server-sent events (`text/event-stream`) | | `@Sse` | server-sent events (`text/event-stream`) |
| `@Ws` | WebSocket duplex | | `@Ws` | WebSocket duplex |
| `@Stream` | negotiated — SSE / ndjson / WS, picked from the client's `Accept` / `Upgrade` | | `@Stream` | negotiated — SSE / ndjson / WS, picked from the client's `Accept` / `Upgrade` |
@@ -28,37 +28,47 @@ The path a route matches is `joinPath(module.mountpoint, route.path)` — a cont
- **Static** — `users` matches exactly. - **Static** — `users` matches exactly.
- **`:param`** — matches exactly one segment; the decoded value lands in `params.name` (`@param('id')`). - **`:param`** — matches exactly one segment; the decoded value lands in `params.name` (`@param('id')`).
- **`:param(constraint)`** — matches one complete decoded segment when it satisfies a safe regex subset, for example `:id(\d+)`.
- **`:name*` catch-all** — a trailing segment that captures the **rest of the path, slashes included**, into `params.name`. - **`:name*` catch-all** — a trailing segment that captures the **rest of the path, slashes included**, into `params.name`.
```typescript ```typescript
@Get('/users/:id(\\d+)') // /users/42 matches; /users/alice does not
@Get('/files/:path*') // /files/img/2026/logo.png → params.path = "img/2026/logo.png" @Get('/files/:path*') // /files/img/2026/logo.png → params.path = "img/2026/logo.png"
``` ```
A catch-all also matches zero remaining segments (`/files` → `params.path = ""`). A catch-all also matches zero remaining segments (`/files` → `params.path = ""`).
Constraints are anchored to the whole segment automatically. They allow character classes, alphanumeric/literal atoms, the escaped character classes `\d`, `\D`, `\s`, `\S`, `\w`, `\W`, and simple quantifiers (`+`, `*`, `?`, `{n}`, `{n,m}`). Groups, alternation, lookarounds, backreferences, anchors, and other arbitrary regex features are rejected at boot. Expressions are limited to 128 characters, counted quantifiers are capped, and unsafe adjacent unbounded quantifiers are rejected. This deliberately small subset avoids accepting route regexes with obvious ReDoS shapes.
Patterns must start with `/`, parameter names must be unique and use identifier syntax, and a catch-all must be the final segment. Repeated slashes in a declared pattern fail at boot.
## Precedence ## Precedence
When more than one route matches the same path, the **most specific wins** — `static ▸ :param ▸ catch-all` — compared segment by segment, **independent of registration order**. Genuine ties (two equally-specific patterns) fall back to registration order. When more than one route matches the same path, the **most specific wins** — `static ▸ constrained :param ▸ plain :param ▸ catch-all` — compared segment by segment, independent of registration order.
```typescript ```typescript
@Get('/a/b') // wins for /a/b @Get('/a/b') // wins for /a/b
@Get('/a/:id(\\d+)') // wins for /a/42 over the plain parameter
@Get('/a/:id') // wins for /a/x @Get('/a/:id') // wins for /a/x
@Get('/a/:rest*') // wins for /a/x/y @Get('/a/:rest*') // wins for /a/x/y
``` ```
## 404 vs 405 Two routes under the same method cannot have the same effective shape: `/users/:id` and `/users/:name` are ambiguous and make boot fail with both declarations named. The same rule applies after mesh routes join. Different methods may reuse a shape.
## HEAD and OPTIONS
An explicit `@Head` or `@Options` route always wins. Without an explicit HEAD route, HEAD falls back to a matching **buffered** GET handler, preserves its status and headers, and suppresses the body. Streaming GET routes do not become implicit HEAD routes.
Without an explicit OPTIONS route, OPTIONS on an existing path returns `204` with a canonical `Allow` header. GET implies HEAD, and any existing path implies OPTIONS, so a GET/POST path reports `GET, HEAD, POST, OPTIONS`. A CORS preflight (OPTIONS with `Access-Control-Request-Method`) is handled before explicit or automatic OPTIONS when CORS is configured.
## Path policy and 404 vs 405
`/path` and `/path/` are equivalent. Repeated slashes such as `/path//item` are rejected rather than collapsed, and malformed percent encoding is rejected; both return `400 Bad Request` with the configured security/CORS headers. Query strings do not participate in route matching.
A path that no route matches returns `404`. A path that **does** exist but under a different method returns **`405 Method Not Allowed`** with an `Allow` header listing the methods that do match — not a `404`. A path that no route matches returns `404`. A path that **does** exist but under a different method returns **`405 Method Not Allowed`** with an `Allow` header listing the methods that do match — not a `404`.
:::note ## Matcher scale
A bare `OPTIONS` request (without an `Access-Control-Request-Method` header — i.e. not a CORS preflight) to an existing path therefore returns `405` with `Allow`. CORS preflights are handled separately; see [Transport security](/guides/security/).
:::
## Not yet Route matching remains a **linear scan** — fine for typical route tables. A radix-tree matcher for very large route tables remains on the roadmap.
The matcher is intentionally small for beta. **Not built** (on the roadmap): See [Streaming & real-time](/docs/guides/streaming/) for `@Sse` / `@Ws` / `@Stream`, and [Argument decorators](/docs/guides/arguments/) for everything a handler can read from a request.
- Regex / typed param constraints such as `:id(\d+)`.
- Route matching is a **linear scan** — fine for typical route tables, but a radix-tree matcher for very large ones isn't implemented.
See [Streaming & real-time](/guides/streaming/) for `@Sse` / `@Ws` / `@Stream`, and [Argument decorators](/guides/arguments/) for everything a handler can read from a request.
+19 -12
View File
@@ -22,13 +22,17 @@ Bun.serve({ fetch: app.fetch });
export default { fetch: app.fetch }; export default { fetch: app.fetch };
``` ```
**Node is the reference implementation** — every runtime returns the same status, headers, **Node is the reference implementation.** A parity suite pins `app.fetch` to Node's native
and body for the same request (enforced by a parity test suite). listener — identical status, headers, and body for the same request. The other runtimes drive
that *same* `app.fetch` / `app.upgrade` core, so they inherit that behaviour rather than
re-implementing it, and each carries its own smoke tests: Deno and Bun cover WebSocket and mesh,
and edge runs against real workerd (Miniflare).
**All four runtimes now have full WebSocket support:** Node, Deno, and Bun via `serveDeno` / **All four runtimes now have full WebSocket support:** Node via `app.listen()`, Deno and Bun via
`serveBun`, and Cloudflare Workers / edge via `edgeHandler` (see below) — same graph, same `serveDeno` / `serveBun`, and Cloudflare Workers / edge via `edgeHandler` (see below) — same graph,
`@Ws` handlers, same rooms/channels everywhere. `app.listen()`, TLS, per-request timeouts, same `@Ws` handlers, same rooms/channels everywhere. `app.listen()`, TLS and per-request timeouts
and mesh remain Node-only; on Deno/Bun/edge you get `app.fetch` + the runtime's adapter. remain Node-only; on Deno/Bun/edge you get `app.fetch` + the runtime's adapter. **Mesh (alpha)
runs on Node, Deno and Bun** — teapot and teacup, in any combination — but not on edge.
**Body-size enforcement differs slightly:** on `app.fetch`, an oversized body is read in full **Body-size enforcement differs slightly:** on `app.fetch`, an oversized body is read in full
before the `413` is returned, whereas Node aborts mid-stream once the limit is hit — so on before the `413` is returned, whereas Node aborts mid-stream once the limit is hit — so on
@@ -58,8 +62,9 @@ Any runtime can build a `WsSocket` capability (`inbound`, `abort`, `isOpen`, `se
`close`, `terminate`) and drive the graph — `serveBun` and `edgeHandler` build on the `close`, `terminate`) and drive the graph — `serveBun` and `edgeHandler` build on the
same primitive (see below). same primitive (see below).
**Still Node-only:** `app.listen()`, TLS, per-request timeouts, and mesh. On Deno you **Still Node-only:** `app.listen()`, TLS and per-request timeouts. On Deno you get
get `app.fetch` + `serveDeno`. `app.fetch` + `serveDeno`. [Mesh](/docs/guides/mesh/) works here: the control channel is
served through `app.upgrade` and the teacup connects with Deno's global `WebSocket`.
## WebSocket on Bun ## WebSocket on Bun
@@ -80,8 +85,8 @@ serveBun(app, { port: 8000 });
`app.upgrade` — the same graph, the same `@Ws` handlers, the same rooms/channels you `app.upgrade` — the same graph, the same `@Ws` handlers, the same rooms/channels you
run on Node and Deno. Behaviour matches the Node reference. run on Node and Deno. Behaviour matches the Node reference.
**Still Node-only:** `app.listen()`, TLS, per-request timeouts, and mesh. On Bun you **Still Node-only:** `app.listen()`, TLS and per-request timeouts. On Bun you get
get `app.fetch` + `serveBun`. `app.fetch` + `serveBun`. [Mesh](/docs/guides/mesh/) works here too.
## Cloudflare Workers / edge ## Cloudflare Workers / edge
@@ -113,14 +118,16 @@ compatibility_date = "2024-09-23" # or later
Green Tea's core statically imports Node built-ins that workerd only provides under Green Tea's core statically imports Node built-ins that workerd only provides under
this flag; without it, the Worker fails to load. this flag; without it, the Worker fails to load.
**Still Node-only:** `app.listen()`, TLS, per-request timeouts, and mesh. Cloudflare's **Still Node-only:** `app.listen()`, TLS and per-request timeouts. [Mesh](/docs/guides/mesh/)
is **not** supported on edge: the teapot's secret comparison needs `node:crypto`'s
`timingSafeEqual`, which `nodejs_compat` does not provide. Cloudflare's
Durable Objects and WebSocket Hibernation are **not** used — `edgeHandler` accepts Durable Objects and WebSocket Hibernation are **not** used — `edgeHandler` accepts
WebSockets with the standard `WebSocketPair` model, so a Worker holds the connection WebSockets with the standard `WebSocketPair` model, so a Worker holds the connection
open for its lifetime rather than hibernating between messages. open for its lifetime rather than hibernating between messages.
## Filesystem features — Node/Deno/Bun only ## Filesystem features — Node/Deno/Bun only
A few [HTML & views](/guides/html/) features read from disk, so they need a runtime with A few [HTML & views](/docs/guides/html/) features read from disk, so they need a runtime with
a filesystem: a filesystem:
- `@Html('file.html')` — reads and caches the file at boot. - `@Html('file.html')` — reads and caches the file at boot.
+6 -4
View File
@@ -4,7 +4,7 @@ description: "TLS and wss, secure-by-default headers, CORS, and trustProxy."
--- ---
Four `createApp` options cover TLS, proxying, CORS, and response headers: `tls`, Four `createApp` options cover TLS, proxying, CORS, and response headers: `tls`,
`trustProxy`, `cors`, and `security`. See the [`createApp` reference](/reference/createapp/) `trustProxy`, `cors`, and `security`. See the [`createApp` reference](/docs/reference/createapp/)
for the full option list. for the full option list.
## TLS (native https/wss) ## TLS (native https/wss)
@@ -44,7 +44,9 @@ const app = createApp({
``` ```
`origins` accepts `string | string[] | '*' | (origin) => boolean`. A preflight `OPTIONS` `origins` accepts `string | string[] | '*' | (origin) => boolean`. A preflight `OPTIONS`
request (with `Access-Control-Request-Method`) is auto-answered with 204. request (with `Access-Control-Request-Method`) is auto-answered with 204 before explicit or
automatic OPTIONS routing. A bare OPTIONS request is instead handled by an explicit `@Options`
route or the router's automatic `204` + `Allow` response.
- With `credentials: true`, the server **never** sends `Access-Control-Allow-Origin: *` — it - With `credentials: true`, the server **never** sends `Access-Control-Allow-Origin: *` — it
echoes the concrete allowed origin (or blocks the request). echoes the concrete allowed origin (or blocks the request).
@@ -97,5 +99,5 @@ strips and sets forwarded headers itself, and terminate TLS where you control th
## Related ## Related
- [`createApp` reference](/reference/createapp/) — every construction option - [`createApp` reference](/docs/reference/createapp/) — every construction option
- [File uploads / multipart](/guides/uploads/) — request-body handling - [File uploads / multipart](/docs/guides/uploads/) — request-body handling
+5 -6
View File
@@ -7,23 +7,22 @@ Most stacks treat "push data over time" as a bolt-on: Express reaches for a `ws`
green-tea has one model: an **`AsyncIterable`**. A handler that returns a sequence of values over time *is* a stream — the same shape you'd return from any function. You **declare the mode** with a decorator; the framework handles framing, backpressure, cleanup, and disconnects. green-tea has one model: an **`AsyncIterable`**. A handler that returns a sequence of values over time *is* a stream — the same shape you'd return from any function. You **declare the mode** with a decorator; the framework handles framing, backpressure, cleanup, and disconnects.
## One primitive, four modes ## One primitive, three modes
| Declare | Direction | Transport | Reach for it when | | Declare | Direction | Transport | Reach for it when |
|---|---|---|---| |---|---|---|---|
| `@Sse` | server → client | `text/event-stream` | live updates to a browser (`EventSource`) | | `@Sse` | server → client | `text/event-stream` | live updates to a browser (`EventSource`) |
| `@Ws` | duplex | WebSocket | chat, collaboration — anything two-way | | `@Ws` | duplex | WebSocket | chat, collaboration — anything two-way |
| `@Stream` | negotiated | SSE / ndjson / WS, picked from the client's `Accept` / `Upgrade` | one handler, the client chooses | | `@Stream` | negotiated | SSE / ndjson / WS, picked from the client's `Accept` / `Upgrade` | one handler, the client chooses |
| *(plain return)* | server → client | SSE or ndjson by `Accept` | programmatic streaming over `fetch` |
The primitive never changes — it's always an `AsyncIterable`. What changes is **direction and framing**, and you declare which. That's the difference between each iterable green-tea hands you: The primitive never changes — it's always an `AsyncIterable`. What changes is **direction and framing**, and you declare which. That's the difference between each iterable green-tea hands you:
- **`@Sse` / plain return** — you return **one** iterable: the *outbound* stream. Each `yield` becomes an SSE event, or an ndjson line. - **`@Sse`** — you return **one** iterable: the *outbound* stream. Each `yield` becomes an SSE event, or an ndjson line.
- **`@Ws` (duplex)** — **two** iterables. `@inbound()` gives you the client's *incoming* messages to consume; the one you **return** is the *outbound* stream to the client. `@abort()` hands you an `AbortSignal` for teardown. - **`@Ws` (duplex)** — **two** iterables. `@inbound()` gives you the client's *incoming* messages to consume; the one you **return** is the *outbound* stream to the client. `@abort()` hands you an `AbortSignal` for teardown.
- **`@Stream`** — you write the handler once; the client's request decides whether it arrives as SSE, ndjson, or a WebSocket. No branching in your code. - **`@Stream`** — you write the handler once; the client's request decides whether it arrives as SSE, ndjson, or a WebSocket. No branching in your code.
:::note :::note
Streaming bypasses the response transformer — the transport frames each value directly, handles backpressure, and cleans up on disconnect. See [arguments](/guides/arguments/) for the full list of argument decorators, including the stream-only `@inbound()` and `@abort()`. Streaming bypasses the response transformer — the transport frames each value directly, handles backpressure, and cleans up on disconnect. See [arguments](/docs/guides/arguments/) for the full list of argument decorators, including the stream-only `@inbound()` and `@abort()`.
::: :::
## Streaming — SSE ## Streaming — SSE
@@ -102,7 +101,7 @@ class Live {
Same `@Route`, same handler shape, same `AsyncIterable` — real-time is not a separate framework you also have to learn. Same `@Route`, same handler shape, same `AsyncIterable` — real-time is not a separate framework you also have to learn.
`rooms` is the built-in shared `Rooms` primitive (one instance app-wide). A typical chat handler pumps the `@inbound()` channel into `rooms.room(name)` and returns that same room as its outbound channel, so every joined socket multicasts to the others. A handshake `@Step` can read `?token=` and throw `Unauthorized` — which closes the socket with code **4401** (`4000 + status`). See [security](/guides/security/) for handshake authentication. `rooms` is the built-in shared `Rooms` primitive (one instance app-wide). A typical chat handler pumps the `@inbound()` channel into `rooms.room(name)` and returns that same room as its outbound channel, so every joined socket multicasts to the others. A handshake `@Step` can read `?token=` and throw `Unauthorized` — which closes the socket with code **4401** (`4000 + status`). See [security](/docs/guides/security/) for handshake authentication.
## Transport is declared, not inferred ## Transport is declared, not inferred
@@ -110,7 +109,7 @@ A route streams **because** it's declared `@Sse`, `@Stream`, or `@Ws` — never
| Declare | Handler must return | Otherwise | | Declare | Handler must return | Otherwise |
|---|---|---| |---|---|---|
| `@Get` / `@Post` / `@Put` / `@Patch` / `@Delete` (buffered) | a value | returning an `AsyncIterable` fails with a 500 `TransportMismatchError` | | `@Get` / `@Head` / `@Post` / `@Put` / `@Patch` / `@Delete` / `@Options` (buffered) | a value | returning an `AsyncIterable` fails with a 500 `TransportMismatchError` |
| `@Sse` / `@Ws` (streaming) | an `AsyncIterable` | returning a plain value fails with a 500 `TransportMismatchError` | | `@Sse` / `@Ws` (streaming) | an `AsyncIterable` | returning a plain value fails with a 500 `TransportMismatchError` |
| `@Stream` (negotiate) | either | the client picks via `Accept` / `Upgrade` — no mismatch | | `@Stream` (negotiate) | either | the client picks via `Accept` / `Upgrade` — no mismatch |
+1 -1
View File
@@ -29,5 +29,5 @@ An override for an unknown token throws. The set of tokens is validated against
graph, so a typo'd or stale override is a construction-time error, not a silent no-op. graph, so a typo'd or stale override is a construction-time error, not a silent no-op.
::: :::
This pairs well with [`app.explain(route)`](/guides/introspection/) — explain the chain to This pairs well with [`app.explain(route)`](/docs/guides/introspection/) — explain the chain to
see which tokens a route actually depends on, then override exactly those. see which tokens a route actually depends on, then override exactly those.
+2 -2
View File
@@ -27,7 +27,7 @@ class ProfileController {
`UploadedFile` is `{ filename, contentType, data: Buffer, size }` — the whole file is buffered in memory, no temp files. `UploadedFile` is `{ filename, contentType, data: Buffer, size }` — the whole file is buffered in memory, no temp files.
:::note[Access asymmetry] :::note[Access asymmetry]
For multipart, `@body('title')` returns `undefined` — the value lives at `body.fields.title`, not `body.title`, unlike JSON/urlencoded where `@body('title')` picks the value directly. Use `@body()` and read `.fields`/`.files`, or key into the envelope itself with `@body('fields')` / `@body('files')`. See [arguments](/guides/arguments/) for how `@body()` behaves across content types. For multipart, `@body('title')` returns `undefined` — the value lives at `body.fields.title`, not `body.title`, unlike JSON/urlencoded where `@body('title')` picks the value directly. Use `@body()` and read `.fields`/`.files`, or key into the envelope itself with `@body('fields')` / `@body('files')`. See [arguments](/docs/guides/arguments/) for how `@body()` behaves across content types.
::: :::
## Repeated fields — `bodyDuplicates` ## Repeated fields — `bodyDuplicates`
@@ -67,5 +67,5 @@ uploadAvatar(@body() form: MultipartBody) { /* ... */ }
A route's `maxBodyBytes` / `maxParts` fall back to the server-wide `limits` when unset. A malformed multipart body (bad boundary, missing headers, truncated part) → **400**. A route's `maxBodyBytes` / `maxParts` fall back to the server-wide `limits` when unset. A malformed multipart body (bad boundary, missing headers, truncated part) → **400**.
:::note :::note
To validate parsed fields against a schema, pass a Standard Schema to `@body()` — see [validation](/guides/validation/). To validate parsed fields against a schema, pass a Standard Schema to `@body()` — see [validation](/docs/guides/validation/).
::: :::
@@ -48,7 +48,7 @@ needs a name to say which route param it binds. `@body(Schema)`, `@query(Schema)
object (all of `body`/`query`/`headers`). object (all of `body`/`query`/`headers`).
::: :::
See [Argument decorators](/guides/arguments/) for the full slot semantics of each decorator. See [Argument decorators](/docs/guides/arguments/) for the full slot semantics of each decorator.
## Failure: 422 with per-field issues ## Failure: 422 with per-field issues
@@ -79,6 +79,6 @@ validation are all out of scope for this feature.
## Related ## Related
- [Argument decorators](/guides/arguments/) — every slot decorator and its parsing rules - [Argument decorators](/docs/guides/arguments/) — every slot decorator and its parsing rules
- [File uploads / multipart](/guides/uploads/) — how multipart bodies are parsed before validation - [File uploads / multipart](/docs/guides/uploads/) — how multipart bodies are parsed before validation
- [`createApp` reference](/reference/createapp/) — app construction options - [`createApp` reference](/docs/reference/createapp/) — app construction options
+6 -3
View File
@@ -9,11 +9,11 @@ hero:
tagline: A zen, opinionated, type-safe framework. Your API is a dependency graph you can see, slice, and trust — not a mutable bag threaded through positional middleware. That's the tea. 🍵 tagline: A zen, opinionated, type-safe framework. Your API is a dependency graph you can see, slice, and trust — not a mutable bag threaded through positional middleware. That's the tea. 🍵
actions: actions:
- text: Get started - text: Get started
link: /getting-started/ link: /docs/getting-started/
icon: right-arrow icon: right-arrow
variant: primary variant: primary
- text: The idea - text: The idea
link: /concepts/the-graph/ link: /docs/concepts/the-graph/
icon: open-book icon: open-book
variant: minimal variant: minimal
--- ---
@@ -37,8 +37,11 @@ Most frameworks make you keep the whole request in your head: which middleware r
<Card title="One primitive for real-time" icon="rocket"> <Card title="One primitive for real-time" icon="rocket">
Declare `@Sse`, `@Stream`, or `@Ws` and return an `AsyncIterable` — the transport streams it (SSE, ndjson, or a WebSocket duplex) with backpressure and cleanup handled. No separate gateway. Declare `@Sse`, `@Stream`, or `@Ws` and return an `AsyncIterable` — the transport streams it (SSE, ndjson, or a WebSocket duplex) with backpressure and cleanup handled. No separate gateway.
</Card> </Card>
<Card title="Runs wherever JS runs" icon="laptop">
Node, Deno, Bun, and the edge — the same app, you only swap the entry point. HTTP, SSE, and WebSocket behave identically on all four.
</Card>
</CardGrid> </CardGrid>
:::note[Beta] :::note[Beta]
green-tea is **beta**, on the RC track. One runtime dependency (`reflect-metadata`); `ws` and `busboy` are optional peers. [mesh](/guides/mesh/) is alpha and gated behind an explicit opt-in. green-tea is **beta**, on the RC track. One runtime dependency (`reflect-metadata`); `ws` and `busboy` are optional peers. [mesh](/docs/guides/mesh/) is alpha and gated behind an explicit opt-in.
::: :::
+18 -14
View File
@@ -12,22 +12,23 @@ const app = createApp(options);
| Option | Type | Default | Meaning | | Option | Type | Default | Meaning |
|---|---|---|---| |---|---|---|---|
| `modules` | `Ctor[]` | — | the `@Module` classes to wire (required) | | `modules` | `Ctor[]` | — | the `@Module` classes to wire (required) |
| `plugins` | `Plugin[]` | `[]` | plugins, each limited to `bus.on` + `scope.add` ([plugins](/guides/plugins/)) | | `plugins` | `Plugin[]` | `[]` | plugins, each limited to `bus.on` + `scope.add` ([plugins](/docs/guides/plugins/)) |
| `limits` | `RequestLimits` | see below | body-size and timeout ceilings | | `limits` | `RequestLimits` | see below | body-size and timeout ceilings |
| `devGraph` | `boolean` | `false` | mount `GET /__graph__` ([introspection](/guides/introspection/)) | | `devGraph` | `boolean` | `false` | mount `GET /__graph__` ([introspection](/docs/guides/introspection/)) |
| `devOpenapi` | `boolean` | `false` | mount `GET /__openapi__` serving the [OpenAPI](/guides/openapi/) document | | `devOpenapi` | `boolean` | `false` | mount `GET /__openapi__` serving the [OpenAPI](/docs/guides/openapi/) document |
| `overrides` | `Record<string, unknown>` | — | swap any node by token ([testing](/guides/testing/)) | | `overrides` | `Record<string, unknown>` | — | swap any node by token ([testing](/docs/guides/testing/)) |
| `tls` | `TlsOptions` | — | serve over https/wss | | `tls` | `TlsOptions` | — | serve over https/wss |
| `trustProxy` | `boolean` | `false` | honor `X-Forwarded-*` for `ctx.protocol` / `ctx.ip` | | `trustProxy` | `boolean` | `false` | honor `X-Forwarded-*` for `ctx.protocol` / `ctx.ip` |
| `security` | `boolean \| SecurityOptions` | `true` | secure-by-default headers ([security](/guides/security/)) | | `security` | `boolean \| SecurityOptions` | `true` | secure-by-default headers ([security](/docs/guides/security/)) |
| `cors` | `CorsOptions` | — | CORS handling | | `cors` | `CorsOptions` | — | CORS handling |
| `bodyDuplicates` | `'array' \| 'last'` | `'last'` | policy for repeated form fields | | `bodyDuplicates` | `'array' \| 'last'` | `'last'` | policy for repeated form fields |
| `onError` | `ErrorRenderer` | — | render errors your way ([error handling](/guides/errors/)); returns a response or `undefined` to fall back to JSON | | `onError` | `ErrorRenderer` | — | render errors your way ([error handling](/docs/guides/errors/)); returns a response or `undefined` to fall back to JSON |
| `views` | `string` | `process.cwd()` | base dir `@Html('file.html')` paths resolve against — relative paths join it, absolute paths are used as-is ([HTML & views](/guides/html/)) | | `views` | `string` | `process.cwd()` | base dir `@Html('file.html')` paths resolve against — relative paths join it, absolute paths are used as-is ([HTML & views](/docs/guides/html/)) |
| `viewEngine` | `(source: string, data: unknown) => string` | built-in `render` | swap in your own template engine for `@Html(..., { template: true })`; template mode only ([HTML & views](/guides/html/)) | | `viewEngine` | `(source: string, data: unknown) => string` | built-in `render` | swap in your own template engine for `@Html(..., { template: true })`; template mode only ([HTML & views](/docs/guides/html/)) |
| `static` | `boolean \| string` | — | serve a directory as a `GET`/`HEAD` fallback (after declared routes, before `404`); `true` → `./public`, a string → that dir; path-traversal-safe; needs a filesystem — Node/Deno/Bun only ([HTML & views](/guides/html/)) | | `static` | `boolean \| string` | — | serve a directory as a `GET`/`HEAD` fallback (after declared routes, before `404`); `true` → `./public`, a string → that dir; path-traversal-safe; needs a filesystem — Node/Deno/Bun only ([HTML & views](/docs/guides/html/)) |
| `mesh` | `MeshConfig` | — | distributed DI — **requires `experimental: true`** ([mesh](/guides/mesh/)) | | `mesh` | `MeshConfig` | — | distributed DI — **requires `experimental: true`** ([mesh](/docs/guides/mesh/)) |
| `experimental` | `boolean` | `false` | opt in to alpha features (currently gates `mesh`) | | `experimental` | `boolean` | `false` | opt in to alpha features (currently gates `mesh`) |
| `warnGraphDepth` | `number \| false` | `20` | warn when one route resolves to more than this many steps; `false` disables the design warning |
### `RequestLimits` ### `RequestLimits`
@@ -53,7 +54,7 @@ const app = createApp(options);
### `MeshConfig` ### `MeshConfig`
`{ secret?, teapots?, timeoutMs? }` — `teapots` is `{ url, secret }[]`. See [Mesh](/guides/mesh/). `{ secret?, teapots?, timeoutMs?, heartbeatMs? }` — `teapots` is `{ url, secret }[]`; `timeoutMs` bounds an RPC (default 30s, → 504), `heartbeatMs` is the ping gap that detects a half-open link (default 15s, → 503). See [Mesh](/docs/guides/mesh/).
## The `App` ## The `App`
@@ -63,14 +64,17 @@ const app = createApp(options);
|---|---|---| |---|---|---|
| `listen(port)` | `Promise<http.Server>` | boots providers, then serves | | `listen(port)` | `Promise<http.Server>` | boots providers, then serves |
| `close()` | `Promise<void>` | drains in-flight, closes streams + mesh links | | `close()` | `Promise<void>` | drains in-flight, closes streams + mesh links |
| `ready()` | `Promise<void>` | resolves the graph and mesh links without booting providers |
| `fetch(request)` | `Promise<Response>` | Web-Standards HTTP/SSE handler for Node, Deno, Bun, and edge |
| `upgrade(request, socket)` | `Promise<void>` | neutral WebSocket upgrade used by non-Node adapters |
| `inspect(route)` | `InspectLine[]` | the provider/step/handler chain for a route | | `inspect(route)` | `InspectLine[]` | the provider/step/handler chain for a route |
| `explain(route)` | `Explain` | the chain annotated with each node's needs/provides | | `explain(route)` | `Explain` | the chain annotated with each node's needs/provides |
| `graph()` | `GraphView` | the full node + route graph | | `graph()` | `GraphView` | the full node + route graph |
| `toMermaid()` / `toDOT()` | `string` | render the graph | | `toMermaid()` / `toDOT()` | `string` | render the graph |
| `openapi(info?)` | `OpenApiDoc` | structural OpenAPI 3.1 document ([details](/guides/openapi/)) | | `openapi(info?)` | `OpenApiDoc` | structural OpenAPI 3.1 document ([details](/docs/guides/openapi/)) |
| `degraded()` | `string[]` | optional providers running degraded (empty until `listen()`) | | `degraded()` | `string[]` | optional providers running degraded (empty until providers boot through `fetch`, `upgrade`, or `listen`) |
| `bus` | `Bus` | lifecycle + request event bus | | `bus` | `Bus` | lifecycle + request event bus |
:::note :::note
On mesh apps, `graph` / `explain` / `inspect` / `degraded` are only available **after** `listen()` — the graph is finalized once remote scopes connect. On mesh apps, `graph` / `explain` / `inspect` / `degraded` are only available after `ready()` or the first serving call — the graph is finalized once remote scopes connect.
::: :::
@@ -3,7 +3,7 @@ title: Decorators
description: "Full reference for every class, method, and argument decorator." description: "Full reference for every class, method, and argument decorator."
--- ---
Every decorator green-tea exports, grouped by where it applies. All require `experimentalDecorators: true` in your `tsconfig` — see [Why legacy decorators](/concepts/the-graph/#why-legacy-decorators). Every decorator green-tea exports, grouped by where it applies. All require `experimentalDecorators: true` in your `tsconfig` — see [Why legacy decorators](/docs/concepts/the-graph/#why-legacy-decorators).
## Structure ## Structure
@@ -35,8 +35,8 @@ An app-scope value, built once at boot and cached, addressable by `provides`.
|---|---|---|---| |---|---|---|---|
| `provides` | `string` | — | the token this provider produces (required) | | `provides` | `string` | — | the token this provider produces (required) |
| `needs` | `string[]` | `[]` | tokens it depends on | | `needs` | `string[]` | `[]` | tokens it depends on |
| `optional` | `boolean` | `false` | if it throws on boot, degrade instead of aborting ([details](/guides/dependency-injection/)) | | `optional` | `boolean` | `false` | if it throws on boot, degrade instead of aborting ([details](/docs/guides/dependency-injection/)) |
| `export` | `boolean` | `false` | expose over the mesh control channel ([mesh](/guides/mesh/)) | | `export` | `boolean` | `false` | expose over the mesh control channel ([mesh](/docs/guides/mesh/)) |
### `@Step(options)` ### `@Step(options)`
@@ -48,23 +48,23 @@ Method decorator. Turns a handler's return value into `{ status?, headers?, body
### `@Html` / `@Html(path, opts?)` ### `@Html` / `@Html(path, opts?)`
Method decorator. Marks a buffered `GET`/`POST` handler as serving HTML instead of going through the JSON transformer. Three modes ([details](/guides/html/)): Method decorator. Marks a buffered `GET`/`POST` handler as serving HTML instead of going through the JSON transformer. Three modes ([details](/docs/guides/html/)):
| Form | Behavior | | Form | Behavior |
|---|---| |---|---|
| `@Html` (bare) | sends the handler's returned string as `text/html` | | `@Html` (bare) | sends the handler's returned string as `text/html` |
| `@Html('file.html')` | serves that file verbatim; the handler's return value is ignored | | `@Html('file.html')` | serves that file verbatim; the handler's return value is ignored |
| `@Html('file.html', { template: true })` | renders the file with the handler's returned data, via the built-in `render` engine or `viewEngine` ([createApp](/reference/createapp/)) | | `@Html('file.html', { template: true })` | renders the file with the handler's returned data, via the built-in `render` engine or `viewEngine` ([createApp](/docs/reference/createapp/)) |
Only buffered `GET`/`POST` routes are supported, and `@Html` can't be combined with `@Transformer` on the same handler — both are validated at boot, not per-request. Only buffered `GET`/`POST` routes are supported, and `@Html` can't be combined with `@Transformer` on the same handler — both are validated at boot, not per-request.
## Routes ## Routes
Method decorators on a controller. All accept `(path, opts?)` where `opts = { export?: boolean, duplicates?: 'array' | 'last', maxBodyBytes?: number, maxParts?: number }`. `maxBodyBytes` / `maxParts` override the server-wide [`limits`](/reference/createapp/) for this route only. Method decorators on a controller. All accept `(path, opts?)` where `opts = { export?: boolean, duplicates?: 'array' | 'last', maxBodyBytes?: number, maxParts?: number }`. `maxBodyBytes` / `maxParts` override the server-wide [`limits`](/docs/reference/createapp/) for this route only.
| Decorator | Method | Transport | | Decorator | Method | Transport |
|---|---|---| |---|---|---|
| `@Get` `@Post` `@Put` `@Patch` `@Delete` | as named | buffered response | | `@Get` `@Head` `@Post` `@Put` `@Patch` `@Delete` `@Options` | as named | buffered response |
| `@Sse` | GET | `text/event-stream` | | `@Sse` | GET | `text/event-stream` |
| `@Ws` | GET | WebSocket duplex | | `@Ws` | GET | WebSocket duplex |
| `@Stream` | GET | negotiated (SSE / ndjson / WS) | | `@Stream` | GET | negotiated (SSE / ndjson / WS) |
@@ -75,7 +75,9 @@ Method decorators on a controller. All accept `(path, opts?)` where `opts = { ex
@Post('/avatar', { maxBodyBytes: 5_000_000, maxParts: 20 }) // per-route upload limits @Post('/avatar', { maxBodyBytes: 5_000_000, maxParts: 20 }) // per-route upload limits
``` ```
See [Routing](/guides/routing/) for pattern matching and [Streaming](/guides/streaming/) for the transports. See [Routing](/docs/guides/routing/) for pattern matching and [Streaming](/docs/guides/streaming/) for the transports.
`@Head` and `@Options` declare explicit handlers. When they are absent, the router can provide an implicit buffered-GET HEAD response or an automatic `204` OPTIONS response; those fallbacks are runtime behavior, not decorator metadata.
## Arguments ## Arguments
@@ -93,4 +95,4 @@ A handler's signature declares exactly what it wants, in any order.
| `@inbound()` | the incoming message stream (WebSocket) | `()` | | `@inbound()` | the incoming message stream (WebSocket) | `()` |
| `@abort()` | the request's `AbortSignal` | `()` | | `@abort()` | the request's `AbortSignal` | `()` |
Passing a [Standard Schema](/guides/validation/) validates and coerces the value before the handler sees it. Full details in [Argument decorators](/guides/arguments/). Passing a [Standard Schema](/docs/guides/validation/) validates and coerces the value before the handler sees it. Full details in [Argument decorators](/docs/guides/arguments/).