From f613a6427be23d01b9d56d3a194f3a4af18158f1 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 10 Jul 2026 15:55:22 -0500 Subject: [PATCH 1/5] feat(pipeline): enforce return contract by declared transport Signed-off-by: Diego Resendez --- src/app/index.ts | 2 ++ src/index.ts | 10 +++++++++- src/pipeline.ts | 31 +++++++++++++++++++++++++++--- src/signals.ts | 13 +++++++++++++ test/pipeline.test.ts | 44 ++++++++++++++++++++++++++++++++++++++----- 5 files changed, 91 insertions(+), 9 deletions(-) diff --git a/src/app/index.ts b/src/app/index.ts index 18ce2a1..a624c6e 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -635,6 +635,7 @@ function buildMeshControl( transformer: plan.transformer, bus, onError, + transport: plan.transport, seed: { ...provided, req: env, params: env.params, query: env.query, body: env.body, headers: env.headers }, }); @@ -671,6 +672,7 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps transformer: plan.transformer, bus, onError, + transport: plan.transport, seed: { ...provided, req, diff --git a/src/index.ts b/src/index.ts index de7e9c9..4beab8b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -44,7 +44,15 @@ export type { Plugin } from './plugin'; // Transformers & error signals export { JsonTransformer } from './transformers'; export type { ErrorRenderer, ErrorRequest, ErrorResponse } from './transformers'; -export { HttpError, Unauthorized, NotFound, Redirect, NotModified, ValidationError } from './signals'; +export { + HttpError, + Unauthorized, + NotFound, + Redirect, + NotModified, + ValidationError, + TransportMismatchError, +} from './signals'; // Bus & flow export { Bus } from './bus'; diff --git a/src/pipeline.ts b/src/pipeline.ts index 4810252..46a303f 100644 --- a/src/pipeline.ts +++ b/src/pipeline.ts @@ -1,7 +1,8 @@ import { Bus } from './bus'; import { renderError, type ErrorRenderer } from './transformers'; import { isAsyncIterable } from './channel'; -import type { TransformerFn } from './metadata'; +import type { TransformerFn, Transport } from './metadata'; +import { TransportMismatchError } from './signals'; /** A single step in a request pipeline: a named unit whose `run` merges its output into the shared context. */ export interface PipelineStep { @@ -22,6 +23,18 @@ export interface StreamResult { /** The outcome of {@link runPipeline}: either a buffered response or a stream. */ export type PipelineResult = ResponseShape | StreamResult; +/** What a route's declared transport requires its handler to return. */ +export type ReturnContract = 'buffer' | 'stream' | 'either'; + +/** Return contract per transport. A new transport just adds a row. `ws` never reaches runPipeline (filtered earlier). */ +export const TRANSPORT_RETURN: Record = { + buffer: 'buffer', + sse: 'stream', + ndjson: 'stream', + ws: 'stream', + negotiate: 'either', +}; + /** Type guard narrowing a {@link PipelineResult} to a {@link StreamResult}. */ export function isStreamResult(result: PipelineResult): result is StreamResult { return 'stream' in result; @@ -38,9 +51,10 @@ export async function runPipeline(args: { transformer: TransformerFn; seed: Record; bus: Bus; + transport: Transport; onError?: ErrorRenderer; }): Promise { - const { steps, handler, transformer, seed, bus, onError } = args; + const { steps, handler, transformer, seed, bus, transport, onError } = args; // context is intentionally `any`: each step merges arbitrary keys into the accumulator let context: any = { ...seed }; @@ -53,7 +67,18 @@ export async function runPipeline(args: { } const result = await handler(context); - if (isAsyncIterable(result)) return { stream: result }; // stream path: transformer bypassed + const streaming = isAsyncIterable(result); + const contract = TRANSPORT_RETURN[transport]; + + if (contract === 'buffer' && streaming) { + throw new TransportMismatchError(transport, 'stream', context.req as { method?: string; url?: string }); + } + + if (contract === 'stream' && !streaming) { + throw new TransportMismatchError(transport, 'value', context.req as { method?: string; url?: string }); + } + + if (streaming) return { stream: result }; // stream path: transformer bypassed const transformed = transformer(result); return { status: transformed.status ?? 200, headers: transformed.headers ?? {}, body: transformed.body }; } catch (error) { diff --git a/src/signals.ts b/src/signals.ts index e7556bb..29f5507 100644 --- a/src/signals.ts +++ b/src/signals.ts @@ -50,6 +50,19 @@ export class ValidationError extends HttpError { } } +/** Thrown when a handler's return value contradicts its route's declared transport (a programming error). */ +export class TransportMismatchError extends HttpError { + constructor(transport: string, got: 'stream' | 'value', req?: { method?: string; url?: string }) { + const where = req?.method && req?.url ? ` (${req.method} ${req.url})` : ''; + const expected = got === 'stream' ? 'return a value' : 'return an AsyncIterable'; + const fix = + got === 'stream' + ? 'buffered routes (@Get/@Post/@Put/@Patch/@Delete) must return a value — to stream, declare @Sse, @Stream, or @Ws' + : 'streaming routes (@Sse/@Ws) must return an AsyncIterable (e.g. an async generator or channel())'; + super(500, `Transport '${transport}'${where} must ${expected}, but the handler returned a ${got}. ${fix}.`); + } +} + /** Type guard: true if `error` is an {@link HttpError}. */ export function isHttpError(error: unknown): error is HttpError { return error instanceof HttpError; diff --git a/test/pipeline.test.ts b/test/pipeline.test.ts index 64abd00..24e7168 100644 --- a/test/pipeline.test.ts +++ b/test/pipeline.test.ts @@ -9,7 +9,7 @@ const base = { transformer: JsonTransformer, seed: { req: { token: 'abc' } } }; test('runs steps, accumulates ctx, transforms handler return', async () => { const bus = new Bus(); const res = await runPipeline({ - ...base, bus, + ...base, bus, transport: 'buffer', steps: [{ name: 'auth', origin: 'mod', run: (ctx) => ({ user: ctx.req.token }) }], handler: (ctx) => ({ user: ctx.user }), }); @@ -23,7 +23,7 @@ test('runs steps, accumulates ctx, transforms handler return', async () => { test('a thrown HttpError short-circuits to an error response', async () => { const bus = new Bus(); const res = await runPipeline({ - ...base, bus, + ...base, bus, transport: 'buffer', steps: [{ name: 'auth', origin: 'mod', run: () => { throw new Unauthorized('no'); } }], handler: () => ({ never: true }), }); @@ -37,7 +37,7 @@ test('emits enter/leave/error lifecycle events', async () => { bus.on('request:step:enter', enter); bus.on('request:step:error', error); await runPipeline({ - ...base, bus, + ...base, bus, transport: 'buffer', steps: [{ name: 'boom', origin: 'mod', run: () => { throw new Unauthorized(); } }], handler: () => ({}), }); @@ -51,7 +51,7 @@ describe('runPipeline streaming', () => { it('returns a StreamResult when the handler returns an AsyncIterable (transformer bypassed)', async () => { async function* gen() { yield 1; yield 2; } - const res = await runPipeline({ steps: [], handler: () => gen(), transformer: noTransform, seed: {}, bus }); + const res = await runPipeline({ steps: [], handler: () => gen(), transformer: noTransform, seed: {}, bus, transport: 'sse' }); expect(isStreamResult(res)).toBe(true); if (isStreamResult(res)) { const out: unknown[] = []; @@ -61,8 +61,42 @@ describe('runPipeline streaming', () => { }); it('still buffers a normal return through the transformer', async () => { - const res = await runPipeline({ steps: [], handler: () => 'hi', transformer: () => ({ body: 'HI' }), seed: {}, bus }); + const res = await runPipeline({ steps: [], handler: () => 'hi', transformer: () => ({ body: 'HI' }), seed: {}, bus, transport: 'buffer' }); expect(isStreamResult(res)).toBe(false); if (!isStreamResult(res)) expect(res.body).toBe('HI'); }); }); + +describe('runPipeline transport enforcement', () => { + const bus = new Bus(); + const noTransform = (v: unknown) => ({ body: String(v) }); + async function* gen() { yield 1; } + + it('renders a 500 mismatch when a buffered route returns an AsyncIterable', async () => { + const res = await runPipeline({ steps: [], handler: () => gen(), transformer: noTransform, seed: {}, bus, transport: 'buffer' }); + expect(isStreamResult(res)).toBe(false); + if (!isStreamResult(res)) { + expect(res.status).toBe(500); + expect(res.body).toContain('must return a value'); + } + }); + + it('renders a 500 mismatch when a streaming route returns a non-iterable', async () => { + const res = await runPipeline({ steps: [], handler: () => ({ x: 1 }), transformer: noTransform, seed: {}, bus, transport: 'sse' }); + expect(isStreamResult(res)).toBe(false); + if (!isStreamResult(res)) { + expect(res.status).toBe(500); + expect(res.body).toContain('must return an AsyncIterable'); + } + }); + + it('negotiate tolerates a value (buffered)', async () => { + const res = await runPipeline({ steps: [], handler: () => 'hi', transformer: noTransform, seed: {}, bus, transport: 'negotiate' }); + expect(isStreamResult(res)).toBe(false); + }); + + it('negotiate tolerates an AsyncIterable (stream)', async () => { + const res = await runPipeline({ steps: [], handler: () => gen(), transformer: noTransform, seed: {}, bus, transport: 'negotiate' }); + expect(isStreamResult(res)).toBe(true); + }); +}); From 4d1ff33f74906f34f9d99ac92cf19c2e4d017d93 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 10 Jul 2026 15:59:52 -0500 Subject: [PATCH 2/5] test(transport): end-to-end enforcement via app.fetch Signed-off-by: Diego Resendez --- test/transport-enforcement.test.ts | 36 ++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 test/transport-enforcement.test.ts diff --git a/test/transport-enforcement.test.ts b/test/transport-enforcement.test.ts new file mode 100644 index 0000000..56a38af --- /dev/null +++ b/test/transport-enforcement.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from 'vitest'; +import { createApp, Route, Get, Sse, Module } from '../src/index'; + +@Route('/api') +class Ctl { + @Get('/ok') ok() { return { ok: true }; } // buffered value — fine + @Get('/leak') leak() { return (async function* () { yield 1; })(); } // buffered + iterable — 500 + @Sse('/stream') stream() { return (async function* () { yield { n: 1 }; })(); } // stream — fine + @Sse('/empty') empty() { return { not: 'a stream' }; } // stream + value — 500 +} +@Module({ mountpoint: '/', controllers: [Ctl] }) +class M {} +const app = createApp({ modules: [M] }); + +describe('transport enforcement (integration)', () => { + it('a normal buffered GET still returns its value', async () => { + const res = await app.fetch(new Request('http://x/api/ok')); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ ok: true }); + }); + it('a buffered GET that returns an AsyncIterable is a 500 mismatch', async () => { + const res = await app.fetch(new Request('http://x/api/leak')); + expect(res.status).toBe(500); + expect(await res.text()).toContain('must return a value'); + }); + it('a normal SSE stream still streams', async () => { + const res = await app.fetch(new Request('http://x/api/stream')); + expect(res.status).toBe(200); + expect(res.headers.get('content-type')).toContain('text/event-stream'); + }); + it('an SSE route that returns a plain value is a 500 mismatch', async () => { + const res = await app.fetch(new Request('http://x/api/empty')); + expect(res.status).toBe(500); + expect(await res.text()).toContain('must return an AsyncIterable'); + }); +}); From 535392babaf040bdfe2eff4f8613a7dfe045c382 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 10 Jul 2026 16:02:36 -0500 Subject: [PATCH 3/5] docs(transport): declared-transport contract + @Html return contract Signed-off-by: Diego Resendez --- CHANGELOG.md | 5 +++++ website/src/content/docs/guides/html.md | 11 +++++++---- website/src/content/docs/guides/streaming.md | 15 +++++++++------ 3 files changed, 21 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 70114e6..cd43a36 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,11 @@ green-tea uses calendar versioning: `YY.MM.PATCH`. fields such as `req.socket` / `req.rawHeaders` are no longer available on `ctx.req`; use `ctx.protocol` / `ctx.ip` / `ctx.query` / `ctx.headers` instead — all still provided. +- **Breaking (pre-1.0): transport is now enforced by declaration.** A buffered route + (`@Get`/`@Post`/`@Put`/`@Patch`/`@Delete`) whose handler returns an `AsyncIterable`, or a streaming + route (`@Sse`/`@Ws`) whose handler returns a plain value, now fails with a 500 `TransportMismatchError` + instead of silently switching behavior. `@Stream` still negotiates both. Declare `@Sse`/`@Stream`/`@Ws` + to stream — a return value no longer changes a route's wire contract. ## [26.7.0-beta.0] - 2026-07-07 diff --git a/website/src/content/docs/guides/html.md b/website/src/content/docs/guides/html.md index 2914c37..246c83d 100644 --- a/website/src/content/docs/guides/html.md +++ b/website/src/content/docs/guides/html.md @@ -62,10 +62,13 @@ class UserController { Same filesystem requirement as file mode: Node/Deno/Bun only. -:::caution[Return a string or data, never an `AsyncIterable`] -An `@Html` handler must return a string (bare mode) or a data object (template mode). Don't -return an `AsyncIterable` — the pipeline detects async-iterable returns and streams them raw, -bypassing the HTML transformer entirely, so your markup never gets wrapped or rendered. +:::caution[Return the right shape for each mode — never an `AsyncIterable`] +`@Html` is a buffered route, so its return contract follows the mode: bare `@Html` returns a +`string`; `@Html('file.html', { template: true })` returns the data object rendered into the +template; `@Html('file.html')` (no template) ignores the return entirely — annotate it `: void` +by convention, e.g. `page(@needs('x')): void {}`. Returning an `AsyncIterable` from any `@Html` +handler is the same buffered-route mismatch as any other `@Get`/`@Post`/`@Put`/`@Patch`/`@Delete` +handler: a 500 `TransportMismatchError`, not a silent raw stream. ::: ## The `views` base directory diff --git a/website/src/content/docs/guides/streaming.md b/website/src/content/docs/guides/streaming.md index 2f6e296..ffeb978 100644 --- a/website/src/content/docs/guides/streaming.md +++ b/website/src/content/docs/guides/streaming.md @@ -104,11 +104,14 @@ Same `@Route`, same handler shape, same `AsyncIterable` — real-time is not a s `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. -## The one rule to remember +## Transport is declared, not inferred -``` -return a VALUE → buffered response (transformer → JSON) -return an AsyncIterable → stream (SSE / WS) -``` +A route streams **because** it's declared `@Sse`, `@Stream`, or `@Ws` — never because a handler happened to return an `AsyncIterable`. In most frameworks the return type decides the wire format; in green-tea the decorator decides, and the return value is enforced against it: -Return a value and you get a buffered JSON response; return an `AsyncIterable` and you get a stream. That's the whole contract. +| Declare | Handler must return | Otherwise | +|---|---|---| +| `@Get` / `@Post` / `@Put` / `@Patch` / `@Delete` (buffered) | a value | returning an `AsyncIterable` fails with a 500 `TransportMismatchError` | +| `@Sse` / `@Ws` (streaming) | an `AsyncIterable` | returning a plain value fails with a 500 `TransportMismatchError` | +| `@Stream` (negotiate) | either | the client picks via `Accept` / `Upgrade` — no mismatch | + +This is the anti-Express guarantee: your wire contract is what you **declared**, never a surprise sprung by a return value. A buffered route can't accidentally start streaming because someone returned a generator; a streaming route can't silently downgrade to a buffered response because someone forgot a `yield`. Declare `@Sse` / `@Stream` / `@Ws` to stream — the return value never changes a route's transport. From 2b646eaec681f4a38e4026bef8691042343db1a8 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 10 Jul 2026 16:06:02 -0500 Subject: [PATCH 4/5] docs(transport): reword stale implicit-streaming passages Signed-off-by: Diego Resendez --- website/src/content/docs/guides/dependency-injection.md | 2 +- website/src/content/docs/guides/streaming.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/website/src/content/docs/guides/dependency-injection.md b/website/src/content/docs/guides/dependency-injection.md index e785640..2026963 100644 --- a/website/src/content/docs/guides/dependency-injection.md +++ b/website/src/content/docs/guides/dependency-injection.md @@ -143,4 +143,4 @@ receive `undefined`. Boot fails loudly, so you never serve `undefined`. - Everything a handler can inject: [Argument decorators](/guides/arguments/) and the [decorator reference](/reference/decorators/). - Coerce and validate injected values with Standard Schema: [Validation](/guides/validation/). -- Return an `AsyncIterable` to push data over time: [Streaming](/guides/streaming/). +- Declare `@Sse` and return an `AsyncIterable` to push data over time: [Streaming](/guides/streaming/). diff --git a/website/src/content/docs/guides/streaming.md b/website/src/content/docs/guides/streaming.md index ffeb978..01ad3a7 100644 --- a/website/src/content/docs/guides/streaming.md +++ b/website/src/content/docs/guides/streaming.md @@ -28,7 +28,7 @@ Streaming bypasses the response transformer — the transport frames each value ## 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). +A route decorated `@Sse` streams — that's what triggers it, not the return value. It must return an `AsyncIterable`; the transport frames each value as an SSE event, handles backpressure, and cleans up on disconnect (the transformer is bypassed). ```typescript import { Route, Sse } from '@green-tea/core'; From 76267b74ec93df5439608f407ca7cdf556b6838a Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 10 Jul 2026 16:07:01 -0500 Subject: [PATCH 5/5] =?UTF-8?q?docs(transport):=20reword=20homepage=20hero?= =?UTF-8?q?=20=E2=80=94=20declare=20@Sse=20to=20stream?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Diego Resendez --- website/src/content/docs/index.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/src/content/docs/index.mdx b/website/src/content/docs/index.mdx index ce98f9d..d725ccb 100644 --- a/website/src/content/docs/index.mdx +++ b/website/src/content/docs/index.mdx @@ -35,7 +35,7 @@ Most frameworks make you keep the whole request in your head: which middleware r `app.explain('/users/:id')` prints the ordered chain; `GET /__graph__` renders it as a live diagram. Onboarding and audits are reading, not archaeology. - Return an `AsyncIterable` and 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.