From 35c60c44c3d1ee9b55896d9cbfdc6ef5a7568389 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 26 Jun 2026 02:07:43 -0500 Subject: [PATCH 001/139] docs: add runtime adapters (Node/Deno/Bun/edge) to roadmap Signed-off-by: Diego Resendez --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 7fa2a2e..2f3213d 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,7 @@ npm run build # emit dist/ - **streams** — native WebSocket/SSE + reactive streams (steps that open an observed channel). - **mesh** — `teapot`/`teacup`: distributed scopes over a persistent channel with auto-registration. Model: a BEAM/OTP-style cluster, *not* microservices. The core's `resolve()` is already async + transport-agnostic to allow this without a rewrite. +- **runtime adapters** — factor the transport behind an adapter so the core stays runtime-agnostic; Node / Deno / Bun / edge become thin adapters over web-standard `Request`/`Response`. Only `src/http.ts` is runtime-specific today. - official plugins (cors, body parsers, auth) — structurally unable to sabotage the global pipeline. ## License From f96d349c74a1bd0b80afa0dc57b30a2e07e1dd9a Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 27 Jun 2026 15:11:28 -0500 Subject: [PATCH 002/139] feat: multicast channel primitive + isAsyncIterable guard Signed-off-by: Diego Resendez --- src/channel.ts | 89 ++++++++++++++++++++++++++++++++++++++++++++ test/channel.test.ts | 74 ++++++++++++++++++++++++++++++++++++ 2 files changed, 163 insertions(+) create mode 100644 src/channel.ts create mode 100644 test/channel.test.ts diff --git a/src/channel.ts b/src/channel.ts new file mode 100644 index 0000000..def9077 --- /dev/null +++ b/src/channel.ts @@ -0,0 +1,89 @@ +export interface Channel extends AsyncIterable { + push(value: T): void; + close(): void; + fail(err: unknown): void; + readonly closed: boolean; +} + +export function isAsyncIterable(x: unknown): x is AsyncIterable { + return x != null && typeof (x as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function'; +} + +interface Sub { + iterator: AsyncIterator; + push(v: T, cap: number): void; + end(): void; + fail(e: unknown): void; +} + +function newSub(onReturn: () => void): Sub { + const queue: T[] = []; + let pending: { resolve: (r: IteratorResult) => void; reject: (e: unknown) => void } | null = null; + let ended = false; + let failure: { err: unknown } | null = null; + + return { + push(v, cap) { + if (ended) return; + if (pending) { const p = pending; pending = null; p.resolve({ value: v, done: false }); return; } + queue.push(v); + if (queue.length > cap) queue.shift(); // drop-oldest when buffer is full + }, + end() { + if (ended) return; + ended = true; + if (pending) { const p = pending; pending = null; p.resolve({ value: undefined as never, done: true }); } + }, + fail(e) { + if (ended) return; + ended = true; + failure = { err: e }; + if (pending) { const p = pending; pending = null; p.reject(e); } + }, + iterator: { + next(): Promise> { + if (queue.length) return Promise.resolve({ value: queue.shift() as T, done: false }); + if (failure) return Promise.reject(failure.err); + if (ended) return Promise.resolve({ value: undefined as never, done: true }); + return new Promise>((resolve, reject) => { pending = { resolve, reject }; }); + }, + return(): Promise> { + ended = true; + onReturn(); + return Promise.resolve({ value: undefined as never, done: true }); + }, + }, + }; +} + +export function channel(opts: { buffer?: number } = {}): Channel { + const cap = opts.buffer ?? Infinity; + const subs = new Set>(); + let done = false; + let closedFlag = false; + + return { + get closed() { return closedFlag; }, + push(value) { + if (done) return; + for (const s of subs) s.push(value, cap); + }, + close() { + if (done) return; + done = true; closedFlag = true; + for (const s of subs) s.end(); + subs.clear(); + }, + fail(err) { + if (done) return; + done = true; closedFlag = true; + for (const s of subs) s.fail(err); + subs.clear(); + }, + [Symbol.asyncIterator](): AsyncIterator { + const s = newSub(() => subs.delete(s)); + subs.add(s); + return s.iterator; + }, + }; +} diff --git a/test/channel.test.ts b/test/channel.test.ts new file mode 100644 index 0000000..cf7d4d3 --- /dev/null +++ b/test/channel.test.ts @@ -0,0 +1,74 @@ +import { describe, it, expect } from 'vitest'; +import { channel, isAsyncIterable } from '../src/channel'; + +const collect = async (it: AsyncIterable, n: number): Promise => { + const out: T[] = []; + for await (const v of it) { out.push(v); if (out.length === n) break; } + return out; +}; + +describe('isAsyncIterable', () => { + it('detects async iterables, rejects sync ones', () => { + expect(isAsyncIterable(channel())).toBe(true); + expect(isAsyncIterable((async function* () {})())).toBe(true); + expect(isAsyncIterable('string')).toBe(false); + expect(isAsyncIterable([1, 2])).toBe(false); + expect(isAsyncIterable(Buffer.from('x'))).toBe(false); + expect(isAsyncIterable(null)).toBe(false); + expect(isAsyncIterable({})).toBe(false); + }); +}); + +describe('channel', () => { + it('fans out the same values to two subscribers', async () => { + const ch = channel(); + const a = collect(ch, 3); + const b = collect(ch, 3); + await Promise.resolve(); // let both subscribe + ch.push(1); ch.push(2); ch.push(3); + expect(await a).toEqual([1, 2, 3]); + expect(await b).toEqual([1, 2, 3]); + }); + + it('close() ends the for-await', async () => { + const ch = channel(); + const seen: number[] = []; + const done = (async () => { for await (const v of ch) seen.push(v); })(); + await Promise.resolve(); + ch.push(1); ch.close(); + await done; + expect(seen).toEqual([1]); + expect(ch.closed).toBe(true); + }); + + it('fail() throws in the consumer', async () => { + const ch = channel(); + const boom = new Error('boom'); + const run = (async () => { for await (const _ of ch) { /* */ } })(); + await Promise.resolve(); + ch.fail(boom); + await expect(run).rejects.toThrow('boom'); + }); + + it('bounded buffer drops oldest for a slow subscriber', async () => { + const ch = channel({ buffer: 2 }); + const it = ch[Symbol.asyncIterator](); + await Promise.resolve(); + ch.push(1); ch.push(2); ch.push(3); // 1 dropped, queue = [2,3] + ch.close(); + expect((await it.next()).value).toBe(2); + expect((await it.next()).value).toBe(3); + expect((await it.next()).done).toBe(true); + }); + + it('.return() on one subscriber does not affect the other', async () => { + const ch = channel(); + const a = ch[Symbol.asyncIterator](); + const b = ch[Symbol.asyncIterator](); + await Promise.resolve(); + await a.return!(); // a unsubscribes + ch.push(7); ch.close(); + expect((await b.next()).value).toBe(7); + expect((await a.next()).done).toBe(true); + }); +}); From a3dad323844f67cdb0fb5cdbcf6ea13169162255 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 27 Jun 2026 15:13:09 -0500 Subject: [PATCH 003/139] feat: SSE and ndjson stream encoders Signed-off-by: Diego Resendez --- src/encoders.ts | 21 +++++++++++++++++++++ test/encoders.test.ts | 29 +++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 src/encoders.ts create mode 100644 test/encoders.test.ts diff --git a/src/encoders.ts b/src/encoders.ts new file mode 100644 index 0000000..e5642e3 --- /dev/null +++ b/src/encoders.ts @@ -0,0 +1,21 @@ +export interface StreamEncoder { + headers: Record; + encode(item: unknown): string | Buffer; + encodeError(err: unknown): string | Buffer | null; + ping?(): string; +} + +const msgOf = (e: unknown): string => (e instanceof Error ? e.message : String(e)); + +export const sseEncoder: StreamEncoder = { + headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' }, + encode: (item) => `data: ${JSON.stringify(item)}\n\n`, + encodeError: (err) => `event: error\ndata: ${JSON.stringify({ error: msgOf(err) })}\n\n`, + ping: () => ': ping\n\n', +}; + +export const ndjsonEncoder: StreamEncoder = { + headers: { 'content-type': 'application/x-ndjson' }, + encode: (item) => `${JSON.stringify(item)}\n`, + encodeError: (err) => `${JSON.stringify({ error: msgOf(err) })}\n`, +}; diff --git a/test/encoders.test.ts b/test/encoders.test.ts new file mode 100644 index 0000000..5ff0a36 --- /dev/null +++ b/test/encoders.test.ts @@ -0,0 +1,29 @@ +import { describe, it, expect } from 'vitest'; +import { sseEncoder, ndjsonEncoder } from '../src/encoders'; + +describe('sseEncoder', () => { + it('frames data as SSE events', () => { + expect(sseEncoder.encode({ a: 1 })).toBe('data: {"a":1}\n\n'); + }); + it('frames errors as an SSE error event with only the message', () => { + expect(sseEncoder.encodeError(new Error('nope'))).toBe('event: error\ndata: {"error":"nope"}\n\n'); + }); + it('sets text/event-stream headers and has a ping', () => { + expect(sseEncoder.headers['content-type']).toBe('text/event-stream'); + expect(typeof sseEncoder.ping).toBe('function'); + expect(sseEncoder.ping!()).toBe(': ping\n\n'); + }); +}); + +describe('ndjsonEncoder', () => { + it('frames one JSON line per item', () => { + expect(ndjsonEncoder.encode({ a: 1 })).toBe('{"a":1}\n'); + }); + it('frames errors as a terminal JSON line', () => { + expect(ndjsonEncoder.encodeError(new Error('nope'))).toBe('{"error":"nope"}\n'); + }); + it('sets ndjson content-type and has no ping', () => { + expect(ndjsonEncoder.headers['content-type']).toBe('application/x-ndjson'); + expect(ndjsonEncoder.ping).toBeUndefined(); + }); +}); From a94a987a350cc89193c592ebdc1609246c8790ed Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 27 Jun 2026 15:15:05 -0500 Subject: [PATCH 004/139] feat: pipeline returns StreamResult for async-iterable handlers Signed-off-by: Diego Resendez --- src/pipeline.ts | 10 +++++++++- test/pipeline.test.ts | 36 +++++++++++++++++++++++++++++++----- 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/src/pipeline.ts b/src/pipeline.ts index 02ebf28..e719b1a 100644 --- a/src/pipeline.ts +++ b/src/pipeline.ts @@ -1,9 +1,16 @@ import { Bus } from './bus'; import { errorToResponse } from './transformers'; +import { isAsyncIterable } from './channel'; import type { TransformerFn } from './metadata'; export interface PipelineStep { name: string; origin: string; run: (ctx: any) => any } export interface ResponseShape { status: number; headers: Record; body: string } +export interface StreamResult { stream: AsyncIterable } +export type PipelineResult = ResponseShape | StreamResult; + +export function isStreamResult(r: PipelineResult): r is StreamResult { + return 'stream' in r; +} export async function runPipeline(args: { steps: PipelineStep[]; @@ -11,7 +18,7 @@ export async function runPipeline(args: { transformer: TransformerFn; seed: Record; bus: Bus; -}): Promise { +}): Promise { const { steps, handler, transformer, seed, bus } = args; let ctx: any = { ...seed }; try { @@ -22,6 +29,7 @@ export async function runPipeline(args: { bus.emit('request:step:leave', { name: s.name, scope: s.origin }); } const result = await handler(ctx); + if (isAsyncIterable(result)) return { stream: result }; // stream path: transformer bypassed const r = transformer(result); return { status: r.status ?? 200, headers: r.headers ?? {}, body: r.body }; } catch (error) { diff --git a/test/pipeline.test.ts b/test/pipeline.test.ts index 83985e8..64abd00 100644 --- a/test/pipeline.test.ts +++ b/test/pipeline.test.ts @@ -1,5 +1,5 @@ -import { expect, test, vi } from 'vitest'; -import { runPipeline } from '../src/pipeline'; +import { describe, expect, it, test, vi } from 'vitest'; +import { runPipeline, isStreamResult } from '../src/pipeline'; import { Bus } from '../src/bus'; import { JsonTransformer } from '../src/transformers'; import { Unauthorized } from '../src/signals'; @@ -13,8 +13,11 @@ test('runs steps, accumulates ctx, transforms handler return', async () => { steps: [{ name: 'auth', origin: 'mod', run: (ctx) => ({ user: ctx.req.token }) }], handler: (ctx) => ({ user: ctx.user }), }); - expect(res.status).toBe(200); - expect(JSON.parse(res.body)).toEqual({ user: 'abc' }); + expect(isStreamResult(res)).toBe(false); + if (!isStreamResult(res)) { + expect(res.status).toBe(200); + expect(JSON.parse(res.body)).toEqual({ user: 'abc' }); + } }); test('a thrown HttpError short-circuits to an error response', async () => { @@ -24,7 +27,8 @@ test('a thrown HttpError short-circuits to an error response', async () => { steps: [{ name: 'auth', origin: 'mod', run: () => { throw new Unauthorized('no'); } }], handler: () => ({ never: true }), }); - expect(res.status).toBe(401); + expect(isStreamResult(res)).toBe(false); + if (!isStreamResult(res)) expect(res.status).toBe(401); }); test('emits enter/leave/error lifecycle events', async () => { @@ -40,3 +44,25 @@ test('emits enter/leave/error lifecycle events', async () => { expect(enter).toHaveBeenCalledWith(expect.objectContaining({ name: 'boom' })); expect(error).toHaveBeenCalled(); }); + +describe('runPipeline streaming', () => { + const bus = new Bus(); + const noTransform = (v: unknown) => ({ body: String(v) }); + + 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 }); + expect(isStreamResult(res)).toBe(true); + if (isStreamResult(res)) { + const out: unknown[] = []; + for await (const v of res.stream) out.push(v); + expect(out).toEqual([1, 2]); + } + }); + + it('still buffers a normal return through the transformer', async () => { + const res = await runPipeline({ steps: [], handler: () => 'hi', transformer: () => ({ body: 'HI' }), seed: {}, bus }); + expect(isStreamResult(res)).toBe(false); + if (!isStreamResult(res)) expect(res.body).toBe('HI'); + }); +}); From 732e1eb636a6119182dee2a1195ee8bc8dea5eaa Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 27 Jun 2026 15:17:08 -0500 Subject: [PATCH 005/139] feat: Sse/Ws/Stream/Post route decorators with transport metadata Signed-off-by: Diego Resendez --- src/metadata.ts | 28 ++++++++++++++++++++-------- test/metadata.test.ts | 21 +++++++++++++++++++-- 2 files changed, 39 insertions(+), 10 deletions(-) diff --git a/src/metadata.ts b/src/metadata.ts index 4408e90..9419cb7 100644 --- a/src/metadata.ts +++ b/src/metadata.ts @@ -5,7 +5,9 @@ export type TransformerFn = (value: unknown) => { status?: number; headers?: Rec export interface ProviderMeta { provides: string; needs: string[]; optional: boolean } export interface StepMeta { provides: string; needs: string[]; optional: boolean } -export interface RouteMeta { method: 'GET'; path: string; handlerName: string } +export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; +export type Transport = 'buffer' | 'sse' | 'ndjson' | 'negotiate' | 'ws'; +export interface RouteMeta { method: HttpMethod; path: string; handlerName: string; transport: Transport } export interface ModuleOptions { mountpoint: string; providers?: Ctor[]; steps?: Ctor[]; controllers?: Ctor[]; } @@ -37,15 +39,25 @@ export function Route(prefix: string): ClassDecorator { return (target) => { Reflect.defineMetadata(K.routePrefix, prefix, target); }; } -export function Get(path: string): MethodDecorator { - return (target, propertyKey) => { - const ctor = target.constructor; - const routes = (Reflect.getMetadata(K.routes, ctor) as RouteMeta[]) ?? []; - routes.push({ method: 'GET', path, handlerName: String(propertyKey) }); - Reflect.defineMetadata(K.routes, routes, ctor); - }; +function routeDecorator(method: HttpMethod, transport: Transport) { + return (path: string): MethodDecorator => + (target, propertyKey) => { + const ctor = target.constructor; + const routes = (Reflect.getMetadata(K.routes, ctor) as RouteMeta[]) ?? []; + routes.push({ method, path, handlerName: String(propertyKey), transport }); + Reflect.defineMetadata(K.routes, routes, ctor); + }; } +export const Get = routeDecorator('GET', 'buffer'); +export const Post = routeDecorator('POST', 'buffer'); +export const Put = routeDecorator('PUT', 'buffer'); +export const Patch = routeDecorator('PATCH', 'buffer'); +export const Delete = routeDecorator('DELETE', 'buffer'); +export const Sse = routeDecorator('GET', 'sse'); +export const Stream = routeDecorator('GET', 'negotiate'); +export const Ws = routeDecorator('GET', 'ws'); + export function Transformer(fn: TransformerFn): MethodDecorator { return (target, propertyKey) => { Reflect.defineMetadata(K.transformer, fn, target.constructor, String(propertyKey)); diff --git a/test/metadata.test.ts b/test/metadata.test.ts index bc62559..8bcb251 100644 --- a/test/metadata.test.ts +++ b/test/metadata.test.ts @@ -1,8 +1,9 @@ import 'reflect-metadata'; -import { expect, test } from 'vitest'; +import { expect, test, describe, it } from 'vitest'; import { Provider, Step, Route, Get, Module, getProviderMeta, getStepMeta, getRoutes, getModuleMeta, + Sse, Ws, Stream, Post, } from '../src/metadata'; @Provider({ provides: 'db', needs: ['config'] }) @@ -26,7 +27,7 @@ test('step metadata is readable', () => { }); test('routes carry method, path and handler name', () => { - expect(getRoutes(Ctl)).toEqual([{ method: 'GET', path: '/users/:id', handlerName: 'getUser' }]); + expect(getRoutes(Ctl)).toEqual([{ method: 'GET', path: '/users/:id', handlerName: 'getUser', transport: 'buffer' }]); }); test('module metadata lists members', () => { @@ -36,3 +37,19 @@ test('module metadata lists members', () => { expect(m.steps).toEqual([Auth]); expect(m.controllers).toEqual([Ctl]); }); + +describe('stream route decorators', () => { + it('records transport + method per decorator', () => { + class StreamCtl { + @Sse('/feed') feed() {} + @Ws('/chat') chat() {} + @Stream('/either') either() {} + @Post('/make') make() {} + } + const byName = Object.fromEntries(getRoutes(StreamCtl).map((r) => [r.handlerName, r])); + expect(byName.feed).toMatchObject({ method: 'GET', transport: 'sse', path: '/feed' }); + expect(byName.chat).toMatchObject({ method: 'GET', transport: 'ws', path: '/chat' }); + expect(byName.either).toMatchObject({ method: 'GET', transport: 'negotiate', path: '/either' }); + expect(byName.make).toMatchObject({ method: 'POST', transport: 'buffer', path: '/make' }); + }); +}); From fdbba5f06dd52efc48629448784287e1fa1e05d2 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 27 Jun 2026 15:18:38 -0500 Subject: [PATCH 006/139] feat: @inbound and @abort handler argument decorators Signed-off-by: Diego Resendez --- src/params.ts | 12 +++++++++++- test/params.test.ts | 21 +++++++++++++++++++-- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/src/params.ts b/src/params.ts index 41c5e96..02f8a20 100644 --- a/src/params.ts +++ b/src/params.ts @@ -5,7 +5,7 @@ export type Query = Record; export type Headers = Record; export type Context = Record; -type ArgSource = 'ctx' | 'needs' | 'params' | 'query' | 'body' | 'headers'; +type ArgSource = 'ctx' | 'needs' | 'params' | 'query' | 'body' | 'headers' | 'inbound' | 'abort'; export interface ArgSpec { index: number; source: ArgSource; key?: string; keys?: string[] } const ARGS = Symbol('gt:args'); @@ -45,6 +45,14 @@ export function ctx(): ParameterDecorator { return (target, methodKey, index) => record(target, methodKey, { index, source: 'ctx' }); } +export function inbound(): ParameterDecorator { + return (target, methodKey, index) => record(target, methodKey, { index, source: 'inbound' }); +} + +export function abort(): ParameterDecorator { + return (target, methodKey, index) => record(target, methodKey, { index, source: 'abort' }); +} + export function getArgs(cls: Ctor, methodName: string): ArgSpec[] { const map: Record = Reflect.getMetadata(ARGS, cls) ?? {}; return [...(map[methodName] ?? [])].sort((a, b) => a.index - b.index); @@ -65,6 +73,8 @@ export function resolveArgs(specs: ArgSpec[], context: Context): unknown[] { function resolveOne(s: ArgSpec, context: Context): unknown { if (s.source === 'ctx') return context; if (s.source === 'needs') return context[s.key as string]; + if (s.source === 'inbound') return context.inbound; + if (s.source === 'abort') return context.abort; const bag = context[s.source]; if (typeof bag !== 'object' || bag === null) return bag; // can't pick from a non-object; return as-is const record = bag as Record; diff --git a/test/params.test.ts b/test/params.test.ts index 558949d..833ffb9 100644 --- a/test/params.test.ts +++ b/test/params.test.ts @@ -1,6 +1,6 @@ import 'reflect-metadata'; -import { expect, test } from 'vitest'; -import { needs, ctx, param, query, getArgs, getHandlerNeeds, resolveArgs } from '../src/params'; +import { expect, test, describe, it } from 'vitest'; +import { needs, ctx, param, query, inbound, abort, getArgs, getHandlerNeeds, resolveArgs } from '../src/params'; class Ctl { handler( @@ -45,3 +45,20 @@ test('a handler with no arg decorators resolves to no args', () => { class Bare { ping() { return 1; } } expect(resolveArgs(getArgs(Bare, 'ping'), {})).toEqual([]); }); + +describe('@inbound / @abort', () => { + it('resolves inbound and abort from reserved context keys, not as bags', () => { + class Ctl { handle(@inbound() inc: AsyncIterable, @abort() sig: AbortSignal) { return [inc, sig]; } } + const specs = getArgs(Ctl, 'handle'); + const ac = new AbortController(); + const inc = (async function* () {})(); + const args = resolveArgs(specs, { inbound: inc, abort: ac.signal }); + expect(args[0]).toBe(inc); + expect(args[1]).toBe(ac.signal); + }); + + it('inbound/abort do not count as graph needs', () => { + class Ctl { handle(@inbound() _i: AsyncIterable, @abort() _a: AbortSignal) {} } + expect(getHandlerNeeds(getArgs(Ctl, 'handle'))).toEqual([]); + }); +}); From 0eaefd00537b388431c39e792a81ce8362f1b768 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 27 Jun 2026 15:22:18 -0500 Subject: [PATCH 007/139] feat: SSE/ndjson streaming responses with backpressure and cleanup Signed-off-by: Diego Resendez --- src/bus.ts | 1 + src/http.ts | 105 +++++++++++++++++++++++++++++++++++----------- test/http.test.ts | 65 ++++++++++++++++++++++++++-- 3 files changed, 143 insertions(+), 28 deletions(-) diff --git a/src/bus.ts b/src/bus.ts index 4e576ce..4fe3a8c 100644 --- a/src/bus.ts +++ b/src/bus.ts @@ -1,6 +1,7 @@ export type LifecycleEvent = | 'boot:provider:start' | 'boot:provider:ok' | 'boot:provider:fail' | 'request:step:enter' | 'request:step:leave' | 'request:step:error' + | 'stream:open' | 'stream:close' | 'stream:error' | 'plugin:mounted'; export interface EventPayload { diff --git a/src/http.ts b/src/http.ts index b0dbff0..c0566c8 100644 --- a/src/http.ts +++ b/src/http.ts @@ -1,6 +1,10 @@ import http from 'http'; +import { once } from 'events'; import { errorToResponse } from './transformers'; -import type { ResponseShape } from './pipeline'; +import { sseEncoder, ndjsonEncoder, StreamEncoder } from './encoders'; +import { isStreamResult, type PipelineResult, type ResponseShape } from './pipeline'; +import type { Transport } from './metadata'; +import type { Bus } from './bus'; export type RouteHandler = (req: { method: string; url: string; @@ -8,24 +12,38 @@ export type RouteHandler = (req: { params: Record; query: Record; body: unknown; -}) => Promise; +}) => Promise; -export interface RouteDef { method: string; pattern: string; handler: RouteHandler } -export interface MatchedRoute { params: Record; handler: RouteHandler } +export interface RouteDef { method: string; pattern: string; transport: Transport; handler: RouteHandler } +export interface MatchedRoute { params: Record; def: RouteDef } + +export interface WsOpenCtx { + params: Record; + inbound: AsyncIterable; + abort: AbortSignal; + req: http.IncomingMessage; +} +export interface WsRouteDef { pattern: string; open: (ctx: WsOpenCtx) => Promise> } + +const PING_MS = 15_000; + +export function matchPattern(pattern: string, path: string): Record | undefined { + const segs = path.split('/').filter(Boolean); + const pat = pattern.split('/').filter(Boolean); + if (pat.length !== segs.length) return undefined; + const params: Record = {}; + for (let i = 0; i < pat.length; i++) { + if (pat[i].startsWith(':')) params[pat[i].slice(1)] = decodeURIComponent(segs[i]); + else if (pat[i] !== segs[i]) return undefined; + } + return params; +} export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined { - const segs = path.split('/').filter(Boolean); for (const r of routes) { if (r.method !== method) continue; - const pat = r.pattern.split('/').filter(Boolean); - if (pat.length !== segs.length) continue; - const params: Record = {}; - let ok = true; - for (let i = 0; i < pat.length; i++) { - if (pat[i].startsWith(':')) params[pat[i].slice(1)] = decodeURIComponent(segs[i]); - else if (pat[i] !== segs[i]) { ok = false; break; } - } - if (ok) return { params, handler: r.handler }; + const params = matchPattern(r.pattern, path); + if (params) return { params, def: r }; } return undefined; } @@ -45,8 +63,42 @@ async function readBody(req: http.IncomingMessage): Promise return raw === '' ? undefined : raw; } -export function createHttpServer(routes: RouteDef[]): http.Server { - return http.createServer(async (req, res) => { +function pickEncoder(transport: Transport, accept: string): StreamEncoder { + if (transport === 'sse') return sseEncoder; + if (transport === 'ndjson') return ndjsonEncoder; + return accept.includes('text/event-stream') ? sseEncoder : ndjsonEncoder; +} + +async function pipeStream( + res: http.ServerResponse, stream: AsyncIterable, encoder: StreamEncoder, + bus?: Bus, name = '', +): Promise { + res.writeHead(200, encoder.headers); + bus?.emit('stream:open', { name }); + const it = stream[Symbol.asyncIterator](); + let ping: ReturnType | undefined; + if (encoder.ping) { ping = setInterval(() => res.write(encoder.ping!()), PING_MS); ping.unref?.(); } + const stop = () => { if (ping) clearInterval(ping); void it.return?.(); }; + res.on('close', stop); + try { + while (true) { + const { value, done } = await it.next(); + if (done) break; + if (!res.write(encoder.encode(value))) await once(res, 'drain'); + } + } catch (err) { + bus?.emit('stream:error', { name, error: err }); + const frame = encoder.encodeError(err); + if (frame && !res.writableEnded) res.write(frame); + } finally { + if (ping) clearInterval(ping); + if (!res.writableEnded) res.end(); + bus?.emit('stream:close', { name }); + } +} + +export function createHttpServer(routes: RouteDef[], wsRoutes: WsRouteDef[] = [], bus?: Bus): http.Server { + const server = http.createServer(async (req, res) => { const url = req.url ?? '/'; const path = url.split('?')[0]; const matched = matchRoute(routes, req.method ?? 'GET', path); @@ -59,7 +111,6 @@ export function createHttpServer(routes: RouteDef[]): http.Server { try { raw = await readBody(req); } catch { - // stream/network failure — not the client's JSON fault res.writeHead(500, { 'content-type': 'application/json' }); res.end(JSON.stringify({ error: 'Internal Server Error' })); return; @@ -67,24 +118,30 @@ export function createHttpServer(routes: RouteDef[]): http.Server { let body: unknown = raw; const ct = String(req.headers['content-type'] ?? ''); if (raw !== undefined && ct.includes('application/json')) { - try { - body = JSON.parse(raw); - } catch { + try { body = JSON.parse(raw); } + catch { res.writeHead(400, { 'content-type': 'application/json' }); res.end(JSON.stringify({ error: 'Invalid JSON body' })); return; } } - let result: ResponseShape; + let result: PipelineResult; try { - result = await matched.handler({ + result = await matched.def.handler({ method: req.method ?? 'GET', url, headers: req.headers, params: matched.params, query: parseQuery(url), body, }); } catch (error) { result = errorToResponse(error); } - res.writeHead(result.status, result.headers); - res.end(result.body); + if (isStreamResult(result)) { + const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? '')); + await pipeStream(res, result.stream, encoder, bus, matched.def.pattern); + return; + } + const r: ResponseShape = result; + res.writeHead(r.status, r.headers); + res.end(r.body); }); + return server; // Task 7 will insert `attachWs(server, wsRoutes);` before this line } diff --git a/test/http.test.ts b/test/http.test.ts index 4a451bd..cc445d1 100644 --- a/test/http.test.ts +++ b/test/http.test.ts @@ -1,16 +1,16 @@ -import { expect, test } from 'vitest'; +import { describe, expect, it, test } from 'vitest'; import { matchRoute, parseQuery, createHttpServer } from '../src/http'; const handler = async () => ({ status: 200, headers: {}, body: 'ok' }); test('matches a static + :param route and extracts params', () => { - const routes = [{ method: 'GET', pattern: '/api/users/:id', handler }]; + const routes = [{ method: 'GET', pattern: '/api/users/:id', transport: 'buffer' as const, handler }]; const m = matchRoute(routes, 'GET', '/api/users/42'); expect(m?.params).toEqual({ id: '42' }); }); test('returns undefined when nothing matches', () => { - const routes = [{ method: 'GET', pattern: '/api/users/:id', handler }]; + const routes = [{ method: 'GET', pattern: '/api/users/:id', transport: 'buffer' as const, handler }]; expect(matchRoute(routes, 'GET', '/api/orders/1')).toBeUndefined(); expect(matchRoute(routes, 'POST', '/api/users/1')).toBeUndefined(); }); @@ -22,7 +22,7 @@ test('parseQuery extracts query params from a url', () => { test('server parses json body and rejects malformed json with 400', async () => { const server = createHttpServer([{ - method: 'POST', pattern: '/echo', + method: 'POST', pattern: '/echo', transport: 'buffer', handler: async (req) => ({ status: 200, headers: { 'content-type': 'application/json' }, body: JSON.stringify({ got: req.body, q: req.query }) }), }]); await new Promise((r) => server.listen(0, r)); @@ -40,3 +40,60 @@ test('server parses json body and rejects malformed json with 400', async () => server.close(); }); + +const getServerUrl = (server: import('http').Server) => { + const addr = server.address(); + if (addr && typeof addr === 'object') return `http://127.0.0.1:${addr.port}`; + throw new Error('no address'); +}; + +describe('http streaming', () => { + it('streams SSE events from an async-iterable handler and runs finally on disconnect', async () => { + let cleanedUp = false; + async function* feed() { + try { yield { n: 1 }; yield { n: 2 }; await new Promise((r) => setTimeout(r, 50)); yield { n: 3 }; } + finally { cleanedUp = true; } + } + const server = createHttpServer([ + { method: 'GET', pattern: '/feed', transport: 'sse', handler: async () => ({ stream: feed() }) }, + ]); + await new Promise((r) => server.listen(0, r)); + const res = await fetch(`${getServerUrl(server)}/feed`, { headers: { accept: 'text/event-stream' } }); + expect(res.headers.get('content-type')).toBe('text/event-stream'); + const reader = res.body!.getReader(); + const dec = new TextDecoder(); + let buf = ''; + while (!buf.includes('data: {"n":2}')) buf += dec.decode((await reader.read()).value); + expect(buf).toContain('data: {"n":1}\n\n'); + await reader.cancel(); // client disconnect + await new Promise((r) => setTimeout(r, 60)); + expect(cleanedUp).toBe(true); + server.close(); + }); + + it('frames a mid-stream error and closes', async () => { + async function* boom() { yield { ok: true }; throw new Error('kaboom'); } + const server = createHttpServer([ + { method: 'GET', pattern: '/boom', transport: 'sse', handler: async () => ({ stream: boom() }) }, + ]); + await new Promise((r) => server.listen(0, r)); + const res = await fetch(`${getServerUrl(server)}/boom`, { headers: { accept: 'text/event-stream' } }); + const text = await res.text(); + expect(text).toContain('data: {"ok":true}\n\n'); + expect(text).toContain('event: error'); + expect(text).toContain('kaboom'); + server.close(); + }); + + it('routes by method (non-GET no longer falls through)', async () => { + const server = createHttpServer([ + { method: 'POST', pattern: '/make', transport: 'buffer', + handler: async () => ({ status: 201, headers: { 'content-type': 'application/json' }, body: '{"made":true}' }) }, + ]); + await new Promise((r) => server.listen(0, r)); + const res = await fetch(`${getServerUrl(server)}/make`, { method: 'POST' }); + expect(res.status).toBe(201); + expect(await res.json()).toEqual({ made: true }); + server.close(); + }); +}); From 8aac7f24bd97432c8ec8a06d55fc8843d4f9cf84 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 27 Jun 2026 15:26:17 -0500 Subject: [PATCH 008/139] fix: prevent stream hang/crash on client disconnect during backpressure Signed-off-by: Diego Resendez --- src/http.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/http.ts b/src/http.ts index c0566c8..f19c717 100644 --- a/src/http.ts +++ b/src/http.ts @@ -78,13 +78,16 @@ async function pipeStream( const it = stream[Symbol.asyncIterator](); let ping: ReturnType | undefined; if (encoder.ping) { ping = setInterval(() => res.write(encoder.ping!()), PING_MS); ping.unref?.(); } - const stop = () => { if (ping) clearInterval(ping); void it.return?.(); }; + const stop = () => { if (ping) clearInterval(ping); void Promise.resolve(it.return?.()).catch(() => {}); }; res.on('close', stop); try { while (true) { const { value, done } = await it.next(); if (done) break; - if (!res.write(encoder.encode(value))) await once(res, 'drain'); + if (!res.write(encoder.encode(value))) { + await Promise.race([once(res, 'drain'), once(res, 'close')]); + if (res.destroyed) break; // let finally clean up + } } } catch (err) { bus?.emit('stream:error', { name, error: err }); @@ -92,7 +95,7 @@ async function pipeStream( if (frame && !res.writableEnded) res.write(frame); } finally { if (ping) clearInterval(ping); - if (!res.writableEnded) res.end(); + if (!res.writableEnded && !res.destroyed) res.end(); bus?.emit('stream:close', { name }); } } From abc4603050e1d71da034067baf235a42360ab715 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 27 Jun 2026 15:29:14 -0500 Subject: [PATCH 009/139] feat: WebSocket upgrade path with lazy optional ws dependency Signed-off-by: Diego Resendez --- package-lock.json | 36 +++++++++++++++++++++++++++++++++++- package.json | 12 +++++++++++- src/http.ts | 35 ++++++++++++++++++++++++++++++++++- test/ws.test.ts | 37 +++++++++++++++++++++++++++++++++++++ 4 files changed, 117 insertions(+), 3 deletions(-) create mode 100644 test/ws.test.ts diff --git a/package-lock.json b/package-lock.json index acd3005..ad8d4ec 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,8 +13,10 @@ }, "devDependencies": { "@types/node": "^18.19.0", + "@types/ws": "^8.18.1", "typescript": "^5.5.0", - "vitest": "^2.0.0" + "vitest": "^2.0.0", + "ws": "^8.21.0" } }, "node_modules/@esbuild/aix-ppc64": { @@ -782,6 +784,16 @@ "undici-types": "~5.26.4" } }, + "node_modules/@types/ws": { + "version": "8.18.1", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz", + "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@vitest/expect": { "version": "2.1.9", "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-2.1.9.tgz", @@ -1459,6 +1471,28 @@ "engines": { "node": ">=8" } + }, + "node_modules/ws": { + "version": "8.21.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", + "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } } } } diff --git a/package.json b/package.json index ce1672b..de2f292 100644 --- a/package.json +++ b/package.json @@ -15,9 +15,19 @@ "dependencies": { "reflect-metadata": "0.2.2" }, + "peerDependencies": { + "ws": "^8.18.0" + }, + "peerDependenciesMeta": { + "ws": { + "optional": true + } + }, "devDependencies": { + "@types/node": "^18.19.0", + "@types/ws": "^8.18.1", "typescript": "^5.5.0", "vitest": "^2.0.0", - "@types/node": "^18.19.0" + "ws": "^8.21.0" } } diff --git a/src/http.ts b/src/http.ts index f19c717..615f4c8 100644 --- a/src/http.ts +++ b/src/http.ts @@ -1,5 +1,6 @@ import http from 'http'; import { once } from 'events'; +import { channel } from './channel'; import { errorToResponse } from './transformers'; import { sseEncoder, ndjsonEncoder, StreamEncoder } from './encoders'; import { isStreamResult, type PipelineResult, type ResponseShape } from './pipeline'; @@ -100,6 +101,37 @@ async function pipeStream( } } +function loadWss(): any | null { + try { return require('ws').WebSocketServer; } catch { return null; } +} + +function attachWs(server: http.Server, wsRoutes: WsRouteDef[]): void { + if (wsRoutes.length === 0) return; + const WSS = loadWss(); + const wss = WSS ? new WSS({ noServer: true }) : null; + server.on('upgrade', (req, socket, head) => { + const path = (req.url ?? '/').split('?')[0]; + const route = wsRoutes.map((r) => ({ r, params: matchPattern(r.pattern, path) })).find((x) => x.params); + if (!route) { socket.destroy(); return; } + if (!wss) { socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n'); socket.destroy(); return; } + wss.handleUpgrade(req, socket, head, async (ws: any) => { + const inbound = channel(); + const ac = new AbortController(); + ws.on('message', (d: Buffer) => inbound.push(d.toString())); + ws.on('close', () => { inbound.close(); ac.abort(); }); + ws.on('error', (e: unknown) => inbound.fail(e)); + try { + const out = await route.r.open({ params: route.params!, inbound, abort: ac.signal, req }); + for await (const m of out) ws.send(typeof m === 'string' ? m : JSON.stringify(m)); + ws.close(); + } catch { + try { ws.close(1011); } catch { /* already closed */ } + ac.abort(); + } + }); + }); +} + export function createHttpServer(routes: RouteDef[], wsRoutes: WsRouteDef[] = [], bus?: Bus): http.Server { const server = http.createServer(async (req, res) => { const url = req.url ?? '/'; @@ -146,5 +178,6 @@ export function createHttpServer(routes: RouteDef[], wsRoutes: WsRouteDef[] = [] res.writeHead(r.status, r.headers); res.end(r.body); }); - return server; // Task 7 will insert `attachWs(server, wsRoutes);` before this line + attachWs(server, wsRoutes); + return server; } diff --git a/test/ws.test.ts b/test/ws.test.ts new file mode 100644 index 0000000..571e9c3 --- /dev/null +++ b/test/ws.test.ts @@ -0,0 +1,37 @@ +import { describe, it, expect } from 'vitest'; +import WebSocket from 'ws'; +import { channel } from '../src/channel'; +import { createHttpServer, type WsRouteDef } from '../src/http'; + +const url = (server: import('http').Server, path: string) => { + const a = server.address(); + if (a && typeof a === 'object') return `ws://127.0.0.1:${a.port}${path}`; + throw new Error('no address'); +}; + +describe('ws upgrade', () => { + it('echoes inbound to outbound and aborts on close', async () => { + let aborted = false; + const wsRoutes: WsRouteDef[] = [{ + pattern: '/echo', + open: async ({ inbound, abort }) => { + abort.addEventListener('abort', () => { aborted = true; }); + const out = channel(); + (async () => { for await (const m of inbound) out.push(`echo:${m}`); out.close(); })(); + return out; + }, + }]; + const server = createHttpServer([], wsRoutes); + await new Promise((r) => server.listen(0, r)); + + const client = new WebSocket(url(server, '/echo')); + await new Promise((r) => client.on('open', r)); + const got = new Promise((r) => client.on('message', (d) => r(d.toString()))); + client.send('hi'); + expect(await got).toBe('echo:hi'); + client.close(); + await new Promise((r) => setTimeout(r, 50)); + expect(aborted).toBe(true); + server.close(); + }); +}); From 04688ab621be231c92262bf1df618cd860b39737 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 27 Jun 2026 15:32:17 -0500 Subject: [PATCH 010/139] feat: wire SSE/WS routes through the graph with stream lifecycle events Signed-off-by: Diego Resendez --- src/app.ts | 79 +++++++++++++++++++++++++++++++----------------- test/app.test.ts | 48 ++++++++++++++++++++++++++++- 2 files changed, 98 insertions(+), 29 deletions(-) diff --git a/src/app.ts b/src/app.ts index fb072b8..ea61bf5 100644 --- a/src/app.ts +++ b/src/app.ts @@ -3,11 +3,12 @@ import { Bus } from './bus'; import { Container } from './container'; import { topoSort, GraphNode } from './graph'; import { runPipeline, PipelineStep } from './pipeline'; -import { createHttpServer, RouteDef } from './http'; +import { createHttpServer, parseQuery, RouteDef, WsRouteDef } from './http'; +import { isAsyncIterable } from './channel'; import { JsonTransformer } from './transformers'; import { mountPlugin, Plugin, ScopeApi, ScopeNode } from './plugin'; import { - Ctor, getModuleMeta, getProviderMeta, getStepMeta, getRoutes, getTransformer, joinPath, + Ctor, HttpMethod, Transport, getModuleMeta, getProviderMeta, getStepMeta, getRoutes, getTransformer, joinPath, } from './metadata'; import { getArgs, getHandlerNeeds, resolveArgs } from './params'; @@ -20,6 +21,8 @@ export interface App { interface RoutePlan { pattern: string; + method: HttpMethod; + transport: Transport; origin: string; providers: GraphNode[]; steps: GraphNode[]; @@ -70,6 +73,8 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[] }): App { const argSpecs = getArgs(C, route.handlerName); routePlans.push({ pattern: joinPath(m.mountpoint, route.path), + method: route.method, + transport: route.transport, origin, providers: [], steps: [], @@ -102,7 +107,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[] }): App { ...providerNodes.flatMap((n) => n.provides), ...stepNodes.flatMap((n) => n.provides), ]); - const allowed = new Set([...producedKeys, 'req', 'params', 'query', 'body', 'headers']); + const allowed = new Set([...producedKeys, 'req', 'params', 'query', 'body', 'headers', 'inbound', 'abort']); for (const plan of routePlans) { for (const need of plan.needs) { if (!allowed.has(need)) { @@ -121,6 +126,19 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[] }): App { ]; }; + const providedSeed = async (plan: RoutePlan): Promise> => { + const provided: Record = {}; + for (const p of plan.providers) { + if (container.has(p.name)) Object.assign(provided, (await container.resolve(p.name)) as Record); + } + return provided; + }; + const planSteps = (plan: RoutePlan): PipelineStep[] => plan.steps.map((s) => { + const fn = runners.get(s.name); + if (!fn) throw new Error(`no runner registered for step '${s.name}'`); + return { name: s.name, origin: s.origin, run: fn }; + }); + const listen = async (port: number): Promise => { // run app-scoped providers in order (fail-fast for required) for (const node of orderedProviders) { @@ -141,32 +159,37 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[] }): App { } } - const routeDefs: RouteDef[] = routePlans.map((plan) => ({ - method: 'GET', - pattern: plan.pattern, - handler: async (req) => { - // build app-scoped seed by spreading each provider's resolved value into context - // providers follow the same merge convention as steps: return { token: value } - const provided: Record = {}; - for (const p of plan.providers) { - if (container.has(p.name)) { - const resolved = (await container.resolve(p.name)) as Record; - Object.assign(provided, resolved); - } - } - const steps: PipelineStep[] = plan.steps.map((s) => { - const fn = runners.get(s.name); - if (!fn) throw new Error(`no runner registered for step '${s.name}'`); - return { name: s.name, origin: s.origin, run: fn }; - }); - return runPipeline({ - steps, handler: plan.run, transformer: plan.transformer, bus, - seed: { ...provided, req, params: req.params, query: req.query, body: req.body, headers: req.headers }, - }); - }, - })); + const httpRoutes: RouteDef[] = routePlans + .filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate + .map((plan) => ({ + method: plan.method, pattern: plan.pattern, transport: plan.transport, + handler: async (req) => { + const provided = await providedSeed(plan); + return runPipeline({ + steps: planSteps(plan), handler: plan.run, transformer: plan.transformer, bus, + seed: { ...provided, req, params: req.params, query: req.query, body: req.body, headers: req.headers }, + }); + }, + })); - const server = createHttpServer(routeDefs); + const wsRoutes: WsRouteDef[] = routePlans + .filter((plan) => plan.transport === 'ws' || plan.transport === 'negotiate') + .map((plan) => ({ + pattern: plan.pattern, + open: async ({ params, inbound, abort, req }) => { + bus.emit('stream:open', { name: plan.pattern }); + const provided = await providedSeed(plan); + let ctx: any = { ...provided, req, params, query: parseQuery(req.url ?? ''), body: undefined, + headers: req.headers, inbound, abort }; + for (const s of planSteps(plan)) { ctx = { ...ctx, ...(await s.run(ctx)) }; } + const out = plan.run(ctx); + abort.addEventListener('abort', () => bus.emit('stream:close', { name: plan.pattern })); + if (!isAsyncIterable(out)) throw new Error(`@Ws handler '${plan.handlerName}' must return an AsyncIterable`); + return out as AsyncIterable; + }, + })); + + const server = createHttpServer(httpRoutes, wsRoutes, bus); await new Promise((resolve) => server.listen(port, resolve)); return server; }; diff --git a/test/app.test.ts b/test/app.test.ts index 5db5423..250bd36 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -1,5 +1,5 @@ import 'reflect-metadata'; -import { expect, test, vi } from 'vitest'; +import { describe, expect, it, test, vi } from 'vitest'; import { Provider, Step, Route, Get, Module, Transformer } from '../src/metadata'; import { JsonTransformer } from '../src/transformers'; import { Unauthorized } from '../src/signals'; @@ -107,3 +107,49 @@ test('boot fails when a handler needs something nothing provides', () => { expect(() => createApp({ modules: [ThingModule] })) .toThrow(/handler 'list' needs 'missing'/); }); + +import { Sse, Ws } from '../src/metadata'; +import { inbound } from '../src/params'; +import { channel } from '../src/channel'; + +describe('app streaming wiring', () => { + it('serves an SSE route declared with @Sse', async () => { + @Route('/') + class Ctl { + @Sse('/ticks') ticks() { + return (async function* () { yield { t: 1 }; yield { t: 2 }; })(); + } + } + @Module({ mountpoint: '/', controllers: [Ctl] }) class M {} + const app = createApp({ modules: [M] }); + const server = await app.listen(0); + const addr = server.address() as import('net').AddressInfo; + const res = await fetch(`http://127.0.0.1:${addr.port}/ticks`, { headers: { accept: 'text/event-stream' } }); + expect(res.headers.get('content-type')).toBe('text/event-stream'); + const text = await res.text(); + expect(text).toContain('data: {"t":1}'); + server.close(); + }); + + it('serves a @Ws route receiving @inbound and returning a channel', async () => { + @Route('/') + class Ctl { + @Ws('/echo') echo(@inbound() inc: AsyncIterable) { + const out = channel(); + (async () => { for await (const m of inc) out.push(`re:${m}`); out.close(); })(); + return out; + } + } + @Module({ mountpoint: '/', controllers: [Ctl] }) class M {} + const app = createApp({ modules: [M] }); + const server = await app.listen(0); + const addr = server.address() as import('net').AddressInfo; + const WebSocket = (await import('ws')).default; + const client = new WebSocket(`ws://127.0.0.1:${addr.port}/echo`); + await new Promise((r) => client.on('open', r)); + const got = new Promise((r) => client.on('message', (d: Buffer) => r(d.toString()))); + client.send('yo'); + expect(await got).toBe('re:yo'); + client.close(); server.close(); + }); +}); From b58db714058d9672d296741f7a95cb951ecc5791 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 27 Jun 2026 15:34:27 -0500 Subject: [PATCH 011/139] feat: export streams API and add SSE/WS example endpoints Signed-off-by: Diego Resendez --- example/server.ts | 31 ++++++++++++++++++++++++++++++- src/index.ts | 7 +++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/example/server.ts b/example/server.ts index cd582ea..09c4b3b 100644 --- a/example/server.ts +++ b/example/server.ts @@ -1,4 +1,4 @@ -import { createApp, Provider, Step, Route, Get, Module, Transformer, JsonTransformer, Unauthorized, Plugin, needs, param } from '../src/index'; +import { createApp, Provider, Step, Route, Get, Module, Transformer, JsonTransformer, Unauthorized, Plugin, needs, param, Sse, Ws, inbound, channel } from '../src/index'; interface User { id: string; name: string } @@ -37,7 +37,36 @@ const logger: Plugin = (api) => { export const app = createApp({ modules: [ApiModule], plugins: [logger] }); +@Route('/feed') +class FeedController { + @Sse('/ticks') + ticks() { + return (async function* () { + for (let n = 1; n <= 3; n++) yield { tick: n }; + })(); + } +} + +@Route('/chat') +class ChatController { + @Ws('/echo') + echo(@inbound() incoming: AsyncIterable) { + const out = channel(); + (async () => { + for await (const msg of incoming) out.push(`echo: ${msg}`); + out.close(); + })(); + return out; + } +} + +@Module({ mountpoint: '/', controllers: [FeedController, ChatController] }) +class StreamModule {} + +export const streamApp = createApp({ modules: [StreamModule] }); + if (require.main === module) { console.log('chain for /api/users/:id ->', app.inspect('/api/users/:id')); app.listen(3000).then(() => console.log('green-tea on http://localhost:3000')); + streamApp.listen(3001).then(() => console.log('green-tea streams on http://localhost:3001')); } diff --git a/src/index.ts b/src/index.ts index a108abd..03edddc 100644 --- a/src/index.ts +++ b/src/index.ts @@ -12,3 +12,10 @@ export { flow, Flow } from './flow'; export type { StepFn, CompiledFlow } from './flow'; export { needs, ctx, param, query, body, headers } from './params'; export type { Query, Headers, Context, ArgSpec } from './params'; +export { channel, isAsyncIterable } from './channel'; +export type { Channel } from './channel'; +export { Sse, Ws, Stream, Post, Put, Patch, Delete } from './metadata'; +export type { Transport, HttpMethod } from './metadata'; +export { inbound, abort } from './params'; +export { sseEncoder, ndjsonEncoder } from './encoders'; +export type { StreamEncoder } from './encoders'; From e365cee3bffcd282e374fa66329464957912e39a Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 27 Jun 2026 15:40:50 -0500 Subject: [PATCH 012/139] fix: transport owns WS stream lifecycle (force-cancel outbound, emit stream:error, balanced events) Signed-off-by: Diego Resendez --- src/app.ts | 2 -- src/http.ts | 27 +++++++++++++++++++++------ 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/src/app.ts b/src/app.ts index ea61bf5..69eba59 100644 --- a/src/app.ts +++ b/src/app.ts @@ -177,13 +177,11 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[] }): App { .map((plan) => ({ pattern: plan.pattern, open: async ({ params, inbound, abort, req }) => { - bus.emit('stream:open', { name: plan.pattern }); const provided = await providedSeed(plan); let ctx: any = { ...provided, req, params, query: parseQuery(req.url ?? ''), body: undefined, headers: req.headers, inbound, abort }; for (const s of planSteps(plan)) { ctx = { ...ctx, ...(await s.run(ctx)) }; } const out = plan.run(ctx); - abort.addEventListener('abort', () => bus.emit('stream:close', { name: plan.pattern })); if (!isAsyncIterable(out)) throw new Error(`@Ws handler '${plan.handlerName}' must return an AsyncIterable`); return out as AsyncIterable; }, diff --git a/src/http.ts b/src/http.ts index 615f4c8..a9253d6 100644 --- a/src/http.ts +++ b/src/http.ts @@ -81,12 +81,13 @@ async function pipeStream( if (encoder.ping) { ping = setInterval(() => res.write(encoder.ping!()), PING_MS); ping.unref?.(); } const stop = () => { if (ping) clearInterval(ping); void Promise.resolve(it.return?.()).catch(() => {}); }; res.on('close', stop); + const onClose = once(res, 'close'); try { while (true) { const { value, done } = await it.next(); if (done) break; if (!res.write(encoder.encode(value))) { - await Promise.race([once(res, 'drain'), once(res, 'close')]); + await Promise.race([once(res, 'drain'), onClose]); if (res.destroyed) break; // let finally clean up } } @@ -105,7 +106,7 @@ function loadWss(): any | null { try { return require('ws').WebSocketServer; } catch { return null; } } -function attachWs(server: http.Server, wsRoutes: WsRouteDef[]): void { +function attachWs(server: http.Server, wsRoutes: WsRouteDef[], bus?: Bus): void { if (wsRoutes.length === 0) return; const WSS = loadWss(); const wss = WSS ? new WSS({ noServer: true }) : null; @@ -120,13 +121,27 @@ function attachWs(server: http.Server, wsRoutes: WsRouteDef[]): void { ws.on('message', (d: Buffer) => inbound.push(d.toString())); ws.on('close', () => { inbound.close(); ac.abort(); }); ws.on('error', (e: unknown) => inbound.fail(e)); + + const name = route.r.pattern; + let it: AsyncIterator | undefined; + ws.on('close', () => { void Promise.resolve(it?.return?.()).catch(() => {}); }); // force-cancel outbound + bus?.emit('stream:open', { name }); try { const out = await route.r.open({ params: route.params!, inbound, abort: ac.signal, req }); - for await (const m of out) ws.send(typeof m === 'string' ? m : JSON.stringify(m)); - ws.close(); - } catch { + it = out[Symbol.asyncIterator](); + while (true) { + const { value, done } = await it.next(); + if (done) break; + if (ws.readyState !== 1) break; // 1 = OPEN; stop if socket gone + ws.send(typeof value === 'string' ? value : JSON.stringify(value)); + } + try { ws.close(); } catch { /* already closed */ } + } catch (err) { + bus?.emit('stream:error', { name, error: err }); try { ws.close(1011); } catch { /* already closed */ } + } finally { ac.abort(); + bus?.emit('stream:close', { name }); } }); }); @@ -178,6 +193,6 @@ export function createHttpServer(routes: RouteDef[], wsRoutes: WsRouteDef[] = [] res.writeHead(r.status, r.headers); res.end(r.body); }); - attachWs(server, wsRoutes); + attachWs(server, wsRoutes, bus); return server; } From 31f91ee61f1d08e1695160381d433dbb06628afa Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 27 Jun 2026 20:23:58 -0500 Subject: [PATCH 013/139] feat(mesh): RPC frame protocol and codec Signed-off-by: Diego Resendez --- src/mesh/protocol.ts | 32 ++++++++++++++++++++++++++++++++ test/mesh/protocol.test.ts | 25 +++++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 src/mesh/protocol.ts create mode 100644 test/mesh/protocol.test.ts diff --git a/src/mesh/protocol.ts b/src/mesh/protocol.ts new file mode 100644 index 0000000..b37d242 --- /dev/null +++ b/src/mesh/protocol.ts @@ -0,0 +1,32 @@ +export interface RequestEnvelope { + method: string; + params: Record; + query: Record; + body: unknown; + headers: Record; +} + +export interface ScopeEntry { token: string; scope: 'app' | 'request' } +export interface RouteEntry { method: string; pattern: string } +export interface Manifest { scopes: ScopeEntry[]; routes: RouteEntry[] } + +export type Frame = + | { type: 'hello'; secret: string } + | { type: 'manifest'; scopes: ScopeEntry[]; routes: RouteEntry[] } + | { type: 'rpc-req'; id: string; kind: 'scope' | 'route'; name: string; ctx: RequestEnvelope } + | { type: 'rpc-res'; id: string; ok: true; result: unknown } + | { type: 'rpc-res'; id: string; ok: false; error: { message: string; status?: number } }; + +const TYPES = new Set(['hello', 'manifest', 'rpc-req', 'rpc-res']); + +export function encode(f: Frame): string { + return JSON.stringify(f); +} + +export function decode(s: string): Frame { + const f = JSON.parse(s) as { type?: unknown }; + if (typeof f.type !== 'string' || !TYPES.has(f.type)) { + throw new Error(`unknown frame type: ${String(f.type)}`); + } + return f as Frame; +} diff --git a/test/mesh/protocol.test.ts b/test/mesh/protocol.test.ts new file mode 100644 index 0000000..f390593 --- /dev/null +++ b/test/mesh/protocol.test.ts @@ -0,0 +1,25 @@ +import { describe, it, expect } from 'vitest'; +import { encode, decode, type Frame, type RequestEnvelope } from '../../src/mesh/protocol'; + +const env: RequestEnvelope = { method: 'GET', params: { id: '1' }, query: {}, body: undefined, headers: {} }; + +describe('protocol codec', () => { + it('round-trips each frame type', () => { + const frames: Frame[] = [ + { type: 'hello', 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: 'rpc-res', id: 'c1:1', ok: true, result: { id: 'u1' } }, + { type: 'rpc-res', id: 'c1:2', ok: false, error: { message: 'no', status: 401 } }, + ]; + for (const f of frames) expect(decode(encode(f))).toEqual(f); + }); + + it('throws on malformed json', () => { + expect(() => decode('{not json')).toThrow(); + }); + + it('throws on unknown frame type', () => { + expect(() => decode(JSON.stringify({ type: 'bogus' }))).toThrow(/unknown frame/i); + }); +}); From ec1214e9e5ccf050bb144c0bb2b291bb60fdd60d Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 27 Jun 2026 20:25:53 -0500 Subject: [PATCH 014/139] feat(mesh): export flag on providers, steps, and routes Signed-off-by: Diego Resendez --- src/metadata.ts | 18 +++++++++--------- test/metadata.test.ts | 27 ++++++++++++++++++++++++--- 2 files changed, 33 insertions(+), 12 deletions(-) diff --git a/src/metadata.ts b/src/metadata.ts index 9419cb7..33e48dc 100644 --- a/src/metadata.ts +++ b/src/metadata.ts @@ -3,11 +3,11 @@ import 'reflect-metadata'; export type Ctor = new (...args: any[]) => any; export type TransformerFn = (value: unknown) => { status?: number; headers?: Record; body: string }; -export interface ProviderMeta { provides: string; needs: string[]; optional: boolean } -export interface StepMeta { provides: string; needs: string[]; optional: boolean } +export interface ProviderMeta { provides: string; needs: string[]; optional: boolean; export: boolean } +export interface StepMeta { provides: string; needs: string[]; optional: boolean; export: boolean } export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; export type Transport = 'buffer' | 'sse' | 'ndjson' | 'negotiate' | 'ws'; -export interface RouteMeta { method: HttpMethod; path: string; handlerName: string; transport: Transport } +export interface RouteMeta { method: HttpMethod; path: string; handlerName: string; transport: Transport; export: boolean } export interface ModuleOptions { mountpoint: string; providers?: Ctor[]; steps?: Ctor[]; controllers?: Ctor[]; } @@ -21,16 +21,16 @@ const K = { transformer: Symbol('gt:transformer'), }; -export function Provider(opts: { provides: string; needs?: string[]; optional?: boolean }): ClassDecorator { +export function Provider(opts: { provides: string; needs?: string[]; optional?: boolean; export?: boolean }): ClassDecorator { return (target) => { - const meta: ProviderMeta = { provides: opts.provides, needs: opts.needs ?? [], optional: opts.optional ?? false }; + const meta: ProviderMeta = { provides: opts.provides, needs: opts.needs ?? [], optional: opts.optional ?? false, export: opts.export ?? false }; Reflect.defineMetadata(K.provider, meta, target); }; } -export function Step(opts: { provides: string; needs?: string[]; optional?: boolean }): ClassDecorator { +export function Step(opts: { provides: string; needs?: string[]; optional?: boolean; export?: boolean }): ClassDecorator { return (target) => { - const meta: StepMeta = { provides: opts.provides, needs: opts.needs ?? [], optional: opts.optional ?? false }; + const meta: StepMeta = { provides: opts.provides, needs: opts.needs ?? [], optional: opts.optional ?? false, export: opts.export ?? false }; Reflect.defineMetadata(K.step, meta, target); }; } @@ -40,11 +40,11 @@ export function Route(prefix: string): ClassDecorator { } function routeDecorator(method: HttpMethod, transport: Transport) { - return (path: string): MethodDecorator => + return (path: string, opts?: { export?: boolean }): MethodDecorator => (target, propertyKey) => { const ctor = target.constructor; const routes = (Reflect.getMetadata(K.routes, ctor) as RouteMeta[]) ?? []; - routes.push({ method, path, handlerName: String(propertyKey), transport }); + routes.push({ method, path, handlerName: String(propertyKey), transport, export: opts?.export ?? false }); Reflect.defineMetadata(K.routes, routes, ctor); }; } diff --git a/test/metadata.test.ts b/test/metadata.test.ts index 8bcb251..300d811 100644 --- a/test/metadata.test.ts +++ b/test/metadata.test.ts @@ -19,15 +19,15 @@ class Ctl { @Get('/:id') getUser() { return 1; } } class ApiModule {} test('provider metadata is readable', () => { - expect(getProviderMeta(Db)).toEqual({ provides: 'db', needs: ['config'], optional: false }); + expect(getProviderMeta(Db)).toEqual({ provides: 'db', needs: ['config'], optional: false, export: false }); }); test('step metadata is readable', () => { - expect(getStepMeta(Auth)).toEqual({ provides: 'user', needs: ['db', 'req'], optional: false }); + expect(getStepMeta(Auth)).toEqual({ provides: 'user', needs: ['db', 'req'], optional: false, export: false }); }); test('routes carry method, path and handler name', () => { - expect(getRoutes(Ctl)).toEqual([{ method: 'GET', path: '/users/:id', handlerName: 'getUser', transport: 'buffer' }]); + expect(getRoutes(Ctl)).toEqual([{ method: 'GET', path: '/users/:id', handlerName: 'getUser', transport: 'buffer', export: false }]); }); test('module metadata lists members', () => { @@ -53,3 +53,24 @@ describe('stream route decorators', () => { expect(byName.make).toMatchObject({ method: 'POST', transport: 'buffer', path: '/make' }); }); }); + +describe('mesh export flags', () => { + it('providers/steps carry export (default false)', () => { + @Provider({ provides: 'config', export: true }) class C { provide() { return {}; } } + @Step({ provides: 'auth', export: true }) class A { run() { return {}; } } + @Provider({ provides: 'priv' }) class P { provide() { return {}; } } + expect(getProviderMeta(C)!.export).toBe(true); + expect(getStepMeta(A)!.export).toBe(true); + expect(getProviderMeta(P)!.export).toBe(false); + }); + + it('routes carry export via decorator option (default false)', () => { + class Ctl2 { + @Get('/pub', { export: true }) pub() {} + @Get('/priv') priv() {} + } + const byName = Object.fromEntries(getRoutes(Ctl2).map((r) => [r.handlerName, r])); + expect(byName.pub.export).toBe(true); + expect(byName.priv.export).toBe(false); + }); +}); From 9f963792f00e1b2eb596fdb190bf4de200c99f01 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 27 Jun 2026 20:26:37 -0500 Subject: [PATCH 015/139] feat(mesh): mesh lifecycle bus events Signed-off-by: Diego Resendez --- src/bus.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/bus.ts b/src/bus.ts index 4fe3a8c..9143d9e 100644 --- a/src/bus.ts +++ b/src/bus.ts @@ -2,6 +2,7 @@ export type LifecycleEvent = | 'boot:provider:start' | 'boot:provider:ok' | 'boot:provider:fail' | 'request:step:enter' | 'request:step:leave' | 'request:step:error' | 'stream:open' | 'stream:close' | 'stream:error' + | 'mesh:connect' | 'mesh:disconnect' | 'mesh:rpc:error' | 'plugin:mounted'; export interface EventPayload { From c4f220f4312b958f2276990695edb33d69105d66 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 27 Jun 2026 20:28:21 -0500 Subject: [PATCH 016/139] feat(mesh): teapot manifest builder and control-channel dispatcher Signed-off-by: Diego Resendez --- src/mesh/teapot.ts | 82 +++++++++++++++++++++++++++++++++++++++ test/mesh/teapot.test.ts | 84 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 166 insertions(+) create mode 100644 src/mesh/teapot.ts create mode 100644 test/mesh/teapot.test.ts diff --git a/src/mesh/teapot.ts b/src/mesh/teapot.ts new file mode 100644 index 0000000..e0e5496 --- /dev/null +++ b/src/mesh/teapot.ts @@ -0,0 +1,82 @@ +import crypto from 'crypto'; +import type { Bus } from '../bus'; +import type { ResponseShape } from '../pipeline'; +import { isHttpError } from '../signals'; +import { encode, decode, type Manifest, type RequestEnvelope, type RouteEntry, type Frame } from './protocol'; + +export const MESH_CONTROL_PATH = '/__mesh__/control'; + +export function buildManifest(args: { + providers: string[]; // exported provider tokens (app-scope) + steps: string[]; // exported step tokens (request-scope) + routes: RouteEntry[]; // exported buffered routes +}): Manifest { + return { + scopes: [ + ...args.providers.map((token) => ({ token, scope: 'app' as const })), + ...args.steps.map((token) => ({ token, scope: 'request' as const })), + ], + routes: args.routes, + }; +} + +function safeEqual(a: string, b: string): boolean { + const ba = Buffer.from(a); + const bb = Buffer.from(b); + if (ba.length !== bb.length) return false; + return crypto.timingSafeEqual(ba, bb); +} + +export interface MeshControlDeps { + secret: string; + manifest: Manifest; + resolveScope: (name: string, env: RequestEnvelope) => Promise; + resolveRoute: (name: string, env: RequestEnvelope) => Promise; + bus?: Bus; +} + +export function createMeshControl(deps: MeshControlDeps): { path: string; handle: (ws: any) => void } { + const exportedScopes = new Set(deps.manifest.scopes.map((s) => s.token)); + const exportedRoutes = new Set(deps.manifest.routes.map((r) => `${r.method} ${r.pattern}`)); + + return { + path: MESH_CONTROL_PATH, + handle(ws: any) { + let authed = false; + ws.on('message', async (data: unknown) => { + let frame: Frame; + try { frame = decode(String(data)); } catch { return; } + + if (!authed) { + if (frame.type === 'hello' && safeEqual(frame.secret, deps.secret)) { + authed = true; + ws.send(encode({ type: 'manifest', scopes: deps.manifest.scopes, routes: deps.manifest.routes })); + deps.bus?.emit('mesh:connect', { name: 'teapot' }); + } else { + ws.close(1008); + } + return; + } + + if (frame.type !== 'rpc-req') return; + const { id, kind, name, ctx } = frame; + try { + let result: unknown; + if (kind === 'scope') { + if (!exportedScopes.has(name)) { const e: any = new Error(`not exported: ${name}`); e.status = 403; throw e; } + result = await deps.resolveScope(name, ctx); + } else { + if (![...exportedRoutes].some((k) => k.endsWith(` ${name}`))) { const e: any = new Error(`not exported: ${name}`); e.status = 403; throw e; } + result = await deps.resolveRoute(name, ctx); + } + ws.send(encode({ type: 'rpc-res', id, ok: true, result })); + } catch (err) { + const status = isHttpError(err) ? err.status : (err as any)?.status ?? 500; + deps.bus?.emit('mesh:rpc:error', { name, error: err }); + ws.send(encode({ type: 'rpc-res', id, ok: false, error: { message: (err as Error).message, status } })); + } + }); + ws.on('close', () => deps.bus?.emit('mesh:disconnect', { name: 'teapot' })); + }, + }; +} diff --git a/test/mesh/teapot.test.ts b/test/mesh/teapot.test.ts new file mode 100644 index 0000000..3ed2746 --- /dev/null +++ b/test/mesh/teapot.test.ts @@ -0,0 +1,84 @@ +import { describe, it, expect, vi } from 'vitest'; +import { EventEmitter } from 'events'; +import { buildManifest, createMeshControl } from '../../src/mesh/teapot'; +import { encode, decode } from '../../src/mesh/protocol'; +import { Unauthorized } from '../../src/signals'; + +const fakeWs = () => { + const ws: any = new EventEmitter(); + ws.sent = []; + ws.send = (s: string) => ws.sent.push(decode(s)); + ws.close = vi.fn(); + return ws; +}; + +describe('buildManifest', () => { + it('maps providers to app scope and steps to request scope', () => { + const m = buildManifest({ providers: ['config'], steps: ['auth'], routes: [{ method: 'GET', pattern: '/u/:id' }] }); + expect(m.scopes).toContainEqual({ token: 'config', scope: 'app' }); + expect(m.scopes).toContainEqual({ token: 'auth', scope: 'request' }); + expect(m.routes).toEqual([{ method: 'GET', pattern: '/u/:id' }]); + }); +}); + +describe('createMeshControl', () => { + const manifest = buildManifest({ providers: ['config'], steps: ['auth'], routes: [{ method: 'GET', pattern: '/u/:id' }] }); + const make = (over: Partial[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', () => { + expect(make().path).toBe('/__mesh__/control'); + }); + + it('rejects a bad secret and closes', () => { + const ws = fakeWs(); make().handle(ws); + ws.emit('message', encode({ type: 'hello', secret: 'wrong' })); + expect(ws.close).toHaveBeenCalledWith(1008); + expect(ws.sent).toEqual([]); + }); + + it('answers a good hello with the manifest', () => { + const ws = fakeWs(); make().handle(ws); + ws.emit('message', encode({ type: 'hello', secret: 'good' })); + expect(ws.sent[0]).toMatchObject({ type: 'manifest', scopes: manifest.scopes }); + }); + + it('does NOT process rpc before handshake', async () => { + const ws = fakeWs(); make().handle(ws); + ws.emit('message', encode({ type: 'rpc-req', id: '1', kind: 'scope', name: 'config', ctx: {} as any })); + await new Promise((r) => setTimeout(r, 5)); + expect(ws.sent).toEqual([]); + }); + + it('resolves an exported scope after handshake', async () => { + const ws = fakeWs(); make().handle(ws); + ws.emit('message', encode({ type: 'hello', secret: 'good' })); + ws.emit('message', encode({ type: 'rpc-req', id: '7', kind: 'scope', name: 'config', ctx: {} as any })); + await new Promise((r) => setTimeout(r, 5)); + expect(ws.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 () => { + const ws = fakeWs(); make().handle(ws); + ws.emit('message', encode({ type: 'hello', secret: 'good' })); + ws.emit('message', encode({ type: 'rpc-req', id: '8', kind: 'scope', name: 'secretsvc', ctx: {} as any })); + await new Promise((r) => setTimeout(r, 5)); + const res: any = ws.sent.find((f: any) => f.type === 'rpc-res'); + expect(res.ok).toBe(false); + expect(res.error.status).toBe(403); + }); + + it('propagates a thrown HttpError status in the error frame', async () => { + const ws = fakeWs(); + make({ resolveScope: async () => { throw new Unauthorized('nope'); } }).handle(ws); + ws.emit('message', encode({ type: 'hello', secret: 'good' })); + ws.emit('message', encode({ type: 'rpc-req', id: '9', kind: 'scope', name: 'config', ctx: {} as any })); + await new Promise((r) => setTimeout(r, 5)); + const res: any = ws.sent.find((f: any) => f.type === 'rpc-res'); + expect(res).toMatchObject({ id: '9', ok: false, error: { message: 'nope', status: 401 } }); + }); +}); From 1174d14754096b1045253e6fb405fce83a1bfb1a Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 27 Jun 2026 20:30:08 -0500 Subject: [PATCH 017/139] feat(mesh): teacup WS link client with id-correlated RPC Signed-off-by: Diego Resendez --- src/mesh/link.ts | 99 ++++++++++++++++++++++++++++++++++++++++++ test/mesh/link.test.ts | 78 +++++++++++++++++++++++++++++++++ 2 files changed, 177 insertions(+) create mode 100644 src/mesh/link.ts create mode 100644 test/mesh/link.test.ts diff --git a/src/mesh/link.ts b/src/mesh/link.ts new file mode 100644 index 0000000..10105d6 --- /dev/null +++ b/src/mesh/link.ts @@ -0,0 +1,99 @@ +import type { Bus } from '../bus'; +import { HttpError } from '../signals'; +import { encode, decode, type Manifest, type RequestEnvelope, type Frame } from './protocol'; + +let connSeq = 0; // module-level: deterministic unique connection-id prefix (no Date.now/Math.random) + +export interface Link { + manifest: Manifest; + rpc(kind: 'scope' | 'route', name: string, ctx: RequestEnvelope): Promise; + close(): void; +} + +function loadWs(): any { + return require('ws'); // lazy/optional, like streams; the ws CJS export is the WebSocket class +} + +export function connectLink(args: { + url: string; + secret: string; + timeoutMs?: number; + bus?: Bus; +}): Promise { + const timeoutMs = args.timeoutMs ?? 30_000; + const WS = loadWs(); + const ws = new WS(args.url); + const pending = new Map< + string, + { resolve: (v: unknown) => void; reject: (e: unknown) => void; timer: ReturnType } + >(); + let counter = 0; + const connId = `c${connSeq++}`; + let manifest: Manifest | undefined; + + return new Promise((resolve, reject) => { + const connectTimer = setTimeout(() => { + ws.close(); + reject(new Error(`mesh connect timeout: ${args.url}`)); + }, timeoutMs); + + ws.on('open', () => ws.send(encode({ type: 'hello', secret: args.secret }))); + ws.on('error', (e: unknown) => reject(e)); + ws.on('close', () => { + clearTimeout(connectTimer); + args.bus?.emit('mesh:disconnect', { name: args.url }); + for (const [, p] of pending) { + clearTimeout(p.timer); + p.reject(new Error('mesh link closed')); + } + pending.clear(); + if (!manifest) reject(new Error(`mesh handshake failed: ${args.url}`)); + }); + + ws.on('message', (data: unknown) => { + let frame: Frame; + try { + frame = decode(String(data)); + } catch { + return; + } + + if (frame.type === 'manifest') { + manifest = { scopes: frame.scopes, routes: frame.routes }; + clearTimeout(connectTimer); + args.bus?.emit('mesh:connect', { name: args.url }); + resolve({ + manifest, + rpc(kind, name, ctx) { + const id = `${connId}:${counter++}`; + return new Promise((res, rej) => { + const timer = setTimeout(() => { + pending.delete(id); + rej(new Error(`mesh rpc timeout: ${name}`)); + }, timeoutMs); + pending.set(id, { resolve: res, reject: rej, timer }); + ws.send(encode({ type: 'rpc-req', id, kind, name, ctx })); + }); + }, + close() { + ws.close(); + }, + }); + return; + } + + if (frame.type === 'rpc-res') { + const p = pending.get(frame.id); + if (!p) return; + pending.delete(frame.id); + clearTimeout(p.timer); + if (frame.ok) { + p.resolve(frame.result); + } else { + args.bus?.emit('mesh:rpc:error', { name: frame.id, error: frame.error }); + p.reject(new HttpError(frame.error.status ?? 500, frame.error.message)); + } + } + }); + }); +} diff --git a/test/mesh/link.test.ts b/test/mesh/link.test.ts new file mode 100644 index 0000000..69bdd18 --- /dev/null +++ b/test/mesh/link.test.ts @@ -0,0 +1,78 @@ +import { describe, it, expect } from 'vitest'; +import { WebSocketServer } from 'ws'; +import { connectLink } from '../../src/mesh/link'; +import { encode, decode } from '../../src/mesh/protocol'; + +const env = { method: 'GET', params: {}, query: {}, body: undefined, headers: {} }; + +// teapot that validates secret 'good', returns a manifest, answers scope rpc (boom -> error) +function startTeapot(secret = 'good') { + const wss = new WebSocketServer({ port: 0 }); + wss.on('connection', (ws) => { + let authed = false; + ws.on('message', (d) => { + const f = decode(d.toString()); + if (!authed) { + if (f.type === 'hello' && f.secret === secret) { authed = true; ws.send(encode({ type: 'manifest', scopes: [{ token: 'auth', scope: 'request' }], routes: [] })); } + else ws.close(1008); + return; + } + if (f.type === 'rpc-req') { + if (f.name === 'boom') ws.send(encode({ type: 'rpc-res', id: f.id, ok: false, error: { message: 'denied', status: 403 } })); + else ws.send(encode({ type: 'rpc-res', id: f.id, ok: true, result: { got: f.name } })); + } + }); + }); + const port = (wss.address() as any).port; + return { url: `ws://127.0.0.1:${port}/__mesh__/control`, close: () => wss.close() }; +} + +// teapot that completes the handshake but NEVER answers rpc-req (for timeout) +function startSilentTeapot(secret = 'good') { + const wss = new WebSocketServer({ port: 0 }); + wss.on('connection', (ws) => { + ws.on('message', (d) => { + const f = decode(d.toString()); + if (f.type === 'hello' && f.secret === secret) ws.send(encode({ type: 'manifest', scopes: [], routes: [] })); + // ignore rpc-req entirely + }); + }); + const port = (wss.address() as any).port; + return { url: `ws://127.0.0.1:${port}/__mesh__/control`, close: () => wss.close() }; +} + +describe('connectLink', () => { + it('handshakes and exposes the manifest', async () => { + const t = startTeapot(); + const link = await connectLink({ url: t.url, secret: 'good' }); + expect(link.manifest.scopes).toEqual([{ token: 'auth', scope: 'request' }]); + link.close(); t.close(); + }); + + it('rpc resolves a result by id', async () => { + const t = startTeapot(); + const link = await connectLink({ url: t.url, secret: 'good' }); + expect(await link.rpc('scope', 'auth', env)).toEqual({ got: 'auth' }); + link.close(); t.close(); + }); + + it('rpc rejects with an HttpError carrying the remote status', async () => { + const t = startTeapot(); + const link = await connectLink({ url: t.url, secret: 'good' }); + await expect(link.rpc('scope', 'boom', env)).rejects.toMatchObject({ status: 403, message: 'denied' }); + link.close(); t.close(); + }); + + it('rejects connect on bad secret', async () => { + const t = startTeapot(); + await expect(connectLink({ url: t.url, secret: 'wrong', timeoutMs: 500 })).rejects.toThrow(); + t.close(); + }); + + it('times out an rpc when the teapot never answers', async () => { + const t = startSilentTeapot(); + const link = await connectLink({ url: t.url, secret: 'good', timeoutMs: 150 }); + await expect(link.rpc('scope', 'whatever', env)).rejects.toThrow(/timeout/i); + link.close(); t.close(); + }); +}); From f151da4bd70cfac9c020777bab4358f185c76b87 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 27 Jun 2026 20:31:48 -0500 Subject: [PATCH 018/139] feat(mesh): route reserved control path to meshControl on upgrade Signed-off-by: Diego Resendez --- src/http.ts | 15 +++++++++++---- test/mesh/control-upgrade.test.ts | 18 ++++++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) create mode 100644 test/mesh/control-upgrade.test.ts diff --git a/src/http.ts b/src/http.ts index a9253d6..86b05b4 100644 --- a/src/http.ts +++ b/src/http.ts @@ -26,6 +26,8 @@ export interface WsOpenCtx { } export interface WsRouteDef { pattern: string; open: (ctx: WsOpenCtx) => Promise> } +export interface MeshControl { path: string; handle(ws: any, req: http.IncomingMessage): void } + const PING_MS = 15_000; export function matchPattern(pattern: string, path: string): Record | undefined { @@ -106,12 +108,17 @@ function loadWss(): any | null { try { return require('ws').WebSocketServer; } catch { return null; } } -function attachWs(server: http.Server, wsRoutes: WsRouteDef[], bus?: Bus): void { - if (wsRoutes.length === 0) return; +function attachWs(server: http.Server, wsRoutes: WsRouteDef[], bus?: Bus, meshControl?: MeshControl): void { + if (wsRoutes.length === 0 && !meshControl) return; const WSS = loadWss(); const wss = WSS ? new WSS({ noServer: true }) : null; server.on('upgrade', (req, socket, head) => { const path = (req.url ?? '/').split('?')[0]; + if (meshControl && path === meshControl.path) { + if (!wss) { socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n'); socket.destroy(); return; } + wss.handleUpgrade(req, socket, head, (ws: any) => meshControl.handle(ws, req)); + return; + } const route = wsRoutes.map((r) => ({ r, params: matchPattern(r.pattern, path) })).find((x) => x.params); if (!route) { socket.destroy(); return; } if (!wss) { socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n'); socket.destroy(); return; } @@ -147,7 +154,7 @@ function attachWs(server: http.Server, wsRoutes: WsRouteDef[], bus?: Bus): void }); } -export function createHttpServer(routes: RouteDef[], wsRoutes: WsRouteDef[] = [], bus?: Bus): http.Server { +export function createHttpServer(routes: RouteDef[], wsRoutes: WsRouteDef[] = [], bus?: Bus, meshControl?: MeshControl): http.Server { const server = http.createServer(async (req, res) => { const url = req.url ?? '/'; const path = url.split('?')[0]; @@ -193,6 +200,6 @@ export function createHttpServer(routes: RouteDef[], wsRoutes: WsRouteDef[] = [] res.writeHead(r.status, r.headers); res.end(r.body); }); - attachWs(server, wsRoutes, bus); + attachWs(server, wsRoutes, bus, meshControl); return server; } diff --git a/test/mesh/control-upgrade.test.ts b/test/mesh/control-upgrade.test.ts new file mode 100644 index 0000000..cd50118 --- /dev/null +++ b/test/mesh/control-upgrade.test.ts @@ -0,0 +1,18 @@ +import { describe, it, expect } from 'vitest'; +import WebSocket from 'ws'; +import { createHttpServer, type MeshControl } from '../../src/http'; + +describe('mesh control upgrade', () => { + it('routes the reserved path to meshControl.handle and leaves wsRoutes intact', async () => { + let handled = false; + const meshControl: MeshControl = { path: '/__mesh__/control', handle: (ws) => { handled = true; ws.send('hi'); } }; + const server = createHttpServer([], [], undefined, meshControl); + await new Promise((r) => server.listen(0, r)); + const port = (server.address() as any).port; + const client = new WebSocket(`ws://127.0.0.1:${port}/__mesh__/control`); + const msg = await new Promise((res) => { client.on('message', (d) => res(d.toString())); }); + expect(msg).toBe('hi'); + expect(handled).toBe(true); + client.close(); server.close(); + }); +}); From a1e8f73e6421e55852848753ee08554e786edaf9 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 27 Jun 2026 20:33:15 -0500 Subject: [PATCH 019/139] feat(mesh): teacup remote node and proxy-route builder Signed-off-by: Diego Resendez --- src/mesh/teacup.ts | 35 +++++++++++++++++++++++++++++++++++ test/mesh/teacup.test.ts | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 src/mesh/teacup.ts create mode 100644 test/mesh/teacup.test.ts diff --git a/src/mesh/teacup.ts b/src/mesh/teacup.ts new file mode 100644 index 0000000..39fe36c --- /dev/null +++ b/src/mesh/teacup.ts @@ -0,0 +1,35 @@ +import type { Link } from './link'; +import type { RequestEnvelope } from './protocol'; +import type { ResponseShape } from '../pipeline'; + +export interface RemoteScopeNode { name: string; run: (ctx: any) => Promise> } +export interface RemoteRoute { method: string; pattern: string; handler: (req: RequestEnvelope) => Promise } + +export function envelopeFrom(ctx: any): RequestEnvelope { + return { + method: ctx?.req?.method ?? ctx?.method ?? 'GET', + params: ctx?.params ?? {}, + query: ctx?.query ?? {}, + body: ctx?.body, + headers: ctx?.headers ?? {}, + }; +} + +export function buildRemote(link: Link, origin: string): { + providers: RemoteScopeNode[]; steps: RemoteScopeNode[]; routes: RemoteRoute[]; +} { + const providers: RemoteScopeNode[] = []; + const steps: RemoteScopeNode[] = []; + for (const s of link.manifest.scopes) { + const node: RemoteScopeNode = { + name: s.token, + run: async (ctx: any) => ({ [s.token]: await link.rpc('scope', s.token, envelopeFrom(ctx)) }), + }; + (s.scope === 'app' ? providers : steps).push(node); + } + const routes: RemoteRoute[] = link.manifest.routes.map((r) => ({ + method: r.method, pattern: r.pattern, + handler: async (req: RequestEnvelope) => (await link.rpc('route', r.pattern, req)) as ResponseShape, + })); + return { providers, steps, routes }; +} diff --git a/test/mesh/teacup.test.ts b/test/mesh/teacup.test.ts new file mode 100644 index 0000000..fa46063 --- /dev/null +++ b/test/mesh/teacup.test.ts @@ -0,0 +1,33 @@ +import { describe, it, expect } from 'vitest'; +import { buildRemote, envelopeFrom } from '../../src/mesh/teacup'; +import type { Link } from '../../src/mesh/link'; + +const fakeLink = (calls: any[]): Link => ({ + manifest: { scopes: [{ token: 'config', scope: 'app' }, { token: 'auth', scope: 'request' }], routes: [{ method: 'GET', pattern: '/u/:id' }] }, + rpc: async (kind, name, ctx) => { calls.push({ kind, name, ctx }); return name === 'config' ? { url: 'db://x' } : { id: 'u1' }; }, + close() {}, +}); + +describe('teacup buildRemote', () => { + it('makes a provider node (app) and a step node (request) with RPC runners returning merge objects', async () => { + const calls: any[] = []; + const { providers, steps } = buildRemote(fakeLink(calls), 'ws://t'); + expect(providers.map((p) => p.name)).toEqual(['config']); + expect(steps.map((s) => s.name)).toEqual(['auth']); + expect(await providers[0].run({})).toEqual({ config: { url: 'db://x' } }); + const ctx = { req: {}, params: { id: '9' }, query: {}, body: undefined, headers: { x: '1' } }; + expect(await steps[0].run(ctx)).toEqual({ auth: { id: 'u1' } }); + expect(calls.find((c) => c.name === 'auth').ctx).toMatchObject({ params: { id: '9' }, headers: { x: '1' } }); + }); + + it('makes a proxy route entry with method+pattern', async () => { + const calls: any[] = []; + const { routes } = buildRemote(fakeLink(calls), 'ws://t'); + expect(routes[0]).toMatchObject({ method: 'GET', pattern: '/u/:id' }); + }); + + it('envelopeFrom extracts only serializable request fields', () => { + const env = envelopeFrom({ method: 'POST', params: { a: '1' }, query: { q: 'x' }, body: { n: 1 }, headers: { h: 'v' }, db: { find() {} } } as any); + expect(env).toEqual({ method: 'POST', params: { a: '1' }, query: { q: 'x' }, body: { n: 1 }, headers: { h: 'v' } }); + }); +}); From e8a63e8d41bdb64884a22104666282c886eecac3 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 27 Jun 2026 20:36:56 -0500 Subject: [PATCH 020/139] feat(mesh): wire remote scopes and proxy routes through the graph Signed-off-by: Diego Resendez --- src/app.ts | 145 +++++++++++++++++++++++++++------- src/index.ts | 5 ++ test/mesh/integration.test.ts | 58 ++++++++++++++ 3 files changed, 178 insertions(+), 30 deletions(-) create mode 100644 test/mesh/integration.test.ts diff --git a/src/app.ts b/src/app.ts index 69eba59..a0e089e 100644 --- a/src/app.ts +++ b/src/app.ts @@ -11,6 +11,11 @@ import { Ctor, HttpMethod, Transport, getModuleMeta, getProviderMeta, getStepMeta, getRoutes, getTransformer, joinPath, } from './metadata'; import { getArgs, getHandlerNeeds, resolveArgs } from './params'; +import { connectLink } from './mesh/link'; +import { buildRemote } from './mesh/teacup'; +import { buildManifest, createMeshControl } from './mesh/teapot'; +import type { MeshControl } from './http'; +import type { RequestEnvelope, RouteEntry } from './mesh/protocol'; export interface InspectLine { name: string; kind: 'provider' | 'step' | 'handler'; origin: string } export interface App { @@ -32,7 +37,13 @@ interface RoutePlan { transformer: typeof JsonTransformer; } -export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[] }): App { +export interface MeshConfig { + secret?: string; + teapots?: Array<{ url: string; secret: string }>; + timeoutMs?: number; +} + +export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig }): App { const bus = new Bus(); const container = new Container(); const extraSteps: ScopeNode[] = []; @@ -48,6 +59,9 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[] }): App { }; const providerMeta = new Map(); const routePlans: RoutePlan[] = []; + const exportedProviders: string[] = []; + const exportedSteps: string[] = []; + const exportedRoutes: RouteEntry[] = []; for (const mod of opts.modules) { const m = getModuleMeta(mod); @@ -58,12 +72,14 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[] }): App { const meta = getProviderMeta(P)!; providerNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin }); providerMeta.set(meta.provides, { optional: meta.optional }); + if (meta.export) exportedProviders.push(meta.provides); const inst: any = new P(); setRunner(meta.provides, (ctx) => inst.provide(ctx)); } for (const S of m.steps ?? []) { const meta = getStepMeta(S)!; stepNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin }); + if (meta.export) exportedSteps.push(meta.provides); const inst: any = new S(); setRunner(meta.provides, (ctx) => inst.run(ctx)); } @@ -71,8 +87,13 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[] }): App { for (const route of getRoutes(C)) { const inst: any = new C(); const argSpecs = getArgs(C, route.handlerName); + const pattern = joinPath(m.mountpoint, route.path); + if (route.export) { + if (route.transport !== 'buffer') throw new Error(`cannot export streaming route ${pattern}`); + exportedRoutes.push({ method: route.method, pattern }); + } routePlans.push({ - pattern: joinPath(m.mountpoint, route.path), + pattern, method: route.method, transport: route.transport, origin, @@ -97,26 +118,34 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[] }): App { // For each route, resolve which providers/steps feed it via topo order. // MVP: every route depends on every declared step + provider in the app graph. - const seedKeys = ['req', 'params']; - const ordered = topoSort([...providerNodes, ...stepNodes], seedKeys); - const orderedProviders = ordered.filter((n) => providerNodes.includes(n)); - const orderedSteps = ordered.filter((n) => stepNodes.includes(n)); - for (const plan of routePlans) { plan.providers = orderedProviders; plan.steps = orderedSteps; } + // For mesh apps, finalize is DEFERRED to listen() so remote scopes can join the graph first. + let orderedProviders: GraphNode[] = []; + let orderedSteps: GraphNode[] = []; + let booted = false; + const finalizeGraph = (): void => { + const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params']); + orderedProviders = ordered.filter((n) => providerNodes.includes(n)); + orderedSteps = ordered.filter((n) => stepNodes.includes(n)); + for (const plan of routePlans) { plan.providers = orderedProviders; plan.steps = orderedSteps; } - const producedKeys = new Set([ - ...providerNodes.flatMap((n) => n.provides), - ...stepNodes.flatMap((n) => n.provides), - ]); - const allowed = new Set([...producedKeys, 'req', 'params', 'query', 'body', 'headers', 'inbound', 'abort']); - for (const plan of routePlans) { - for (const need of plan.needs) { - if (!allowed.has(need)) { - throw new Error(`handler '${plan.handlerName}' needs '${need}' but nothing provides it`); + const producedKeys = new Set([ + ...providerNodes.flatMap((n) => n.provides), + ...stepNodes.flatMap((n) => n.provides), + ]); + const allowed = new Set([...producedKeys, 'req', 'params', 'query', 'body', 'headers', 'inbound', 'abort']); + for (const plan of routePlans) { + for (const need of plan.needs) { + if (!allowed.has(need)) { + throw new Error(`handler '${plan.handlerName}' needs '${need}' but nothing (local or mesh) provides it`); + } } } - } + booted = true; + }; + if (!opts.mesh) finalizeGraph(); const inspect = (routePath: string): InspectLine[] => { + if (!booted) throw new Error('inspect() unavailable before listen() for mesh apps'); const plan = routePlans.find((p) => p.pattern === routePath); if (!plan) throw new Error(`no route: ${routePath}`); return [ @@ -140,6 +169,32 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[] }): App { }); const listen = async (port: number): Promise => { + // mesh teacup: connect remote teapots, splice their scopes/routes into the graph, then finalize + const remoteRoutes: RouteDef[] = []; + let meshControl: MeshControl | undefined; + if (opts.mesh && !booted) { + for (const t of opts.mesh.teapots ?? []) { + const link = await connectLink({ url: t.url, secret: t.secret, timeoutMs: opts.mesh.timeoutMs, bus }); + const { providers, steps, routes } = buildRemote(link, t.url); + for (const p of providers) { + providerNodes.push({ name: p.name, needs: [], provides: [p.name], origin: `mesh:${t.url}` }); + providerMeta.set(p.name, { optional: false }); + setRunner(p.name, p.run); + } + for (const s of steps) { + stepNodes.push({ name: s.name, needs: [], provides: [s.name], origin: `mesh:${t.url}` }); + setRunner(s.name, s.run); + } + for (const r of routes) { + remoteRoutes.push({ + method: r.method, pattern: r.pattern, transport: 'buffer', + handler: async (req) => r.handler(req as RequestEnvelope), + }); + } + } + finalizeGraph(); + } + // run app-scoped providers in order (fail-fast for required) for (const node of orderedProviders) { bus.emit('boot:provider:start', { name: node.name, scope: node.origin }); @@ -159,18 +214,48 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[] }): App { } } - const httpRoutes: RouteDef[] = routePlans - .filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate - .map((plan) => ({ - method: plan.method, pattern: plan.pattern, transport: plan.transport, - handler: async (req) => { - const provided = await providedSeed(plan); - return runPipeline({ - steps: planSteps(plan), handler: plan.run, transformer: plan.transformer, bus, - seed: { ...provided, req, params: req.params, query: req.query, body: req.body, headers: req.headers }, - }); - }, - })); + // mesh teapot: expose declared exports over the control channel (lazy resolvers read live state) + const hasExports = exportedProviders.length || exportedSteps.length || exportedRoutes.length; + if (hasExports && !opts.mesh?.secret) { + throw new Error('mesh: exports declared (export: true) but no mesh.secret configured to gate the control channel'); + } + if (opts.mesh?.secret && hasExports) { + const manifest = buildManifest({ providers: exportedProviders, steps: exportedSteps, routes: exportedRoutes }); + const resolveScope = async (name: string, env: RequestEnvelope): Promise => { + let ctx: any = { req: env, params: env.params, query: env.query, body: env.body, headers: env.headers }; + for (const p of orderedProviders) if (container.has(p.name)) Object.assign(ctx, await container.resolve(p.name)); + for (const s of orderedSteps) { const fn = runners.get(s.name)!; ctx = { ...ctx, ...(await fn(ctx)) }; } + return ctx[name]; + }; + const resolveRoute = async (name: string, env: RequestEnvelope) => { + const plan = routePlans.find((p) => p.pattern === name); + if (!plan) { const e: any = new Error(`no route ${name}`); e.status = 404; throw e; } + const provided = await providedSeed(plan); + const result = await runPipeline({ + steps: planSteps(plan), handler: plan.run, transformer: plan.transformer, bus, + seed: { ...provided, req: env, params: env.params, query: env.query, body: env.body, headers: env.headers }, + }); + if ('stream' in result) { const e: any = new Error('cannot proxy a streaming route'); e.status = 500; throw e; } + return result; + }; + meshControl = createMeshControl({ secret: opts.mesh.secret, manifest, resolveScope, resolveRoute, bus }); + } + + const httpRoutes: RouteDef[] = [ + ...routePlans + .filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate + .map((plan): RouteDef => ({ + method: plan.method, pattern: plan.pattern, transport: plan.transport, + handler: async (req) => { + const provided = await providedSeed(plan); + return runPipeline({ + steps: planSteps(plan), handler: plan.run, transformer: plan.transformer, bus, + seed: { ...provided, req, params: req.params, query: req.query, body: req.body, headers: req.headers }, + }); + }, + })), + ...remoteRoutes, + ]; const wsRoutes: WsRouteDef[] = routePlans .filter((plan) => plan.transport === 'ws' || plan.transport === 'negotiate') @@ -187,7 +272,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[] }): App { }, })); - const server = createHttpServer(httpRoutes, wsRoutes, bus); + const server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl); await new Promise((resolve) => server.listen(port, resolve)); return server; }; diff --git a/src/index.ts b/src/index.ts index 03edddc..fec76a1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -19,3 +19,8 @@ export type { Transport, HttpMethod } from './metadata'; export { inbound, abort } from './params'; export { sseEncoder, ndjsonEncoder } from './encoders'; export type { StreamEncoder } from './encoders'; +export type { MeshConfig } from './app'; +export { connectLink } from './mesh/link'; +export { buildRemote, envelopeFrom } from './mesh/teacup'; +export { buildManifest, createMeshControl, MESH_CONTROL_PATH } from './mesh/teapot'; +export type { Manifest, RequestEnvelope, Frame } from './mesh/protocol'; diff --git a/test/mesh/integration.test.ts b/test/mesh/integration.test.ts new file mode 100644 index 0000000..8f6ee37 --- /dev/null +++ b/test/mesh/integration.test.ts @@ -0,0 +1,58 @@ +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(ctx: any) { return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; } } + +@Route('/remote') +class RemoteCtl { @Get('/ping', { export: true }) ping() { return { pong: true }; } } + +@Module({ mountpoint: '/api', providers: [Config], steps: [Auth], controllers: [RemoteCtl] }) +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 {} + +describe('mesh skeleton integration', () => { + it('teacup resolves remote app-scope + request-scope into a local handler', async () => { + const teapot = createApp({ modules: [TeapotModule], mesh: { secret: SECRET } }); + const tServer = await teapot.listen(0); + const tPort = (tServer.address() as any).port; + const url = `ws://127.0.0.1:${tPort}/__mesh__/control`; + + const teacup = createApp({ modules: [TeacupModule], mesh: { teapots: [{ url, secret: SECRET }] } }); + const cServer = await teacup.listen(0); + const cPort = (cServer.address() as any).port; + + const res = await fetch(`http://127.0.0.1:${cPort}/api/local/who`, { headers: { 'x-token': 'abc' } }); + expect(await res.json()).toEqual({ config: { region: 'mx' }, auth: { token: 'abc' } }); + + tServer.close(); cServer.close(); + }); + + it('teapot still serves its own local route (regression)', async () => { + const app = createApp({ modules: [TeapotModule], mesh: { secret: SECRET } }); + const s = await app.listen(0); const p = (s.address() as any).port; + const res = await fetch(`http://127.0.0.1:${p}/api/remote/ping`); + expect(await res.json()).toEqual({ pong: true }); + s.close(); + }); + + it('rejects a bad secret (teacup boot fails)', async () => { + const teapot = createApp({ modules: [TeapotModule], mesh: { secret: SECRET } }); + const tServer = await teapot.listen(0); const tPort = (tServer.address() as any).port; + const teacup = createApp({ modules: [TeacupModule], mesh: { teapots: [{ url: `ws://127.0.0.1:${tPort}/__mesh__/control`, secret: 'WRONG' }], timeoutMs: 800 } }); + await expect(teacup.listen(0)).rejects.toThrow(); + tServer.close(); + }); +}); From e702de187d37851a2efcfac9a98ce7d5a86a68ec Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 27 Jun 2026 20:42:44 -0500 Subject: [PATCH 021/139] fix(mesh): close teacup links on shutdown/boot-failure; match proxy routes by method Signed-off-by: Diego Resendez --- src/app.ts | 48 ++++++++++++++++++++++++++++-------------------- 1 file changed, 28 insertions(+), 20 deletions(-) diff --git a/src/app.ts b/src/app.ts index a0e089e..7374ac5 100644 --- a/src/app.ts +++ b/src/app.ts @@ -11,7 +11,7 @@ import { Ctor, HttpMethod, Transport, getModuleMeta, getProviderMeta, getStepMeta, getRoutes, getTransformer, joinPath, } from './metadata'; import { getArgs, getHandlerNeeds, resolveArgs } from './params'; -import { connectLink } from './mesh/link'; +import { connectLink, type Link } from './mesh/link'; import { buildRemote } from './mesh/teacup'; import { buildManifest, createMeshControl } from './mesh/teapot'; import type { MeshControl } from './http'; @@ -171,28 +171,35 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me const listen = async (port: number): Promise => { // mesh teacup: connect remote teapots, splice their scopes/routes into the graph, then finalize const remoteRoutes: RouteDef[] = []; + const meshLinks: Link[] = []; let meshControl: MeshControl | undefined; if (opts.mesh && !booted) { - for (const t of opts.mesh.teapots ?? []) { - const link = await connectLink({ url: t.url, secret: t.secret, timeoutMs: opts.mesh.timeoutMs, bus }); - const { providers, steps, routes } = buildRemote(link, t.url); - for (const p of providers) { - providerNodes.push({ name: p.name, needs: [], provides: [p.name], origin: `mesh:${t.url}` }); - providerMeta.set(p.name, { optional: false }); - setRunner(p.name, p.run); - } - for (const s of steps) { - stepNodes.push({ name: s.name, needs: [], provides: [s.name], origin: `mesh:${t.url}` }); - setRunner(s.name, s.run); - } - for (const r of routes) { - remoteRoutes.push({ - method: r.method, pattern: r.pattern, transport: 'buffer', - handler: async (req) => r.handler(req as RequestEnvelope), - }); + try { + for (const t of opts.mesh.teapots ?? []) { + const link = await connectLink({ url: t.url, secret: t.secret, timeoutMs: opts.mesh.timeoutMs, bus }); + meshLinks.push(link); + const { providers, steps, routes } = buildRemote(link, t.url); + for (const p of providers) { + providerNodes.push({ name: p.name, needs: [], provides: [p.name], origin: `mesh:${t.url}` }); + providerMeta.set(p.name, { optional: false }); + setRunner(p.name, p.run); + } + for (const s of steps) { + stepNodes.push({ name: s.name, needs: [], provides: [s.name], origin: `mesh:${t.url}` }); + setRunner(s.name, s.run); + } + for (const r of routes) { + remoteRoutes.push({ + method: r.method, pattern: r.pattern, transport: 'buffer', + handler: async (req) => r.handler(req as RequestEnvelope), + }); + } } + finalizeGraph(); + } catch (err) { + for (const l of meshLinks) { try { l.close(); } catch { /* */ } } + throw err; } - finalizeGraph(); } // run app-scoped providers in order (fail-fast for required) @@ -228,7 +235,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me return ctx[name]; }; const resolveRoute = async (name: string, env: RequestEnvelope) => { - const plan = routePlans.find((p) => p.pattern === name); + const plan = routePlans.find((p) => p.pattern === name && p.method === env.method); if (!plan) { const e: any = new Error(`no route ${name}`); e.status = 404; throw e; } const provided = await providedSeed(plan); const result = await runPipeline({ @@ -273,6 +280,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me })); const server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl); + server.on('close', () => { for (const l of meshLinks) { try { l.close(); } catch { /* */ } } }); await new Promise((resolve) => server.listen(port, resolve)); return server; }; From 44e77d4bb42db46ec18261513b00c64cfea13f08 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 27 Jun 2026 20:45:58 -0500 Subject: [PATCH 022/139] feat(mesh): two-node teapot/teacup example Signed-off-by: Diego Resendez --- example/server.ts | 54 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) diff --git a/example/server.ts b/example/server.ts index 09c4b3b..7ab6c97 100644 --- a/example/server.ts +++ b/example/server.ts @@ -1,4 +1,4 @@ -import { createApp, Provider, Step, Route, Get, Module, Transformer, JsonTransformer, Unauthorized, Plugin, needs, param, Sse, Ws, inbound, channel } from '../src/index'; +import { createApp, Provider, Step, Route, Get, Module, Transformer, JsonTransformer, Unauthorized, Plugin, needs, param, Sse, Ws, inbound, channel, MESH_CONTROL_PATH } from '../src/index'; interface User { id: string; name: string } @@ -70,3 +70,55 @@ if (require.main === module) { app.listen(3000).then(() => console.log('green-tea on http://localhost:3000')); streamApp.listen(3001).then(() => console.log('green-tea streams on http://localhost:3001')); } + +// ── Mesh Demo (teapot / teacup) ─────────────────────────────────────────── + +@Provider({ provides: 'config', export: true }) +class ConfigProvider { + provide() { + return { config: { env: 'demo' } }; + } +} + +@Step({ provides: 'auth', needs: [], export: true }) +class AuthStep { + run(ctx: { headers?: Record }) { + const tok = ctx.headers?.['x-token']; + return { auth: Array.isArray(tok) ? tok[0] ?? 'anonymous' : tok ?? 'anonymous' }; + } +} + +@Route('/svc') +class PingController { + @Get('/ping', { export: true }) + ping(@needs('config') config: { env: string }, @needs('auth') auth: string) { + return { pong: true, config, auth }; + } +} + +@Module({ mountpoint: '/mesh', providers: [ConfigProvider], steps: [AuthStep], controllers: [PingController] }) +class TeapotModule {} + +export const teapotApp = createApp({ modules: [TeapotModule], mesh: { secret: 'demo-secret' } }); + +@Route('/remote') +class TeacupController { + @Get('/status') + status(@needs('config') config: { env: string }, @needs('auth') auth: string) { + return { via: 'teacup', config, auth }; + } +} + +@Module({ mountpoint: '/', controllers: [TeacupController] }) +class TeacupModule {} + +if (require.main === module) { + teapotApp.listen(3002).then(() => { + console.log('teapot on http://localhost:3002'); + const teacupApp = createApp({ + modules: [TeacupModule], + mesh: { teapots: [{ url: `ws://127.0.0.1:3002${MESH_CONTROL_PATH}`, secret: 'demo-secret' }] }, + }); + teacupApp.listen(3003).then(() => console.log('teacup on http://localhost:3003')); + }); +} From 8b43a15609ffb14ba893765b5ab24b53816cf8ec Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 27 Jun 2026 21:30:33 -0500 Subject: [PATCH 023/139] docs: architecture mental map, quickstart guide, README links Signed-off-by: Diego Resendez --- README.md | 12 ++- docs/architecture.md | 115 ++++++++++++++++++++++ docs/quickstart.md | 227 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 351 insertions(+), 3 deletions(-) create mode 100644 docs/architecture.md create mode 100644 docs/quickstart.md diff --git a/README.md b/README.md index 2f3213d..48551bf 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,12 @@ > A declarative, type-safe HTTP framework for Node. The request pipeline is an explicit **dependency graph**, not a mutable middleware chain. -`@green-tea/core` — **alpha**. Zero runtime dependencies beyond `reflect-metadata`. +`@green-tea/core` — **alpha**. Zero runtime dependencies beyond `reflect-metadata` (`ws` is an optional peer dep, only for WebSocket/mesh on Node). + +## Documentation + +- **[Quickstart](./docs/quickstart.md)** — install + concrete examples (routes/DI, `flow`, SSE, WebSocket, mesh, plugins). +- **[Architecture](./docs/architecture.md)** — the mental map (layers, request lifecycle, mesh) as diagrams. ## Why @@ -92,8 +97,9 @@ npm run build # emit dist/ ## Roadmap -- **streams** — native WebSocket/SSE + reactive streams (steps that open an observed channel). -- **mesh** — `teapot`/`teacup`: distributed scopes over a persistent channel with auto-registration. Model: a BEAM/OTP-style cluster, *not* microservices. The core's `resolve()` is already async + transport-agnostic to allow this without a rewrite. +- ✅ **streams** — SSE / ndjson / WebSocket duplex over a multicast `AsyncIterable` channel. Return an `AsyncIterable` and the transport streams it (backpressure + cleanup). See the [quickstart](./docs/quickstart.md#3-streaming--sse). +- ✅ **mesh (walking skeleton)** — `teapot`/`teacup`: a consumer resolves a scope/step or proxies a route living on another node, over a secret-gated WS control channel, via one id-correlated RPC. Remote tokens become synthetic graph nodes. Model: a BEAM/OTP-style cluster, *not* microservices. See the [quickstart](./docs/quickstart.md#5-mesh--distributed-dependency-injection). +- **mesh sub-specs (next)** — discovery/auto-registration, 2-way load-balancing, failover/health. - **runtime adapters** — factor the transport behind an adapter so the core stays runtime-agnostic; Node / Deno / Bun / edge become thin adapters over web-standard `Request`/`Response`. Only `src/http.ts` is runtime-specific today. - official plugins (cors, body parsers, auth) — structurally unable to sabotage the global pipeline. diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..f7551c1 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,115 @@ +# green-tea — Architecture + +> The request and boot are an explicit **dependency graph**, not a mutable middleware chain. +> You declare *what* you need; the framework computes the order. The graph can extend in +> **time** (streams) and across **machines** (mesh). + +## The four layers + +```mermaid +flowchart TB + subgraph L3["#3 MESH — the graph crosses machines"] + direction LR + teacup["teacup (consumer)"] -- "WS RPC" --> teapot["teapot (host)"] + end + subgraph L2["#2 STREAMS — the graph emits over time"] + sse["SSE / ndjson"]:::n + ws["WebSocket duplex"]:::n + end + subgraph L15["#1.5 ARG DECORATORS — the handler declares its deps"] + sig["handler signature = dependency declaration"]:::n + end + subgraph L1["#1 CORE — graph DI + boot + router + pipeline + flow"] + core["Providers · Steps · Routes · Transformers · Container · Bus"]:::n + end + L3 --> L2 --> L15 --> L1 + classDef n fill:#f6f8fa,stroke:#aaa; +``` + +## Building blocks + +```mermaid +flowchart LR + Provider["@Provider\n(app scope · singleton)"]:::p + Step["@Step\n(request scope · per call)"]:::s + Route["@Route + @Get/@Post/@Sse/@Ws/@Stream"]:::r + Transformer["@Transformer\nvalue → ResponseShape"]:::t + Container["Container.resolve()\nasync · transport-agnostic"]:::c + Bus["Bus\nlifecycle events"]:::b + + Provider --> Container + Step --> Container + Route --> Transformer + Container -. "remote binding (mesh)" .-> Provider + classDef p fill:#e7f5ff,stroke:#4dabf7; + classDef s fill:#fff3bf,stroke:#f59f00; + classDef r fill:#ebfbee,stroke:#40c057; + classDef t fill:#f3f0ff,stroke:#7950f2; + classDef c fill:#fff0f6,stroke:#e64980; + classDef b fill:#f1f3f5,stroke:#868e96; +``` + +## Request lifecycle + +```mermaid +sequenceDiagram + participant C as Client + participant H as http.ts (transport) + participant P as Pipeline + participant G as Graph (providers/steps) + participant T as Transformer + + C->>H: HTTP request + H->>H: matchRoute(method, path) + H->>P: runPipeline(seed = req envelope) + P->>G: providers (cached) + steps (topo order) + Note over G: each step merges into ctx;
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. diff --git a/docs/quickstart.md b/docs/quickstart.md new file mode 100644 index 0000000..fe412f4 --- /dev/null +++ b/docs/quickstart.md @@ -0,0 +1,227 @@ +# 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" } } +``` + +### 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) { + const out = channel(); + (async () => { + for await (const msg of incoming) out.push(`echo: ${msg}`); + out.close(); + })(); + return out; + } +} +``` + +`channel()` is a multicast `AsyncIterable` with `push` / `close` / `fail` and an optional +bounded buffer (`channel({ buffer: 100 })`, drop-oldest). + +## 5. Mesh — distributed dependency injection + +A **teacup** can depend on a token that physically lives on a **teapot**. Exports are +opt-in (`export: true`) and the control channel is gated by a shared secret. + +**Node A — teapot (exposes `config`, `auth`, and a route):** + +```typescript +@Provider({ provides: 'config', export: true }) +class Config { provide() { return { config: { region: 'mx', tier: 'pro' } }; } } + +@Step({ provides: 'auth', needs: [], export: true }) +class Auth { run(ctx: any) { return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; } } + +@Route('/svc') +class Svc { @Get('/ping', { export: true }) ping() { return { pong: true }; } } + +@Module({ mountpoint: '/api', providers: [Config], steps: [Auth], controllers: [Svc] }) +class TeapotModule {} + +const teapot = createApp({ modules: [TeapotModule], mesh: { secret: 'shh' } }); +await teapot.listen(3002); +``` + +**Node B — teacup (uses `config` + `auth` with no local providers):** + +```typescript +@Route('/local') +class LocalCtl { + @Get('/who') + who(@needs('config') config: any, @needs('auth') auth: any) { + return { config, auth }; // both resolved by RPC to the teapot + } +} +@Module({ mountpoint: '/api', controllers: [LocalCtl] }) +class TeacupModule {} + +const teacup = createApp({ + modules: [TeacupModule], + mesh: { teapots: [{ url: 'ws://A-host:3002/__mesh__/control', secret: 'shh' }] }, +}); +await teacup.listen(3003); +// GET B:3003/api/local/who (x-token: abc) +// → { "config": { "region": "mx", "tier": "pro" }, "auth": { "token": "abc" } } +``` + +`@needs('config' | 'auth')` validates at boot because the teapot announced them in its +manifest on connect. A provider export is app-scope (resolved once, cached); a step export is +request-scope (RPC per request, carrying the request envelope). + +> Skeleton limitations (by design): no discovery, load-balancing, or failover yet; app-scope +> remote values are not reconciled on reconnect; the request envelope omits `req.url`. + +## 6. Plugins & observability + +```typescript +const logger = (api: any) => { + api.bus.on('request:step:enter', (p: any) => console.log(`→ ${p.name}`)); + api.bus.on('stream:open', (p: any) => console.log(`stream open ${p.name}`)); + api.bus.on('mesh:rpc:error', (p: any) => console.error('mesh rpc failed', p.error)); +}; + +const app = createApp({ modules: [ApiModule], plugins: [logger] }); +``` + +Lifecycle events: `boot:provider:*`, `request:step:*`, `stream:open|close|error`, +`mesh:connect|disconnect|rpc:error`, `plugin:mounted`. + +## 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) +``` From 774d807e9659e45e620cf99a2b39777c7088f54c Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 27 Jun 2026 21:49:40 -0500 Subject: [PATCH 024/139] docs: comparison vs Express/Fastify/NestJS/expressive-tea Signed-off-by: Diego Resendez --- README.md | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/README.md b/README.md index 48551bf..abc6a39 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,51 @@ Express/Fastify middleware is positional, untyped, and globally mutable: order d - **Response = return value.** No `Response.json()`. Return data; a `@Transformer` serializes it in a leave phase. Cut a request by `throw`ing a typed signal. - **Fail-fast boot.** A required provider that can't initialize (e.g. the DB) stops the server from serving — no 500s because a resource wasn't ready. +## How it compares + +Every framework here can serve `/users/:id`. The difference is what happens when the app +grows: more dependencies, real-time, and more than one machine. + +| | Express | Fastify | NestJS | expressive-tea | **green-tea** | +|---|---|---|---|---|---| +| **Pipeline model** | positional `app.use()` | hooks + encapsulated plugins | DI + interceptors/guards | decorators on Express + boot stages | **explicit dependency graph (topo-sorted)** | +| **Order is decided by** | the line you wrote it on | hook phase + registration order | module/provider wiring | boot-stage order | **what each step *needs/produces*** | +| **`req.user` exists?** | hope so | hope so | if the guard ran | if the middleware ran | **boot fails if nothing provides it** | +| **Type safety** | none | schemas (runtime) | decorator types (runtime DI) | runtime | **compile-time in `flow`** + boot-validated decorators | +| **Response** | `res.send()` (mutate) | `reply.send()` | return value | return value | **return value → `@Transformer`** | +| **Real-time** | bolt on `ws`/`sse` libs | plugins | separate Gateway + adapter | separate engine | **return an `AsyncIterable`** — same primitive | +| **Cross-service calls** | HTTP client / gRPC by hand | HTTP client / gRPC | Microservices transport + message patterns | — | **`@needs('x')` resolves on another node** | +| **Plugin can break your pipeline?** | yes (deletes your body parser) | encapsulated, but hooks are global | interceptor order matters | yes | **no** — plugins only `bus.on` + `scope.add` | +| **Runtime deps** | minimal | minimal | heavy (rxjs, reflect-metadata, …) | Express + InversifyJS | **`reflect-metadata` only** (`ws` optional) | + +### Read it as a story + +- **Express / Fastify** — fast and battle-tested, but the request is a *mutable bag* threaded + through positional middleware. Order is implicit, `req.x` is a leap of faith, and a careless + plugin can delete another's work. You wire types and DI yourself. +- **NestJS** — brings DI, decorators, and structure, but the DI is *runtime token resolution*, + it's a large opinionated dependency tree, and every new capability (WebSockets, gRPC, + microservices) is a **separate subsystem** with its own abstraction (Gateways, transports, + message patterns) to learn and glue. +- **expressive-tea** — the sibling this project grew from: decorators + InversifyJS DI + boot + stages on top of Express. green-tea keeps the ideas, drops Express and Inversify, and makes + the graph — not the middleware chain — the core. +- **green-tea** — one model answers three questions other stacks answer with three subsystems: + - *"what does this handler depend on?"* → the graph (boot-validated, `flow` checks it at compile time) + - *"how do I push data over time?"* → return an `AsyncIterable` (SSE / WebSocket, one primitive) + - *"how do I call another service?"* → `@needs` a token that lives on another node (mesh) + + A remote dependency looks **identical** to a local one. There is no gRPC layer, no + message-pattern DSL, no separate WebSocket gateway — there is the graph, and some of its + nodes happen to live on another machine. + +### Honest scope + +green-tea is **alpha**. Express/Fastify have a decade of ecosystem; NestJS has enterprise +tooling and a huge plugin catalog. Mesh discovery, load-balancing, and failover are not built +yet (the [walking skeleton](./docs/quickstart.md#5-mesh--distributed-dependency-injection) is). +Pick green-tea for the model, not the ecosystem — *yet*. + ## Quick look ```typescript From a327352ba0422eb8e60ca9218e3be822dd9db312 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 28 Jun 2026 01:02:43 -0500 Subject: [PATCH 025/139] ci: typecheck, test, and build on push/PR (Gitea Actions, Node 18) Signed-off-by: Diego Resendez --- .gitea/workflows/ci.yml | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 .gitea/workflows/ci.yml diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..ba0e6fd --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,18 @@ +name: CI +on: + push: + branches: [develop, main] + pull_request: + branches: [develop, main] +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '18' + - run: npm ci + - run: npm run typecheck + - run: npm test + - run: npm run build From ddca3fd74bab2f0dd9b0ac598942dd35749495c8 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 28 Jun 2026 01:05:09 -0500 Subject: [PATCH 026/139] feat: request body-size limit (413) and configurable server timeouts Signed-off-by: Diego Resendez --- src/app.ts | 6 +++--- src/http.ts | 35 ++++++++++++++++++++++++++++------- src/index.ts | 1 + test/http.test.ts | 41 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 73 insertions(+), 10 deletions(-) diff --git a/src/app.ts b/src/app.ts index 7374ac5..f6a415e 100644 --- a/src/app.ts +++ b/src/app.ts @@ -3,7 +3,7 @@ import { Bus } from './bus'; import { Container } from './container'; import { topoSort, GraphNode } from './graph'; import { runPipeline, PipelineStep } from './pipeline'; -import { createHttpServer, parseQuery, RouteDef, WsRouteDef } from './http'; +import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from './http'; import { isAsyncIterable } from './channel'; import { JsonTransformer } from './transformers'; import { mountPlugin, Plugin, ScopeApi, ScopeNode } from './plugin'; @@ -43,7 +43,7 @@ export interface MeshConfig { timeoutMs?: number; } -export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig }): App { +export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits }): App { const bus = new Bus(); const container = new Container(); const extraSteps: ScopeNode[] = []; @@ -279,7 +279,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me }, })); - const server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl); + const server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits }); server.on('close', () => { for (const l of meshLinks) { try { l.close(); } catch { /* */ } } }); await new Promise((resolve) => server.listen(port, resolve)); return server; diff --git a/src/http.ts b/src/http.ts index 86b05b4..a0bc495 100644 --- a/src/http.ts +++ b/src/http.ts @@ -2,11 +2,20 @@ import http from 'http'; import { once } from 'events'; import { channel } from './channel'; import { errorToResponse } from './transformers'; +import { HttpError } from './signals'; import { sseEncoder, ndjsonEncoder, StreamEncoder } from './encoders'; import { isStreamResult, type PipelineResult, type ResponseShape } from './pipeline'; import type { Transport } from './metadata'; import type { Bus } from './bus'; +export interface RequestLimits { + maxBodyBytes?: number; // default 1_000_000 + requestTimeoutMs?: number; // default 30_000 + headersTimeoutMs?: number; // default 10_000 + keepAliveTimeoutMs?: number; // default 5_000 +} +export interface HttpOptions { limits?: RequestLimits } + export type RouteHandler = (req: { method: string; url: string; headers: Record; @@ -58,9 +67,14 @@ export function parseQuery(url: string): Record { return out; } -async function readBody(req: http.IncomingMessage): Promise { +async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise { const chunks: Buffer[] = []; - for await (const chunk of req) chunks.push(chunk as Buffer); + let total = 0; + for await (const chunk of req) { + total += (chunk as Buffer).length; + if (total > maxBodyBytes) throw new HttpError(413, 'Payload Too Large'); + chunks.push(chunk as Buffer); + } if (chunks.length === 0) return undefined; const raw = Buffer.concat(chunks).toString('utf8'); return raw === '' ? undefined : raw; @@ -154,7 +168,10 @@ function attachWs(server: http.Server, wsRoutes: WsRouteDef[], bus?: Bus, meshCo }); } -export function createHttpServer(routes: RouteDef[], wsRoutes: WsRouteDef[] = [], bus?: Bus, meshControl?: MeshControl): http.Server { +export function createHttpServer( + routes: RouteDef[], wsRoutes: WsRouteDef[] = [], bus?: Bus, meshControl?: MeshControl, opts?: HttpOptions, +): http.Server { + const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000; const server = http.createServer(async (req, res) => { const url = req.url ?? '/'; const path = url.split('?')[0]; @@ -166,10 +183,11 @@ export function createHttpServer(routes: RouteDef[], wsRoutes: WsRouteDef[] = [] } let raw: string | undefined; try { - raw = await readBody(req); - } catch { - res.writeHead(500, { 'content-type': 'application/json' }); - res.end(JSON.stringify({ error: 'Internal Server Error' })); + raw = await readBody(req, maxBody); + } catch (error) { + const r = errorToResponse(error); + res.writeHead(r.status, { ...r.headers, connection: 'close' }); + res.end(r.body); return; } let body: unknown = raw; @@ -200,6 +218,9 @@ export function createHttpServer(routes: RouteDef[], wsRoutes: WsRouteDef[] = [] res.writeHead(r.status, r.headers); res.end(r.body); }); + server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000; + server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000; + server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000; attachWs(server, wsRoutes, bus, meshControl); return server; } diff --git a/src/index.ts b/src/index.ts index fec76a1..57ed120 100644 --- a/src/index.ts +++ b/src/index.ts @@ -20,6 +20,7 @@ export { inbound, abort } from './params'; export { sseEncoder, ndjsonEncoder } from './encoders'; export type { StreamEncoder } from './encoders'; export type { MeshConfig } from './app'; +export type { RequestLimits } from './http'; export { connectLink } from './mesh/link'; export { buildRemote, envelopeFrom } from './mesh/teacup'; export { buildManifest, createMeshControl, MESH_CONTROL_PATH } from './mesh/teapot'; diff --git a/test/http.test.ts b/test/http.test.ts index cc445d1..f94b407 100644 --- a/test/http.test.ts +++ b/test/http.test.ts @@ -97,3 +97,44 @@ describe('http streaming', () => { server.close(); }); }); + +describe('request hardening', () => { + const getUrl = (s: import('http').Server) => `http://127.0.0.1:${(s.address() as any).port}`; + + it('rejects an over-size body with 413 and does not run the handler', async () => { + let ran = false; + const server = createHttpServer( + [{ method: 'POST', pattern: '/echo', transport: 'buffer', + handler: async () => { ran = true; return { status: 200, headers: {}, body: 'ok' }; } }], + [], undefined, undefined, { limits: { maxBodyBytes: 16 } }, + ); + await new Promise((r) => server.listen(0, r)); + const res = await fetch(`${getUrl(server)}/echo`, { method: 'POST', body: 'x'.repeat(1000) }); + expect(res.status).toBe(413); + expect(ran).toBe(false); + server.close(); + }); + + it('sets the configured server timeouts', async () => { + const server = createHttpServer([], [], undefined, undefined, + { limits: { requestTimeoutMs: 12345, headersTimeoutMs: 6789, keepAliveTimeoutMs: 4321 } }); + expect(server.requestTimeout).toBe(12345); + expect(server.headersTimeout).toBe(6789); + expect(server.keepAliveTimeout).toBe(4321); + server.close(); + }); + + it('requestTimeout does NOT kill an in-flight SSE stream (streaming regression)', async () => { + async function* feed() { for (let n = 1; n <= 3; n++) { yield { n }; await new Promise((r) => setTimeout(r, 80)); } } + const server = createHttpServer( + [{ method: 'GET', pattern: '/feed', transport: 'sse', handler: async () => ({ stream: feed() }) }], + [], undefined, undefined, { limits: { requestTimeoutMs: 100 } }, + ); + await new Promise((r) => server.listen(0, r)); + const res = await fetch(`${getUrl(server)}/feed`, { headers: { accept: 'text/event-stream' } }); + const text = await res.text(); + expect(text).toContain('data: {"n":1}'); + expect(text).toContain('data: {"n":3}'); + server.close(); + }); +}); From 68caca2cc1ca24d0f2eb7593e249e3894bf4c1c9 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 28 Jun 2026 01:07:42 -0500 Subject: [PATCH 027/139] feat: graceful shutdown via app.close() force-closing streams and connections Signed-off-by: Diego Resendez --- src/app.ts | 16 +++++++++++++--- src/http.ts | 18 +++++++++++++----- test/app.test.ts | 19 +++++++++++++++++++ 3 files changed, 45 insertions(+), 8 deletions(-) diff --git a/src/app.ts b/src/app.ts index f6a415e..19e7079 100644 --- a/src/app.ts +++ b/src/app.ts @@ -20,6 +20,7 @@ import type { RequestEnvelope, RouteEntry } from './mesh/protocol'; export interface InspectLine { name: string; kind: 'provider' | 'step' | 'handler'; origin: string } export interface App { listen(port: number): Promise; + close(): Promise; inspect(routePath: string): InspectLine[]; bus: Bus; } @@ -46,6 +47,8 @@ export interface MeshConfig { export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits }): App { const bus = new Bus(); const container = new Container(); + let server: http.Server | undefined; + const streams = new Set<() => void>(); const extraSteps: ScopeNode[] = []; const scope: ScopeApi = { add: (n) => extraSteps.push(n) }; @@ -279,13 +282,20 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me }, })); - const server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits }); + server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams }); server.on('close', () => { for (const l of meshLinks) { try { l.close(); } catch { /* */ } } }); - await new Promise((resolve) => server.listen(port, resolve)); + await new Promise((resolve) => server!.listen(port, resolve)); return server; }; - return { listen, inspect, bus }; + const close = (): Promise => new Promise((resolve) => { + if (!server) return resolve(); + server.close(() => resolve()); // waits for in-flight buffered to drain + for (const closeStream of streams) closeStream(); // force-close long-lived SSE/WS so close() resolves + server.closeIdleConnections(); // Node >=18.2: drop idle keep-alive + }); + + return { listen, close, inspect, bus }; } async function snapshot(c: Container, needs: string[]): Promise> { diff --git a/src/http.ts b/src/http.ts index a0bc495..c4602c0 100644 --- a/src/http.ts +++ b/src/http.ts @@ -14,7 +14,7 @@ export interface RequestLimits { headersTimeoutMs?: number; // default 10_000 keepAliveTimeoutMs?: number; // default 5_000 } -export interface HttpOptions { limits?: RequestLimits } +export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void> } export type RouteHandler = (req: { method: string; url: string; @@ -88,7 +88,7 @@ function pickEncoder(transport: Transport, accept: string): StreamEncoder { async function pipeStream( res: http.ServerResponse, stream: AsyncIterable, encoder: StreamEncoder, - bus?: Bus, name = '', + bus?: Bus, name = '', streams?: Set<() => void>, ): Promise { res.writeHead(200, encoder.headers); bus?.emit('stream:open', { name }); @@ -97,6 +97,8 @@ async function pipeStream( if (encoder.ping) { ping = setInterval(() => res.write(encoder.ping!()), PING_MS); ping.unref?.(); } const stop = () => { if (ping) clearInterval(ping); void Promise.resolve(it.return?.()).catch(() => {}); }; res.on('close', stop); + const closer = () => { try { res.destroy(); } catch { /* */ } }; + streams?.add(closer); const onClose = once(res, 'close'); try { while (true) { @@ -113,6 +115,7 @@ async function pipeStream( if (frame && !res.writableEnded) res.write(frame); } finally { if (ping) clearInterval(ping); + streams?.delete(closer); if (!res.writableEnded && !res.destroyed) res.end(); bus?.emit('stream:close', { name }); } @@ -122,7 +125,9 @@ function loadWss(): any | null { try { return require('ws').WebSocketServer; } catch { return null; } } -function attachWs(server: http.Server, wsRoutes: WsRouteDef[], bus?: Bus, meshControl?: MeshControl): void { +function attachWs( + server: http.Server, wsRoutes: WsRouteDef[], bus?: Bus, meshControl?: MeshControl, streams?: Set<() => void>, +): void { if (wsRoutes.length === 0 && !meshControl) return; const WSS = loadWss(); const wss = WSS ? new WSS({ noServer: true }) : null; @@ -137,6 +142,9 @@ function attachWs(server: http.Server, wsRoutes: WsRouteDef[], bus?: Bus, meshCo if (!route) { socket.destroy(); return; } if (!wss) { socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n'); socket.destroy(); return; } wss.handleUpgrade(req, socket, head, async (ws: any) => { + const closer = () => { try { (ws.terminate ?? ws.close).call(ws); } catch { /* */ } }; + streams?.add(closer); + ws.on('close', () => streams?.delete(closer)); const inbound = channel(); const ac = new AbortController(); ws.on('message', (d: Buffer) => inbound.push(d.toString())); @@ -211,7 +219,7 @@ export function createHttpServer( } if (isStreamResult(result)) { const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? '')); - await pipeStream(res, result.stream, encoder, bus, matched.def.pattern); + await pipeStream(res, result.stream, encoder, bus, matched.def.pattern, opts?.streams); return; } const r: ResponseShape = result; @@ -221,6 +229,6 @@ export function createHttpServer( server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000; server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000; server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000; - attachWs(server, wsRoutes, bus, meshControl); + attachWs(server, wsRoutes, bus, meshControl, opts?.streams); return server; } diff --git a/test/app.test.ts b/test/app.test.ts index 250bd36..cb1c6d8 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -153,3 +153,22 @@ describe('app streaming wiring', () => { client.close(); server.close(); }); }); + +describe('graceful shutdown', () => { + it('app.close() stops accepting and resolves, even with an SSE stream open', async () => { + @Route('/') + class Ctl { @Sse('/ticks') ticks() { return (async function* () { yield { t: 1 }; await new Promise((r) => setTimeout(r, 1000)); yield { t: 2 }; })(); } } + @Module({ mountpoint: '/', controllers: [Ctl] }) class M {} + const app = createApp({ modules: [M] }); + const server = await app.listen(0); + const port = (server.address() as any).port; + + const res = await fetch(`http://127.0.0.1:${port}/ticks`, { headers: { accept: 'text/event-stream' } }); + const reader = res.body!.getReader(); + await reader.read(); // first event; stream still open + + await app.close(); // must NOT hang despite the open stream + await expect(fetch(`http://127.0.0.1:${port}/ticks`).then((r) => r.text())).rejects.toThrow(); + reader.cancel().catch(() => {}); + }); +}); From df01bbfc410e92f0c45f39a17d3724ad460b1f76 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 28 Jun 2026 01:09:47 -0500 Subject: [PATCH 028/139] =?UTF-8?q?feat:=20per-route=20subgraph=20slicing?= =?UTF-8?q?=20=E2=80=94=20routes=20run=20only=20their=20needed=20providers?= =?UTF-8?q?/steps?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Diego Resendez --- src/app.ts | 10 ++++++++-- src/graph.ts | 15 +++++++++++++++ test/app.test.ts | 39 +++++++++++++++++++++++++++++++++++++++ test/graph.test.ts | 22 ++++++++++++++++++++-- 4 files changed, 82 insertions(+), 4 deletions(-) diff --git a/src/app.ts b/src/app.ts index 19e7079..97afff6 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,7 +1,7 @@ import http from 'http'; import { Bus } from './bus'; import { Container } from './container'; -import { topoSort, GraphNode } from './graph'; +import { topoSort, subgraphFor, GraphNode } from './graph'; import { runPipeline, PipelineStep } from './pipeline'; import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from './http'; import { isAsyncIterable } from './channel'; @@ -129,7 +129,13 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params']); orderedProviders = ordered.filter((n) => providerNodes.includes(n)); orderedSteps = ordered.filter((n) => stepNodes.includes(n)); - for (const plan of routePlans) { plan.providers = orderedProviders; plan.steps = orderedSteps; } + const alwaysSteps = stepNodes.filter((n) => n.provides.length === 0); // side-effect/observer steps (plugins) + for (const plan of routePlans) { + const closure = subgraphFor(plan.needs, ordered); + plan.providers = closure.filter((n) => providerNodes.includes(n)); + const sliced = new Set([...closure.filter((n) => stepNodes.includes(n)), ...alwaysSteps]); + plan.steps = ordered.filter((n) => stepNodes.includes(n) && sliced.has(n)); // topo order, deduped + } const producedKeys = new Set([ ...providerNodes.flatMap((n) => n.provides), diff --git a/src/graph.ts b/src/graph.ts index 76f3112..7a215a9 100644 --- a/src/graph.ts +++ b/src/graph.ts @@ -37,3 +37,18 @@ export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] { for (const n of nodes) visit(n, []); return ordered; } + +export function subgraphFor(needs: string[], ordered: GraphNode[]): GraphNode[] { + const producedBy = new Map(); + for (const n of ordered) for (const k of n.provides) producedBy.set(k, n); + const inClosure = new Set(); + const work = [...needs]; + while (work.length) { + const token = work.pop() as string; + const node = producedBy.get(token); + if (!node || inClosure.has(node)) continue; // no producer = seed/envelope; already-seen = skip + inClosure.add(node); + work.push(...node.needs); + } + return ordered.filter((n) => inClosure.has(n)); +} diff --git a/test/app.test.ts b/test/app.test.ts index cb1c6d8..38e04b9 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -154,6 +154,45 @@ describe('app streaming wiring', () => { }); }); +describe('per-route subgraph slicing', () => { + it('a route that does not @needs a step does not run it', async () => { + const ran: string[] = []; + @Step({ provides: 'tracked', needs: [] }) + class Tracked { run() { ran.push('tracked'); return { tracked: true }; } } + @Route('/') + class Ctl { + @Get('/needs') needs(@needs('tracked') t: any) { return { t }; } + @Get('/free') free() { return { ok: true }; } + } + @Module({ mountpoint: '/', steps: [Tracked], controllers: [Ctl] }) class M {} + const app = createApp({ modules: [M] }); + const server = await app.listen(0); + const port = (server.address() as any).port; + + await fetch(`http://127.0.0.1:${port}/free`).then((r) => r.json()); + expect(ran).toEqual([]); // step did NOT run for /free + await fetch(`http://127.0.0.1:${port}/needs`).then((r) => r.json()); + expect(ran).toEqual(['tracked']); // step ran for /needs + expect(app.inspect('/free').map((l) => l.kind)).toEqual(['handler']); // no step in the chain + server.close(); + }); + + it('a side-effect step (provides: []) added by a plugin runs unconditionally', async () => { + // NB: @Step always provides exactly one token (always sliceable). provides:[] only arises via a plugin's scope.add. + const ran: string[] = []; + const observer = (api: any) => api.scope.add({ kind: 'step', name: 'obs', needs: [], provides: [], run: () => { ran.push('obs'); return {}; } }); + @Route('/') + class Ctl { @Get('/free') free() { return { ok: true }; } } + @Module({ mountpoint: '/', controllers: [Ctl] }) class M {} + const app = createApp({ modules: [M], plugins: [observer] }); + const server = await app.listen(0); + const port = (server.address() as any).port; + await fetch(`http://127.0.0.1:${port}/free`).then((r) => r.json()); + expect(ran).toEqual(['obs']); // ran despite the route @needs-ing nothing + server.close(); + }); +}); + describe('graceful shutdown', () => { it('app.close() stops accepting and resolves, even with an SSE stream open', async () => { @Route('/') diff --git a/test/graph.test.ts b/test/graph.test.ts index f59b92e..a64bb44 100644 --- a/test/graph.test.ts +++ b/test/graph.test.ts @@ -1,5 +1,5 @@ -import { expect, test } from 'vitest'; -import { topoSort, GraphNode } from '../src/graph'; +import { describe, expect, it, test } from 'vitest'; +import { topoSort, GraphNode, subgraphFor } from '../src/graph'; const node = (name: string, needs: string[], provides: string[]): GraphNode => ({ name, needs, provides, origin: 'test' }); @@ -23,3 +23,21 @@ test('throws on cycle', () => { const nodes = [node('a', ['b'], ['a']), node('b', ['a'], ['b'])]; expect(() => topoSort(nodes, [])).toThrow(/cycle detected/); }); + +const N = (name: string, needs: string[] = []) => ({ name, needs, provides: [name], origin: 'm' }); + +describe('subgraphFor', () => { + const ordered = [N('config'), N('db', ['config']), N('user', ['db', 'req']), N('audit', ['db'])]; + it('returns the transitive closure of needs, in the given order', () => { + expect(subgraphFor(['user'], ordered).map((n) => n.name)).toEqual(['config', 'db', 'user']); + }); + it('returns empty for no needs', () => { + expect(subgraphFor([], ordered)).toEqual([]); + }); + it('ignores tokens with no producer (seeds/envelope)', () => { + expect(subgraphFor(['user', 'query', 'req'], ordered).map((n) => n.name)).toEqual(['config', 'db', 'user']); + }); + it('does not pull in unrelated nodes', () => { + expect(subgraphFor(['user'], ordered).map((n) => n.name)).not.toContain('audit'); + }); +}); From 9a5f54a4b3054265cc47d6fdb31f8e7dcaa8bc73 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 28 Jun 2026 01:14:06 -0500 Subject: [PATCH 029/139] docs: document per-route slicing execution and app.close() in quickstart Signed-off-by: Diego Resendez --- docs/quickstart.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/docs/quickstart.md b/docs/quickstart.md index fe412f4..6db7651 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -68,8 +68,18 @@ 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? | From a25c9752a2e61ef804eef311620a8c8b98762fa9 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 28 Jun 2026 01:14:20 -0500 Subject: [PATCH 030/139] fix: always-run observer steps receive their declared needs under slicing Signed-off-by: Diego Resendez --- src/app.ts | 3 ++- test/app.test.ts | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/app.ts b/src/app.ts index 97afff6..3ca3b38 100644 --- a/src/app.ts +++ b/src/app.ts @@ -130,8 +130,9 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me orderedProviders = ordered.filter((n) => providerNodes.includes(n)); orderedSteps = ordered.filter((n) => stepNodes.includes(n)); const alwaysSteps = stepNodes.filter((n) => n.provides.length === 0); // side-effect/observer steps (plugins) + const alwaysNeeds = alwaysSteps.flatMap((n) => n.needs); // pull observers' deps into every route for (const plan of routePlans) { - const closure = subgraphFor(plan.needs, ordered); + const closure = subgraphFor([...plan.needs, ...alwaysNeeds], ordered); plan.providers = closure.filter((n) => providerNodes.includes(n)); const sliced = new Set([...closure.filter((n) => stepNodes.includes(n)), ...alwaysSteps]); plan.steps = ordered.filter((n) => stepNodes.includes(n) && sliced.has(n)); // topo order, deduped diff --git a/test/app.test.ts b/test/app.test.ts index 38e04b9..b1feb59 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -191,6 +191,22 @@ describe('per-route subgraph slicing', () => { expect(ran).toEqual(['obs']); // ran despite the route @needs-ing nothing server.close(); }); + + it('an always-run observer step receives its declared needs even when the route does not need them', async () => { + let seen: any; + const observer = (api: any) => api.scope.add({ kind: 'step', name: 'audit', needs: ['user'], provides: [], run: (ctx: any) => { seen = ctx.user; return {}; } }); + @Step({ provides: 'user', needs: [] }) + class Auth { run() { return { user: { id: 'u1' } }; } } + @Route('/') + class Ctl { @Get('/free') free() { return { ok: true }; } } // does NOT @needs('user') + @Module({ mountpoint: '/', steps: [Auth], controllers: [Ctl] }) class M {} + const app = createApp({ modules: [M], plugins: [observer] }); + const server = await app.listen(0); + const port = (server.address() as any).port; + await fetch(`http://127.0.0.1:${port}/free`).then((r) => r.json()); + expect(seen).toEqual({ id: 'u1' }); // observer got user, not undefined + server.close(); + }); }); describe('graceful shutdown', () => { From d67a4080dd721c5454232c82d244ff8da2e9d998 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 28 Jun 2026 02:28:39 -0500 Subject: [PATCH 031/139] feat: pure Mermaid/DOT/HTML graph renderers Signed-off-by: Diego Resendez --- src/graph-viz.ts | 45 ++++++++++++++++++++++++++++++++++++++++++ test/graph-viz.test.ts | 41 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 src/graph-viz.ts create mode 100644 test/graph-viz.test.ts diff --git a/src/graph-viz.ts b/src/graph-viz.ts new file mode 100644 index 0000000..f981962 --- /dev/null +++ b/src/graph-viz.ts @@ -0,0 +1,45 @@ +export interface GraphNodeView { name: string; kind: 'provider' | 'step'; origin: string; needs: string[]; provides: string[] } +export interface GraphRouteView { pattern: string; method: string; transport: string; chain: string[] } +export interface GraphView { nodes: GraphNodeView[]; routes: GraphRouteView[] } + +const nid = (s: string) => 'n_' + s.replace(/[^a-zA-Z0-9]/g, '_'); +const rid = (s: string) => 'r_' + s.replace(/[^a-zA-Z0-9]/g, '_'); + +export function toMermaid(view: GraphView): string { + const known = new Set(view.nodes.map((n) => n.name)); + const out: string[] = ['flowchart LR']; + for (const n of view.nodes) { + out.push(n.kind === 'provider' ? ` ${nid(n.name)}(["${n.name}"])` : ` ${nid(n.name)}["${n.name}"]`); + } + for (const n of view.nodes) for (const need of n.needs) if (known.has(need)) out.push(` ${nid(need)} --> ${nid(n.name)}`); + for (const r of view.routes) { + out.push(` ${rid(r.pattern)}{{"${r.method} ${r.pattern}"}}`); + for (const c of r.chain) if (known.has(c)) out.push(` ${nid(c)} --> ${rid(r.pattern)}`); + } + return out.join('\n'); +} + +export function toDOT(view: GraphView): string { + const known = new Set(view.nodes.map((n) => n.name)); + const out: string[] = ['digraph green_tea {', ' rankdir=LR;']; + for (const n of view.nodes) { + out.push(` "${n.name}" [shape=${n.kind === 'provider' ? 'ellipse' : 'box'}];`); + } + for (const n of view.nodes) for (const need of n.needs) if (known.has(need)) out.push(` "${need}" -> "${n.name}";`); + for (const r of view.routes) { + const label = `${r.method} ${r.pattern}`; + out.push(` "${label}" [shape=hexagon];`); + for (const c of r.chain) if (known.has(c)) out.push(` "${c}" -> "${label}";`); + } + out.push('}'); + return out.join('\n'); +} + +export function graphHtml(mermaid: string): string { + return [ + 'green-tea graph', + '', + '
', mermaid, '
', + '', + ].join('\n'); +} diff --git a/test/graph-viz.test.ts b/test/graph-viz.test.ts new file mode 100644 index 0000000..940c0d3 --- /dev/null +++ b/test/graph-viz.test.ts @@ -0,0 +1,41 @@ +import { describe, it, expect } from 'vitest'; +import { toMermaid, toDOT, graphHtml, type GraphView } from '../src/graph-viz'; + +const view: GraphView = { + nodes: [ + { name: 'db', kind: 'provider', origin: 'module:M', needs: ['config'], provides: ['db'] }, + { name: 'config', kind: 'provider', origin: 'module:M', needs: [], provides: ['config'] }, + { name: 'user', kind: 'step', origin: 'module:M', needs: ['db', 'req'], provides: ['user'] }, + ], + routes: [{ pattern: '/users/:id', method: 'GET', transport: 'buffer', chain: ['config', 'db', 'user', 'getUser'] }], +}; + +describe('toMermaid', () => { + it('declares nodes and draws needs edges between known nodes', () => { + const m = toMermaid(view); + expect(m).toContain('flowchart'); + expect(m).toContain('"db"'); + expect(m).toContain('"user"'); + expect(m).toContain('n_config --> n_db'); // db needs config + expect(m).toContain('n_db --> n_user'); // user needs db + expect(m).not.toContain('n_req'); // 'req' is a seed (no node) -> no edge + expect(m).toContain('GET /users/:id'); // route node label + }); +}); + +describe('toDOT', () => { + it('emits a digraph with nodes and edges', () => { + const d = toDOT(view); + expect(d).toContain('digraph'); + expect(d).toContain('"config" -> "db"'); + }); +}); + +describe('graphHtml', () => { + it('wraps mermaid source in an HTML page that loads mermaid', () => { + const html = graphHtml('flowchart LR\n a-->b'); + expect(html).toContain('
');
+    expect(html).toContain('flowchart LR');
+    expect(html).toContain('mermaid');
+  });
+});

From f5136e35d0058926ac206169d5ed36ff1baec107 Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Sun, 28 Jun 2026 02:30:22 -0500
Subject: [PATCH 032/139] =?UTF-8?q?feat:=20app.graph/explain/toMermaid/toD?=
 =?UTF-8?q?OT=20=E2=80=94=20inspect=20the=20dependency=20graph?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Signed-off-by: Diego Resendez 
---
 src/app.ts       | 38 +++++++++++++++++++++++++++++++++++++-
 src/index.ts     |  4 +++-
 test/app.test.ts | 29 +++++++++++++++++++++++++++++
 3 files changed, 69 insertions(+), 2 deletions(-)

diff --git a/src/app.ts b/src/app.ts
index 3ca3b38..f9a78f7 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -2,6 +2,7 @@ import http from 'http';
 import { Bus } from './bus';
 import { Container } from './container';
 import { topoSort, subgraphFor, GraphNode } from './graph';
+import { toMermaid, toDOT, type GraphView } from './graph-viz';
 import { runPipeline, PipelineStep } from './pipeline';
 import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from './http';
 import { isAsyncIterable } from './channel';
@@ -18,10 +19,16 @@ import type { MeshControl } from './http';
 import type { RequestEnvelope, RouteEntry } from './mesh/protocol';
 
 export interface InspectLine { name: string; kind: 'provider' | 'step' | 'handler'; origin: string }
+export interface ExplainNode { name: string; kind: 'provider' | 'step' | 'handler'; origin: string; needs: string[]; provides: string[] }
+export interface Explain { pattern: string; method: HttpMethod; transport: Transport; chain: ExplainNode[] }
 export interface App {
   listen(port: number): Promise;
   close(): Promise;
   inspect(routePath: string): InspectLine[];
+  graph(): GraphView;
+  toMermaid(): string;
+  toDOT(): string;
+  explain(routePath: string): Explain;
   bus: Bus;
 }
 
@@ -165,6 +172,35 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
     ];
   };
 
+  const graph = (): GraphView => {
+    if (!booted) throw new Error('graph() unavailable before listen() for mesh apps');
+    return {
+      nodes: [
+        ...providerNodes.map((n) => ({ name: n.name, kind: 'provider' as const, origin: n.origin, needs: n.needs, provides: n.provides })),
+        ...stepNodes.map((n) => ({ name: n.name, kind: 'step' as const, origin: n.origin, needs: n.needs, provides: n.provides })),
+      ],
+      routes: routePlans.map((p) => ({
+        pattern: p.pattern, method: p.method, transport: p.transport,
+        chain: [...p.providers.map((n) => n.name), ...p.steps.map((n) => n.name), p.handlerName],
+      })),
+    };
+  };
+
+  const explain = (routePath: string): Explain => {
+    if (!booted) throw new Error('explain() unavailable before listen() for mesh apps');
+    const plan = routePlans.find((p) => p.pattern === routePath);
+    if (!plan) throw new Error(`no route: ${routePath}`);
+    const nv = (n: GraphNode, kind: 'provider' | 'step'): ExplainNode => ({ name: n.name, kind, origin: n.origin, needs: n.needs, provides: n.provides });
+    return {
+      pattern: plan.pattern, method: plan.method, transport: plan.transport,
+      chain: [
+        ...plan.providers.map((n) => nv(n, 'provider')),
+        ...plan.steps.map((n) => nv(n, 'step')),
+        { name: plan.handlerName, kind: 'handler', origin: plan.origin, needs: plan.needs, provides: [] },
+      ],
+    };
+  };
+
   const providedSeed = async (plan: RoutePlan): Promise> => {
     const provided: Record = {};
     for (const p of plan.providers) {
@@ -302,7 +338,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
     server.closeIdleConnections();            // Node >=18.2: drop idle keep-alive
   });
 
-  return { listen, close, inspect, bus };
+  return { listen, close, inspect, graph, toMermaid: () => toMermaid(graph()), toDOT: () => toDOT(graph()), explain, bus };
 }
 
 async function snapshot(c: Container, needs: string[]): Promise> {
diff --git a/src/index.ts b/src/index.ts
index 57ed120..5f098fc 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -2,7 +2,9 @@ import 'reflect-metadata';
 
 export const VERSION = '0.0.0';
 export { createApp } from './app';
-export type { App, InspectLine } from './app';
+export type { App, InspectLine, Explain } from './app';
+export { toMermaid, toDOT } from './graph-viz';
+export type { GraphView } from './graph-viz';
 export { Provider, Step, Route, Get, Module, Transformer } from './metadata';
 export type { Plugin } from './plugin';
 export { JsonTransformer } from './transformers';
diff --git a/test/app.test.ts b/test/app.test.ts
index b1feb59..162c732 100644
--- a/test/app.test.ts
+++ b/test/app.test.ts
@@ -209,6 +209,35 @@ describe('per-route subgraph slicing', () => {
   });
 });
 
+import { toMermaid as renderMermaid } from '../src/graph-viz';
+
+describe('app.graph / explain', () => {
+  it('graph() returns nodes (with origin/needs/provides) and routes with their sliced chain', async () => {
+    @Provider({ provides: 'db' }) class Db { provide() { return { db: 1 }; } }
+    @Step({ provides: 'user', needs: ['db'] }) class Auth { run() { return { user: 1 }; } }
+    @Route('/u') class Ctl { @Get('/:id') get(@needs('user') u: any) { return { u }; } }
+    @Module({ mountpoint: '/api', providers: [Db], steps: [Auth], controllers: [Ctl] }) class M {}
+    const app = createApp({ modules: [M] });
+    const g = app.graph();
+    expect(g.nodes.find((n) => n.name === 'db')).toMatchObject({ kind: 'provider', origin: 'module:M' });
+    expect(g.nodes.find((n) => n.name === 'user')).toMatchObject({ kind: 'step', needs: ['db'] });
+    const route = g.routes.find((r) => r.pattern === '/api/u/:id')!;
+    expect(route.chain).toEqual(['db', 'user', 'get']);
+    expect(app.toMermaid()).toContain('flowchart');
+  });
+
+  it('explain() returns the rich chain with origin and a handler entry', async () => {
+    @Step({ provides: 'user', needs: [] }) class Auth { run() { return { user: 1 }; } }
+    @Route('/u') class Ctl { @Get('/me') me(@needs('user') u: any) { return { u }; } }
+    @Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] }) class M {}
+    const app = createApp({ modules: [M] });
+    const e = app.explain('/api/u/me');
+    expect(e).toMatchObject({ pattern: '/api/u/me', method: 'GET', transport: 'buffer' });
+    expect(e.chain.map((c) => `${c.kind}:${c.name}`)).toEqual(['step:user', 'handler:me']);
+    expect(e.chain[0]).toMatchObject({ origin: 'module:M', provides: ['user'] });
+  });
+});
+
 describe('graceful shutdown', () => {
   it('app.close() stops accepting and resolves, even with an SSE stream open', async () => {
     @Route('/')

From 73cd874caef66382083a388d1a26c020e46bf6be Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Sun, 28 Jun 2026 02:31:52 -0500
Subject: [PATCH 033/139] feat: opt-in GET /__graph__ dev endpoint rendering
 the live graph

Signed-off-by: Diego Resendez 
---
 src/app.ts       | 17 +++++++++++++++--
 test/app.test.ts | 26 ++++++++++++++++++++++++++
 2 files changed, 41 insertions(+), 2 deletions(-)

diff --git a/src/app.ts b/src/app.ts
index f9a78f7..1bbf352 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -2,7 +2,7 @@ import http from 'http';
 import { Bus } from './bus';
 import { Container } from './container';
 import { topoSort, subgraphFor, GraphNode } from './graph';
-import { toMermaid, toDOT, type GraphView } from './graph-viz';
+import { toMermaid, toDOT, graphHtml, type GraphView } from './graph-viz';
 import { runPipeline, PipelineStep } from './pipeline';
 import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from './http';
 import { isAsyncIterable } from './channel';
@@ -51,7 +51,7 @@ export interface MeshConfig {
   timeoutMs?: number;
 }
 
-export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits }): App {
+export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean }): App {
   const bus = new Bus();
   const container = new Container();
   let server: http.Server | undefined;
@@ -310,6 +310,19 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
       ...remoteRoutes,
     ];
 
+    if (opts.devGraph) {
+      httpRoutes.push({
+        method: 'GET', pattern: '/__graph__', transport: 'buffer',
+        handler: async (req) => {
+          const mermaid = toMermaid(graph());
+          const accept = String(req.headers['accept'] ?? '');
+          return accept.includes('text/plain')
+            ? { status: 200, headers: { 'content-type': 'text/plain' }, body: mermaid }
+            : { status: 200, headers: { 'content-type': 'text/html' }, body: graphHtml(mermaid) };
+        },
+      });
+    }
+
     const wsRoutes: WsRouteDef[] = routePlans
       .filter((plan) => plan.transport === 'ws' || plan.transport === 'negotiate')
       .map((plan) => ({
diff --git a/test/app.test.ts b/test/app.test.ts
index 162c732..3ab5680 100644
--- a/test/app.test.ts
+++ b/test/app.test.ts
@@ -238,6 +238,32 @@ describe('app.graph / explain', () => {
   });
 });
 
+describe('devGraph endpoint', () => {
+  const portOf = (s: any) => (s.address() as any).port;
+  it('serves /__graph__ as HTML when devGraph:true', async () => {
+    @Route('/u') class Ctl { @Get('/me') me() { return { ok: 1 }; } }
+    @Module({ mountpoint: '/api', controllers: [Ctl] }) class M {}
+    const app = createApp({ modules: [M], devGraph: true });
+    const s = await app.listen(0);
+    const html = await fetch(`http://127.0.0.1:${portOf(s)}/__graph__`).then((r) => r.text());
+    expect(html).toContain('class="mermaid"');
+    expect(html).toContain('flowchart');
+    const mmd = await fetch(`http://127.0.0.1:${portOf(s)}/__graph__`, { headers: { accept: 'text/plain' } });
+    expect(mmd.headers.get('content-type')).toContain('text/plain');
+    expect(await mmd.text()).toContain('flowchart');
+    s.close();
+  });
+  it('does NOT mount /__graph__ without devGraph', async () => {
+    @Route('/u') class Ctl { @Get('/me') me() { return { ok: 1 }; } }
+    @Module({ mountpoint: '/api', controllers: [Ctl] }) class M {}
+    const app = createApp({ modules: [M] });
+    const s = await app.listen(0);
+    const res = await fetch(`http://127.0.0.1:${portOf(s)}/__graph__`);
+    expect(res.status).toBe(404);
+    s.close();
+  });
+});
+
 describe('graceful shutdown', () => {
   it('app.close() stops accepting and resolves, even with an SSE stream open', async () => {
     @Route('/')

From cc0044ba6a95bc6e26fdbbc851b7e01901e9be87 Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Sun, 28 Jun 2026 02:33:52 -0500
Subject: [PATCH 034/139] =?UTF-8?q?feat:=20createApp=20overrides=20?=
 =?UTF-8?q?=E2=80=94=20swap=20any=20provider/step=20by=20token=20in=20one?=
 =?UTF-8?q?=20line?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Signed-off-by: Diego Resendez 
---
 src/app.ts       | 12 +++++++++++-
 test/app.test.ts | 28 ++++++++++++++++++++++++++++
 2 files changed, 39 insertions(+), 1 deletion(-)

diff --git a/src/app.ts b/src/app.ts
index 1bbf352..aacd63b 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -51,7 +51,7 @@ export interface MeshConfig {
   timeoutMs?: number;
 }
 
-export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean }): App {
+export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record }): App {
   const bus = new Bus();
   const container = new Container();
   let server: http.Server | undefined;
@@ -248,6 +248,16 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
       }
     }
 
+    // apply overrides: swap any provider/step runner by token in one line
+    if (opts.overrides) {
+      const produced = new Set([...providerNodes, ...stepNodes].flatMap((n) => n.provides));
+      for (const [token, val] of Object.entries(opts.overrides)) {
+        if (!produced.has(token)) throw new Error(`override for unknown token '${token}'`);
+        const fn = typeof val === 'function' ? (val as (ctx: any) => any) : () => ({ [token]: val });
+        runners.set(token, fn);   // direct set (setRunner throws on dup); replaces the real runner
+      }
+    }
+
     // run app-scoped providers in order (fail-fast for required)
     for (const node of orderedProviders) {
       bus.emit('boot:provider:start', { name: node.name, scope: node.origin });
diff --git a/test/app.test.ts b/test/app.test.ts
index 3ab5680..c1a5ddb 100644
--- a/test/app.test.ts
+++ b/test/app.test.ts
@@ -282,3 +282,31 @@ describe('graceful shutdown', () => {
     reader.cancel().catch(() => {});
   });
 });
+
+describe('overrides', () => {
+  const portOf = (s: any) => (s.address() as any).port;
+  it('overrides a provider token with a plain value (wrapped as a merge object)', async () => {
+    @Provider({ provides: 'db' }) class Db { provide() { return { db: { real: true } }; } }
+    @Route('/u') class Ctl { @Get('/x') x(@needs('db') db: any) { return { db }; } }
+    @Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] }) class M {}
+    const app = createApp({ modules: [M], overrides: { db: { fake: true } } });
+    const s = await app.listen(0);
+    expect(await fetch(`http://127.0.0.1:${portOf(s)}/api/u/x`).then((r) => r.json())).toEqual({ db: { fake: true } });
+    s.close();
+  });
+  it('overrides with a function runner', async () => {
+    @Provider({ provides: 'db' }) class Db { provide() { return { db: 'real' }; } }
+    @Route('/u') class Ctl { @Get('/x') x(@needs('db') db: any) { return { db }; } }
+    @Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] }) class M {}
+    const app = createApp({ modules: [M], overrides: { db: () => ({ db: 'fn' }) } });
+    const s = await app.listen(0);
+    expect(await fetch(`http://127.0.0.1:${portOf(s)}/api/u/x`).then((r) => r.json())).toEqual({ db: 'fn' });
+    s.close();
+  });
+  it('rejects an override for an unknown token', async () => {
+    @Route('/u') class Ctl { @Get('/x') x() { return { ok: 1 }; } }
+    @Module({ mountpoint: '/api', controllers: [Ctl] }) class M {}
+    const app = createApp({ modules: [M], overrides: { nope: 1 } });
+    await expect(app.listen(0)).rejects.toThrow(/unknown token 'nope'/);
+  });
+});

From 9d8088d0a9b0400e4509622821b080f211971fab Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Sun, 28 Jun 2026 02:36:37 -0500
Subject: [PATCH 035/139] feat: 'did you mean' boot hint, flow compile-time
 type-test, and demos

Signed-off-by: Diego Resendez 
---
 docs/quickstart.md            | 41 +++++++++++++++++++++++++++++++++++
 example/server.ts             |  2 ++
 src/app.ts                    |  5 +++--
 src/graph.ts                  | 18 +++++++++++++++
 test/app.test.ts              |  7 ++++++
 test/graph.test.ts            | 12 +++++++++-
 test/types/flow-types.test.ts |  6 +++++
 7 files changed, 88 insertions(+), 3 deletions(-)

diff --git a/docs/quickstart.md b/docs/quickstart.md
index 6db7651..d7fcdbe 100644
--- a/docs/quickstart.md
+++ b/docs/quickstart.md
@@ -228,6 +228,47 @@ const app = createApp({ modules: [ApiModule], plugins: [logger] });
 Lifecycle events: `boot:provider:*`, `request:step:*`, `stream:open|close|error`,
 `mesh:connect|disconnect|rpc:error`, `plugin:mounted`.
 
+## Inspect & test the graph
+
+### Visualize with Mermaid
+
+```typescript
+console.log(app.toMermaid());  // flowchart diagram of all nodes and routes
+```
+
+Enable a live `GET /__graph__` endpoint (renders HTML with Mermaid, or plain-text with `Accept: text/plain`):
+
+```typescript
+const app = createApp({ modules: [ApiModule], devGraph: true });
+// GET /__graph__            → HTML viewer
+// GET /__graph__ (text/plain) → raw Mermaid source
+```
+
+### Explain a route
+
+```typescript
+const e = app.explain('/api/users/:id');
+// { pattern, method, transport, chain: [{ name, kind, origin, needs, provides }, ...] }
+console.log(e.chain.map((n) => `${n.kind}:${n.name}`));
+// → ['provider:db', 'step:user', 'handler:getUser']
+```
+
+### Override tokens in tests
+
+Swap any provider or step token with a test double at construction time — no monkey-patching:
+
+```typescript
+const app = createApp({
+  modules: [ApiModule],
+  overrides: {
+    db: { find: () => ({ id: 'test-user' }) },   // plain object — wrapped as { db: value }
+    user: () => ({ user: { id: 'stub' } }),       // function runner
+  },
+});
+```
+
+Overrides replace only the named token's runner; the rest of the graph is untouched.
+
 ## The one rule to remember
 
 ```
diff --git a/example/server.ts b/example/server.ts
index 7ab6c97..c9c1367 100644
--- a/example/server.ts
+++ b/example/server.ts
@@ -67,6 +67,8 @@ export const streamApp = createApp({ modules: [StreamModule] });
 
 if (require.main === module) {
   console.log('chain for /api/users/:id ->', app.inspect('/api/users/:id'));
+  console.log('graph:\n' + app.toMermaid());
+  console.log('explain /api/users/:id:', app.explain('/api/users/:id'));
   app.listen(3000).then(() => console.log('green-tea on http://localhost:3000'));
   streamApp.listen(3001).then(() => console.log('green-tea streams on http://localhost:3001'));
 }
diff --git a/src/app.ts b/src/app.ts
index aacd63b..7d1af04 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -1,7 +1,7 @@
 import http from 'http';
 import { Bus } from './bus';
 import { Container } from './container';
-import { topoSort, subgraphFor, GraphNode } from './graph';
+import { topoSort, subgraphFor, GraphNode, nearest } from './graph';
 import { toMermaid, toDOT, graphHtml, type GraphView } from './graph-viz';
 import { runPipeline, PipelineStep } from './pipeline';
 import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from './http';
@@ -153,7 +153,8 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
     for (const plan of routePlans) {
       for (const need of plan.needs) {
         if (!allowed.has(need)) {
-          throw new Error(`handler '${plan.handlerName}' needs '${need}' but nothing (local or mesh) provides it`);
+          const hint = nearest(need, allowed);
+          throw new Error(`handler '${plan.handlerName}' needs '${need}' but nothing (local or mesh) provides it${hint ? ` — did you mean '${hint}'?` : ''}`);
         }
       }
     }
diff --git a/src/graph.ts b/src/graph.ts
index 7a215a9..1e992d1 100644
--- a/src/graph.ts
+++ b/src/graph.ts
@@ -1,3 +1,21 @@
+function levenshtein(a: string, b: string): number {
+  const m = a.length, n = b.length;
+  const d: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
+  for (let i = 0; i <= m; i++) d[i][0] = i;
+  for (let j = 0; j <= n; j++) d[0][j] = j;
+  for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++) {
+    d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
+  }
+  return d[m][n];
+}
+
+export function nearest(token: string, candidates: Iterable): string | undefined {
+  let best: string | undefined;
+  let bestD = 3;   // only suggest edit distance <= 2
+  for (const c of candidates) { const dist = levenshtein(token, c); if (dist < bestD) { bestD = dist; best = c; } }
+  return best;
+}
+
 export interface GraphNode {
   name: string;
   needs: string[];
diff --git a/test/app.test.ts b/test/app.test.ts
index c1a5ddb..d555167 100644
--- a/test/app.test.ts
+++ b/test/app.test.ts
@@ -108,6 +108,13 @@ test('boot fails when a handler needs something nothing provides', () => {
     .toThrow(/handler 'list' needs 'missing'/);
 });
 
+it('boot error for a misspelled @needs suggests the closest token', () => {
+  @Step({ provides: 'user', needs: [] }) class Auth { run() { return { user: 1 }; } }
+  @Route('/u') class Ctl { @Get('/x') x(@needs('usr') u: any) { return { u }; } }
+  @Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] }) class M {}
+  expect(() => createApp({ modules: [M] })).toThrow(/did you mean 'user'\?/);
+});
+
 import { Sse, Ws } from '../src/metadata';
 import { inbound } from '../src/params';
 import { channel } from '../src/channel';
diff --git a/test/graph.test.ts b/test/graph.test.ts
index a64bb44..dc5e825 100644
--- a/test/graph.test.ts
+++ b/test/graph.test.ts
@@ -1,5 +1,5 @@
 import { describe, expect, it, test } from 'vitest';
-import { topoSort, GraphNode, subgraphFor } from '../src/graph';
+import { topoSort, GraphNode, subgraphFor, nearest } from '../src/graph';
 
 const node = (name: string, needs: string[], provides: string[]): GraphNode =>
   ({ name, needs, provides, origin: 'test' });
@@ -41,3 +41,13 @@ describe('subgraphFor', () => {
     expect(subgraphFor(['user'], ordered).map((n) => n.name)).not.toContain('audit');
   });
 });
+
+describe('nearest', () => {
+  it('suggests a close candidate (edit distance <= 2)', () => {
+    expect(nearest('usr', ['user', 'config', 'db'])).toBe('user');
+    expect(nearest('confgi', ['user', 'config'])).toBe('config');
+  });
+  it('returns undefined when nothing is close', () => {
+    expect(nearest('zzzzzz', ['user', 'db'])).toBeUndefined();
+  });
+});
diff --git a/test/types/flow-types.test.ts b/test/types/flow-types.test.ts
index 66c5c1f..a6e76cf 100644
--- a/test/types/flow-types.test.ts
+++ b/test/types/flow-types.test.ts
@@ -12,5 +12,11 @@ test('type guarantee holds (this file must typecheck)', () => {
     // @ts-expect-error — `user` is not in the accumulated context
     .handle((ctx) => ctx.user);
 
+  // GUARANTEE: a step can only read tokens produced by PRIOR steps.
+  flow<{ req: { token: string } }>()
+    .step('user', (ctx) => ({ user: ctx.req.token }))   // produces `user`
+    // @ts-expect-error — `db` was never produced by a prior step (only `user` was)
+    .step('next', (ctx) => ({ next: ctx.db }));
+
   expect(true).toBe(true);
 });

From 2bbc43505e48b89acd802d6c09d8bb03d5561bfc Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Sun, 28 Jun 2026 13:22:01 -0500
Subject: [PATCH 036/139] feat: parse application/x-www-form-urlencoded request
 bodies

Signed-off-by: Diego Resendez 
---
 src/http.ts       |  2 ++
 test/http.test.ts | 14 ++++++++++++++
 2 files changed, 16 insertions(+)

diff --git a/src/http.ts b/src/http.ts
index c4602c0..f08a63e 100644
--- a/src/http.ts
+++ b/src/http.ts
@@ -207,6 +207,8 @@ export function createHttpServer(
         res.end(JSON.stringify({ error: 'Invalid JSON body' }));
         return;
       }
+    } else if (raw !== undefined && ct.includes('application/x-www-form-urlencoded')) {
+      body = Object.fromEntries(new URLSearchParams(raw));
     }
     let result: PipelineResult;
     try {
diff --git a/test/http.test.ts b/test/http.test.ts
index f94b407..468592e 100644
--- a/test/http.test.ts
+++ b/test/http.test.ts
@@ -137,4 +137,18 @@ describe('request hardening', () => {
     expect(text).toContain('data: {"n":3}');
     server.close();
   });
+
+  it('parses application/x-www-form-urlencoded into an object body', async () => {
+    const getUrl = (s: import('http').Server) => `http://127.0.0.1:${(s.address() as any).port}`;
+    const server = createHttpServer([{
+      method: 'POST', pattern: '/form', transport: 'buffer',
+      handler: async (req) => ({ status: 200, headers: { 'content-type': 'application/json' }, body: JSON.stringify(req.body) }),
+    }]);
+    await new Promise((r) => server.listen(0, r));
+    const res = await fetch(`${getUrl(server)}/form`, {
+      method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: 'a=1&b=two',
+    });
+    expect(await res.json()).toEqual({ a: '1', b: 'two' });
+    server.close();
+  });
 });

From 6171e5e6bdb8a49f41005cb393ed79ccfa5b733e Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Sun, 28 Jun 2026 13:23:54 -0500
Subject: [PATCH 037/139] feat: rooms broadcast-hub primitive, auto-provided to
 handlers

Signed-off-by: Diego Resendez 
---
 src/app.ts         |  9 +++++++++
 src/index.ts       |  1 +
 src/rooms.ts       | 11 +++++++++++
 test/app.test.ts   | 19 +++++++++++++++++++
 test/rooms.test.ts | 28 ++++++++++++++++++++++++++++
 5 files changed, 68 insertions(+)
 create mode 100644 src/rooms.ts
 create mode 100644 test/rooms.test.ts

diff --git a/src/app.ts b/src/app.ts
index 7d1af04..00a58ef 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -13,6 +13,7 @@ import {
 } from './metadata';
 import { getArgs, getHandlerNeeds, resolveArgs } from './params';
 import { connectLink, type Link } from './mesh/link';
+import { Rooms } from './rooms';
 import { buildRemote } from './mesh/teacup';
 import { buildManifest, createMeshControl } from './mesh/teapot';
 import type { MeshControl } from './http';
@@ -126,6 +127,14 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
     setRunner(n.name, n.run);
   }
 
+  // built-in: auto-provide a shared Rooms instance (unless the user declares one)
+  if (!runners.has('rooms')) {
+    const roomsInstance = new Rooms();
+    providerNodes.push({ name: 'rooms', needs: [], provides: ['rooms'], origin: 'builtin' });
+    providerMeta.set('rooms', { optional: false });
+    setRunner('rooms', () => ({ rooms: roomsInstance }));   // merge object -> ctx.rooms
+  }
+
   // For each route, resolve which providers/steps feed it via topo order.
   // MVP: every route depends on every declared step + provider in the app graph.
   // For mesh apps, finalize is DEFERRED to listen() so remote scopes can join the graph first.
diff --git a/src/index.ts b/src/index.ts
index 5f098fc..cbaa2e0 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -16,6 +16,7 @@ export { needs, ctx, param, query, body, headers } from './params';
 export type { Query, Headers, Context, ArgSpec } from './params';
 export { channel, isAsyncIterable } from './channel';
 export type { Channel } from './channel';
+export { Rooms } from './rooms';
 export { Sse, Ws, Stream, Post, Put, Patch, Delete } from './metadata';
 export type { Transport, HttpMethod } from './metadata';
 export { inbound, abort } from './params';
diff --git a/src/rooms.ts b/src/rooms.ts
new file mode 100644
index 0000000..7eee41b
--- /dev/null
+++ b/src/rooms.ts
@@ -0,0 +1,11 @@
+import { channel, type Channel } from './channel';
+
+export class Rooms {
+  private readonly hubs = new Map>();
+  room(name: string): Channel {
+    let hub = this.hubs.get(name);
+    if (!hub) { hub = channel(); this.hubs.set(name, hub); }
+    return hub as unknown as Channel;
+  }
+  names(): string[] { return [...this.hubs.keys()]; }
+}
diff --git a/test/app.test.ts b/test/app.test.ts
index d555167..6ed9190 100644
--- a/test/app.test.ts
+++ b/test/app.test.ts
@@ -216,6 +216,7 @@ describe('per-route subgraph slicing', () => {
   });
 });
 
+import { Rooms } from '../src/rooms';
 import { toMermaid as renderMermaid } from '../src/graph-viz';
 
 describe('app.graph / explain', () => {
@@ -317,3 +318,21 @@ describe('overrides', () => {
     await expect(app.listen(0)).rejects.toThrow(/unknown token 'nope'/);
   });
 });
+
+describe('rooms auto-provide', () => {
+  it('injects a built-in rooms instance resolvable via @needs("rooms")', async () => {
+    @Route('/r') class Ctl { @Get('/x') x(@needs('rooms') rooms: Rooms) { return { ok: rooms instanceof Rooms }; } }
+    @Module({ mountpoint: '/api', controllers: [Ctl] }) class M {}
+    const app = createApp({ modules: [M] });
+    const s = await app.listen(0);
+    const port = (s.address() as any).port;
+    expect(await fetch(`http://127.0.0.1:${port}/api/r/x`).then((r) => r.json())).toEqual({ ok: true });
+    s.close();
+  });
+  it('a user-declared rooms provider wins (no duplicate-name throw)', () => {
+    @Provider({ provides: 'rooms' }) class MyRooms { provide() { return { rooms: { custom: true } }; } }
+    @Route('/r') class Ctl { @Get('/x') x(@needs('rooms') rooms: any) { return rooms; } }
+    @Module({ mountpoint: '/api', providers: [MyRooms], controllers: [Ctl] }) class M {}
+    expect(() => createApp({ modules: [M] })).not.toThrow();
+  });
+});
diff --git a/test/rooms.test.ts b/test/rooms.test.ts
new file mode 100644
index 0000000..1f56de5
--- /dev/null
+++ b/test/rooms.test.ts
@@ -0,0 +1,28 @@
+import { describe, it, expect } from 'vitest';
+import { Rooms } from '../src/rooms';
+
+describe('Rooms', () => {
+  it('returns the same shared channel for a given name', () => {
+    const r = new Rooms();
+    expect(r.room('general')).toBe(r.room('general'));
+    expect(r.room('a')).not.toBe(r.room('b'));
+  });
+  it('broadcasts a push to all current subscribers of a room', async () => {
+    const r = new Rooms();
+    const hub = r.room('x');
+    const a = hub[Symbol.asyncIterator]();
+    const b = hub[Symbol.asyncIterator]();
+    await Promise.resolve();
+    hub.push(7);
+    expect((await a.next()).value).toBe(7);
+    expect((await b.next()).value).toBe(7);
+  });
+  it('isolates distinct rooms', async () => {
+    const r = new Rooms();
+    const it = r.room('a')[Symbol.asyncIterator]();
+    await Promise.resolve();
+    r.room('b').push(1);
+    r.room('a').push(2);
+    expect((await it.next()).value).toBe(2);
+  });
+});

From 9050a7e5d920ff888279d8a6dcffee0f92947303 Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Sun, 28 Jun 2026 13:25:24 -0500
Subject: [PATCH 038/139] feat: WS connections rejected by an HttpError close
 with 4000+status

Signed-off-by: Diego Resendez 
---
 src/http.ts     |  9 +++++++--
 test/ws.test.ts | 16 ++++++++++++++++
 2 files changed, 23 insertions(+), 2 deletions(-)

diff --git a/src/http.ts b/src/http.ts
index f08a63e..840a9be 100644
--- a/src/http.ts
+++ b/src/http.ts
@@ -2,7 +2,7 @@ import http from 'http';
 import { once } from 'events';
 import { channel } from './channel';
 import { errorToResponse } from './transformers';
-import { HttpError } from './signals';
+import { HttpError, isHttpError } from './signals';
 import { sseEncoder, ndjsonEncoder, StreamEncoder } from './encoders';
 import { isStreamResult, type PipelineResult, type ResponseShape } from './pipeline';
 import type { Transport } from './metadata';
@@ -167,7 +167,12 @@ function attachWs(
         try { ws.close(); } catch { /* already closed */ }
       } catch (err) {
         bus?.emit('stream:error', { name, error: err });
-        try { ws.close(1011); } catch { /* already closed */ }
+        if (isHttpError(err)) {
+          const reason = Buffer.from(String(err.message)).subarray(0, 120).toString();
+          try { ws.close(4000 + err.status, reason); } catch { /* already closed */ }
+        } else {
+          try { ws.close(1011); } catch { /* already closed */ }
+        }
       } finally {
         ac.abort();
         bus?.emit('stream:close', { name });
diff --git a/test/ws.test.ts b/test/ws.test.ts
index 571e9c3..ec58541 100644
--- a/test/ws.test.ts
+++ b/test/ws.test.ts
@@ -2,6 +2,7 @@ import { describe, it, expect } from 'vitest';
 import WebSocket from 'ws';
 import { channel } from '../src/channel';
 import { createHttpServer, type WsRouteDef } from '../src/http';
+import { Unauthorized } from '../src/signals';
 
 const url = (server: import('http').Server, path: string) => {
   const a = server.address();
@@ -34,4 +35,19 @@ describe('ws upgrade', () => {
     expect(aborted).toBe(true);
     server.close();
   });
+
+  it('closes with a 4000+status code when the WS open() throws an HttpError', async () => {
+    const wsRoutes = [{ pattern: '/secure', open: async () => { throw new Unauthorized('no token'); } }];
+    const server = createHttpServer([], wsRoutes as any);
+    await new Promise((r) => server.listen(0, r));
+    const port = (server.address() as any).port;
+    const WebSocket = (await import('ws')).default;
+    const client = new WebSocket(`ws://127.0.0.1:${port}/secure`);
+    const { code, reason } = await new Promise<{ code: number; reason: string }>((res) => {
+      client.on('close', (code: number, reason: Buffer) => res({ code, reason: reason.toString() }));
+    });
+    expect(code).toBe(4401);
+    expect(reason).toContain('no token');
+    server.close();
+  });
 });

From 3842271c4d0b316046a1e5d43932f12bbdd67c80 Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Sun, 28 Jun 2026 13:28:42 -0500
Subject: [PATCH 039/139] feat(example): in-memory CRUD with query and
 JSON/urlencoded bodies

Signed-off-by: Diego Resendez 
---
 example/crud.ts            | 91 ++++++++++++++++++++++++++++++++++++++
 test/examples/crud.test.ts | 28 ++++++++++++
 2 files changed, 119 insertions(+)
 create mode 100644 example/crud.ts
 create mode 100644 test/examples/crud.test.ts

diff --git a/example/crud.ts b/example/crud.ts
new file mode 100644
index 0000000..97aae4e
--- /dev/null
+++ b/example/crud.ts
@@ -0,0 +1,91 @@
+import {
+  createApp, Provider, Route,
+  Get, Post, Put, Patch, Delete,
+  Module, needs, param, query, body, NotFound,
+} from '../src/index';
+
+interface Todo { id: string; title: string; done: boolean }
+
+interface Store {
+  todos: Map;
+  next(): string;
+}
+
+@Provider({ provides: 'store' })
+class TodoStore {
+  private counter = 0;
+  private readonly todos: Map = new Map();
+
+  provide(): { store: Store } {
+    const store: Store = {
+      todos: this.todos,
+      next: () => String(++this.counter),
+    };
+    return { store };
+  }
+}
+
+@Route('/todos')
+class TodoController {
+  @Get('/')
+  list(@needs('store') store: Store, @query('done') done: string | undefined): Todo[] {
+    const all = [...store.todos.values()];
+    if (done !== undefined) {
+      const flag = done === 'true';
+      return all.filter((t) => t.done === flag);
+    }
+    return all;
+  }
+
+  @Get('/:id')
+  get(@needs('store') store: Store, @param('id') id: string): Todo {
+    const todo = store.todos.get(id);
+    if (!todo) throw new NotFound(`todo ${id} not found`);
+    return todo;
+  }
+
+  @Post('/')
+  create(@needs('store') store: Store, @body() data: Record): Todo {
+    const id = store.next();
+    const todo: Todo = { id, title: String(data.title ?? ''), done: false };
+    store.todos.set(id, todo);
+    return todo;
+  }
+
+  @Put('/:id')
+  replace(@needs('store') store: Store, @param('id') id: string, @body() data: Record): Todo {
+    if (!store.todos.has(id)) throw new NotFound(`todo ${id} not found`);
+    const todo: Todo = { id, title: String(data.title ?? ''), done: Boolean(data.done ?? false) };
+    store.todos.set(id, todo);
+    return todo;
+  }
+
+  @Patch('/:id')
+  merge(@needs('store') store: Store, @param('id') id: string, @body() data: Record): Todo {
+    const todo = store.todos.get(id);
+    if (!todo) throw new NotFound(`todo ${id} not found`);
+    const updated: Todo = {
+      id,
+      title: 'title' in data ? String(data.title) : todo.title,
+      done: 'done' in data ? Boolean(data.done) : todo.done,
+    };
+    store.todos.set(id, updated);
+    return updated;
+  }
+
+  @Delete('/:id')
+  remove(@needs('store') store: Store, @param('id') id: string): { deleted: string } {
+    if (!store.todos.has(id)) throw new NotFound(`todo ${id} not found`);
+    store.todos.delete(id);
+    return { deleted: id };
+  }
+}
+
+@Module({ mountpoint: '/api', providers: [TodoStore], controllers: [TodoController] })
+class TodoModule {}
+
+export const app = createApp({ modules: [TodoModule] });
+
+if (require.main === module) {
+  app.listen(3300).then(() => console.log('green-tea crud on http://localhost:3300'));
+}
diff --git a/test/examples/crud.test.ts b/test/examples/crud.test.ts
new file mode 100644
index 0000000..f97e236
--- /dev/null
+++ b/test/examples/crud.test.ts
@@ -0,0 +1,28 @@
+import { describe, it, expect, afterAll } from 'vitest';
+import { app } from '../../example/crud';
+
+let base: string; let server: any;
+const url = (p: string) => `${base}${p}`;
+afterAll(() => server?.close());
+
+describe('crud example', () => {
+  it('supports create / read / update / delete', async () => {
+    server = await app.listen(0); base = `http://127.0.0.1:${(server.address() as any).port}`;
+    const created = await fetch(url('/api/todos'), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ title: 'a' }) }).then((r) => r.json() as Promise<{ id: string; title: string; done: boolean }>);
+    expect(created).toMatchObject({ title: 'a' });
+    const id = created.id;
+    expect(await fetch(url(`/api/todos/${id}`)).then((r) => r.json())).toMatchObject({ title: 'a' });
+    await fetch(url(`/api/todos/${id}`), { method: 'PATCH', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ done: true }) });
+    expect(await fetch(url(`/api/todos/${id}`)).then((r) => r.json())).toMatchObject({ done: true });
+    const list = await fetch(url('/api/todos')).then((r) => r.json());
+    expect(Array.isArray(list)).toBe(true);
+    const del = await fetch(url(`/api/todos/${id}`), { method: 'DELETE' });
+    expect(del.status).toBe(200);
+    expect((await fetch(url(`/api/todos/${id}`))).status).toBe(404);
+  });
+
+  it('accepts urlencoded form bodies', async () => {
+    const res = await fetch(url('/api/todos'), { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: 'title=form' });
+    expect(await res.json()).toMatchObject({ title: 'form' });
+  });
+});

From 8335ff28754bc7bee9ac84cdf47b276b887c7018 Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Sun, 28 Jun 2026 13:30:16 -0500
Subject: [PATCH 040/139] feat(example): WS chat with rooms and handshake auth
 (no socket.io)

Signed-off-by: Diego Resendez 
---
 example/chat.ts            | 29 +++++++++++++++++++++++++++++
 test/examples/chat.test.ts | 25 +++++++++++++++++++++++++
 2 files changed, 54 insertions(+)
 create mode 100644 example/chat.ts
 create mode 100644 test/examples/chat.test.ts

diff --git a/example/chat.ts b/example/chat.ts
new file mode 100644
index 0000000..0c040e5
--- /dev/null
+++ b/example/chat.ts
@@ -0,0 +1,29 @@
+import { createApp, Step, Route, Ws, Module, Unauthorized, param, needs, inbound, Rooms } from '../src/index';
+
+@Step({ provides: 'user', needs: [] })
+class Authenticate {
+  run(ctx: any) {
+    const token = ctx.query?.token;            // steps read ctx directly (no @query on steps)
+    if (!token) throw new Unauthorized('token required');
+    return { user: { id: String(token) } };
+  }
+}
+
+@Route('/chat')
+class ChatController {
+  @Ws('/:room')
+  join(@param('room') room: string, @needs('user') user: any, @needs('rooms') rooms: Rooms, @inbound() incoming: AsyncIterable) {
+    const hub = rooms.room(room);
+    (async () => { for await (const msg of incoming) hub.push(`${user.id}: ${msg}`); })().catch(() => {});   // fire-and-forget pump
+    return hub;                                 // broadcast as the outbound channel
+  }
+}
+
+@Module({ mountpoint: '/', steps: [Authenticate], controllers: [ChatController] })
+class ChatModule {}
+
+export const app = createApp({ modules: [ChatModule] });
+
+if (require.main === module) {
+  app.listen(4100).then(() => console.log('chat on ws://localhost:4100/chat/:room?token=...'));
+}
diff --git a/test/examples/chat.test.ts b/test/examples/chat.test.ts
new file mode 100644
index 0000000..4ea912c
--- /dev/null
+++ b/test/examples/chat.test.ts
@@ -0,0 +1,25 @@
+import { describe, it, expect, afterAll } from 'vitest';
+import { app } from '../../example/chat';
+
+let server: any; let port: number;
+afterAll(() => server?.close());
+
+describe('chat example', () => {
+  it('two authed clients in a room see each other; missing token is rejected 4401', async () => {
+    server = await app.listen(0); port = (server.address() as any).port;
+    const WebSocket = (await import('ws')).default;
+
+    const a = new WebSocket(`ws://127.0.0.1:${port}/chat/general?token=alice`);
+    const b = new WebSocket(`ws://127.0.0.1:${port}/chat/general?token=bob`);
+    await Promise.all([new Promise((r) => a.on('open', r)), new Promise((r) => b.on('open', r))]);
+    const bGot = new Promise((r) => b.on('message', (d: Buffer) => r(d.toString())));
+    await new Promise((r) => setTimeout(r, 50));   // let server-side open()/subscribe complete (channel has no replay)
+    a.send('hi');
+    expect(await bGot).toContain('hi');
+    a.close(); b.close();
+
+    const noTok = new WebSocket(`ws://127.0.0.1:${port}/chat/general`);
+    const code = await new Promise((r) => noTok.on('close', (c: number) => r(c)));
+    expect(code).toBe(4401);
+  });
+});

From 0c29c76a8aa819bea948968c1f65ff30fa18d2ee Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Sun, 28 Jun 2026 13:37:33 -0500
Subject: [PATCH 041/139] fix(http): flush SSE headers immediately so idle
 subscriptions don't deadlock clients

Signed-off-by: Diego Resendez 
---
 src/http.ts | 1 +
 1 file changed, 1 insertion(+)

diff --git a/src/http.ts b/src/http.ts
index 840a9be..adf4252 100644
--- a/src/http.ts
+++ b/src/http.ts
@@ -91,6 +91,7 @@ async function pipeStream(
   bus?: Bus, name = '', streams?: Set<() => void>,
 ): Promise {
   res.writeHead(200, encoder.headers);
+  res.flushHeaders();   // establish the stream immediately so idle-until-event sources (e.g. subscriptions) don't deadlock clients awaiting headers
   bus?.emit('stream:open', { name });
   const it = stream[Symbol.asyncIterator]();
   let ping: ReturnType | undefined;

From c39eb667ace80ef895dc64d9cc0a8bc848fdf734 Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Sun, 28 Jun 2026 13:37:37 -0500
Subject: [PATCH 042/139] feat(example): minimal GraphQL with query/mutation
 and an SSE subscription over rooms

Signed-off-by: Diego Resendez 
---
 docs/quickstart.md            | 34 +++++++++++++++++++++++++
 example/graphql.ts            | 47 +++++++++++++++++++++++++++++++++++
 package-lock.json             | 19 ++++++++++++++
 package.json                  |  1 +
 test/examples/graphql.test.ts | 24 ++++++++++++++++++
 5 files changed, 125 insertions(+)
 create mode 100644 example/graphql.ts
 create mode 100644 test/examples/graphql.test.ts

diff --git a/docs/quickstart.md b/docs/quickstart.md
index d7fcdbe..552729c 100644
--- a/docs/quickstart.md
+++ b/docs/quickstart.md
@@ -269,6 +269,40 @@ const app = createApp({
 
 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
 
 ```
diff --git a/example/graphql.ts b/example/graphql.ts
new file mode 100644
index 0000000..720c349
--- /dev/null
+++ b/example/graphql.ts
@@ -0,0 +1,47 @@
+import { GraphQLSchema, GraphQLObjectType, GraphQLString, GraphQLList, GraphQLNonNull, graphql, subscribe, parse } from 'graphql';
+import { createApp, Route, Post, Sse, Module, body, needs, isAsyncIterable, Rooms } from '../src/index';
+
+interface Message { text: string }
+const store: Message[] = [];
+const MessageType = new GraphQLObjectType({ name: 'Message', fields: { text: { type: GraphQLString } } });
+
+function buildSchema(rooms: Rooms): GraphQLSchema {
+  return new GraphQLSchema({
+    query: new GraphQLObjectType({ name: 'Query', fields: {
+      messages: { type: new GraphQLList(MessageType), resolve: () => store },
+    } }),
+    mutation: new GraphQLObjectType({ name: 'Mutation', fields: {
+      postMessage: { type: MessageType, args: { text: { type: new GraphQLNonNull(GraphQLString) } },
+        resolve: (_root, { text }: { text: string }) => { const m = { text }; store.push(m); rooms.room('messages').push(m); return m; } },
+    } }),
+    subscription: new GraphQLObjectType({ name: 'Subscription', fields: {
+      messageAdded: { type: MessageType,
+        subscribe: () => rooms.room('messages'),   // Channel is the AsyncIterable source
+        resolve: (payload: Message) => payload },
+    } }),
+  });
+}
+
+@Route('/graphql')
+class GraphQLController {
+  @Post('')
+  async run(@body() input: any, @needs('rooms') rooms: Rooms) {
+    return graphql({ schema: buildSchema(rooms), source: input?.query ?? '', variableValues: input?.variables });
+  }
+
+  @Sse('/stream')
+  async stream(@needs('rooms') rooms: Rooms) {
+    const result = await subscribe({ schema: buildSchema(rooms), document: parse('subscription { messageAdded { text } }') });
+    if (!isAsyncIterable(result)) throw new Error('subscription failed');   // subscribe() returns a single ExecutionResult on error
+    return result;
+  }
+}
+
+@Module({ mountpoint: '/', controllers: [GraphQLController] })
+class GraphQLModule {}
+
+export const app = createApp({ modules: [GraphQLModule] });
+
+if (require.main === module) {
+  app.listen(4200).then(() => console.log('graphql on http://localhost:4200/graphql'));
+}
diff --git a/package-lock.json b/package-lock.json
index ad8d4ec..1e3ee1c 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -14,9 +14,18 @@
       "devDependencies": {
         "@types/node": "^18.19.0",
         "@types/ws": "^8.18.1",
+        "graphql": "^16.9.0",
         "typescript": "^5.5.0",
         "vitest": "^2.0.0",
         "ws": "^8.21.0"
+      },
+      "peerDependencies": {
+        "ws": "^8.18.0"
+      },
+      "peerDependenciesMeta": {
+        "ws": {
+          "optional": true
+        }
       }
     },
     "node_modules/@esbuild/aix-ppc64": {
@@ -1063,6 +1072,16 @@
         "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
       }
     },
+    "node_modules/graphql": {
+      "version": "16.14.2",
+      "resolved": "https://registry.npmjs.org/graphql/-/graphql-16.14.2.tgz",
+      "integrity": "sha512-Chq1s4CY7jmh8gO2qvLIJyfCDIN+EHLFW/9iShnp1z8FjBQMoodWP1kDC36VAMXXIvAjj4ARa7ntfAV2BrjsbA==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": "^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0"
+      }
+    },
     "node_modules/loupe": {
       "version": "3.2.1",
       "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",
diff --git a/package.json b/package.json
index de2f292..2e69fa2 100644
--- a/package.json
+++ b/package.json
@@ -26,6 +26,7 @@
   "devDependencies": {
     "@types/node": "^18.19.0",
     "@types/ws": "^8.18.1",
+    "graphql": "^16.9.0",
     "typescript": "^5.5.0",
     "vitest": "^2.0.0",
     "ws": "^8.21.0"
diff --git a/test/examples/graphql.test.ts b/test/examples/graphql.test.ts
new file mode 100644
index 0000000..8d07363
--- /dev/null
+++ b/test/examples/graphql.test.ts
@@ -0,0 +1,24 @@
+import { describe, it, expect, afterAll } from 'vitest';
+import { app } from '../../example/graphql';
+
+let server: any; let base: string;
+afterAll(() => server?.close());
+const gql = (query: string, variables?: any) =>
+  fetch(`${base}/graphql`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ query, variables }) }).then((r) => r.json() as Promise);
+
+describe('graphql example', () => {
+  it('runs a query and a mutation, and streams a subscription over SSE', async () => {
+    server = await app.listen(0); base = `http://127.0.0.1:${(server.address() as any).port}`;
+
+    expect(await gql('{ messages { text } }')).toMatchObject({ data: { messages: expect.any(Array) } });
+
+    const res = await fetch(`${base}/graphql/stream`, { headers: { accept: 'text/event-stream' } });
+    const reader = res.body!.getReader();
+    await new Promise((r) => setTimeout(r, 50));   // let the subscription subscribe to the room before publishing
+    await gql('mutation($t:String!){ postMessage(text:$t){ text } }', { t: 'hello-sub' });
+    const dec = new TextDecoder(); let buf = '';
+    while (!buf.includes('hello-sub')) buf += dec.decode((await reader.read()).value);
+    expect(buf).toContain('hello-sub');
+    await reader.cancel();
+  });
+});

From 881bc59419ab44f847cc273f7f730f4921b5114b Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Mon, 6 Jul 2026 18:52:24 -0500
Subject: [PATCH 043/139] feat(security): pure CORS + security-header
 computation module

Signed-off-by: Diego Resendez 
---
 src/security.ts       | 93 +++++++++++++++++++++++++++++++++++++++++++
 test/security.test.ts | 62 +++++++++++++++++++++++++++++
 2 files changed, 155 insertions(+)
 create mode 100644 src/security.ts
 create mode 100644 test/security.test.ts

diff --git a/src/security.ts b/src/security.ts
new file mode 100644
index 0000000..988f627
--- /dev/null
+++ b/src/security.ts
@@ -0,0 +1,93 @@
+// src/security.ts — pure header computation, no server deps
+export interface TlsOptions { key: Buffer | string; cert: Buffer | string; ca?: Buffer | string; passphrase?: string }
+
+export interface CorsOptions {
+  origins: string | string[] | '*' | ((origin: string) => boolean);
+  methods?: string[];
+  allowedHeaders?: string[];
+  exposedHeaders?: string[];
+  credentials?: boolean;
+  maxAge?: number;
+}
+
+export interface SecurityOptions {
+  hsts?: boolean | { maxAge?: number; includeSubDomains?: boolean; preload?: boolean };
+  frameOptions?: 'SAMEORIGIN' | 'DENY' | false;
+  referrerPolicy?: string | false;
+  noSniff?: boolean;
+  dnsPrefetchControl?: boolean;
+  csp?: string;
+}
+
+type Headers = Record;
+const HSTS_DEFAULT_MAXAGE = 15552000; // 180 days
+
+// scheme "://" host [":" port], or literal "null". Rejects control chars/whitespace.
+const ORIGIN_RE = /^(?:null|[a-z][a-z0-9+.-]*:\/\/[^\s/?#]+)$/i;
+export function isValidOrigin(o: string): boolean { return ORIGIN_RE.test(o); }
+
+export function mergeVary(existing: string | undefined, add: string): string {
+  const parts = (existing ? existing.split(',').map((s) => s.trim()).filter(Boolean) : []);
+  if (!parts.some((p) => p.toLowerCase() === add.toLowerCase())) parts.push(add);
+  return parts.join(', ');
+}
+
+export function buildSecurityHeaders(opts: boolean | SecurityOptions, secure: boolean): Headers {
+  if (opts === false) return {};
+  const o: SecurityOptions = opts === true ? {} : opts;
+  const h: Headers = {};
+  if (o.noSniff !== false) h['x-content-type-options'] = 'nosniff';
+  if (o.frameOptions !== false) h['x-frame-options'] = o.frameOptions ?? 'SAMEORIGIN';
+  if (o.referrerPolicy !== false) h['referrer-policy'] = o.referrerPolicy ?? 'no-referrer';
+  if (o.dnsPrefetchControl !== false) h['x-dns-prefetch-control'] = 'off';
+  if (o.csp) h['content-security-policy'] = o.csp;
+  if (secure && o.hsts !== false) {
+    const hs = o.hsts && o.hsts !== true ? o.hsts : {};
+    let v = `max-age=${hs.maxAge ?? HSTS_DEFAULT_MAXAGE}`;
+    if (hs.includeSubDomains) v += '; includeSubDomains';
+    if (hs.preload) v += '; preload';
+    h['strict-transport-security'] = v;
+  }
+  return h;
+}
+
+function originAllowed(spec: CorsOptions['origins'], origin: string): boolean {
+  if (spec === '*') return true;
+  if (typeof spec === 'function') return spec(origin);
+  if (Array.isArray(spec)) return spec.includes(origin);
+  return spec === origin;
+}
+
+// req: minimal shape { headers: { origin? } }
+export function resolveCors(opts: CorsOptions, req: { headers: Record }): Headers {
+  const h: Headers = {};
+  const raw = req.headers['origin'];
+  const origin = Array.isArray(raw) ? raw[0] : raw;
+  if (!origin || !isValidOrigin(origin) || !originAllowed(opts.origins, origin)) return h;
+
+  // credentials => never '*'; echo concrete origin. Also echo when allowlist is dynamic.
+  if (opts.credentials) {
+    h['access-control-allow-origin'] = origin;
+    h['access-control-allow-credentials'] = 'true';
+    h['vary'] = mergeVary(h['vary'], 'Origin');
+  } else if (opts.origins === '*') {
+    h['access-control-allow-origin'] = '*';
+  } else {
+    h['access-control-allow-origin'] = origin;
+    h['vary'] = mergeVary(h['vary'], 'Origin');
+  }
+  if (opts.exposedHeaders?.length) h['access-control-expose-headers'] = opts.exposedHeaders.join(', ');
+  return h;
+}
+
+// Preflight-specific headers (methods/allowed-headers/max-age). Call only for OPTIONS+ACRM.
+export function corsPreflightHeaders(opts: CorsOptions, req: { headers: Record }): Headers {
+  const h = resolveCors(opts, req);
+  if (!h['access-control-allow-origin']) return h; // origin not allowed → bare 204
+  h['access-control-allow-methods'] = (opts.methods ?? ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']).join(', ');
+  const reqHdrs = req.headers['access-control-request-headers'];
+  h['access-control-allow-headers'] = opts.allowedHeaders?.join(', ')
+    ?? (Array.isArray(reqHdrs) ? reqHdrs.join(', ') : reqHdrs ?? '*');
+  if (opts.maxAge != null) h['access-control-max-age'] = String(opts.maxAge);
+  return h;
+}
diff --git a/test/security.test.ts b/test/security.test.ts
new file mode 100644
index 0000000..9ad2ad4
--- /dev/null
+++ b/test/security.test.ts
@@ -0,0 +1,62 @@
+import { describe, it, expect } from 'vitest';
+import { buildSecurityHeaders, resolveCors, mergeVary } from '../src/security';
+
+describe('buildSecurityHeaders', () => {
+  it('default set (security:true), no HSTS over insecure', () => {
+    const h = buildSecurityHeaders(true, false);
+    expect(h['x-content-type-options']).toBe('nosniff');
+    expect(h['x-frame-options']).toBe('SAMEORIGIN');
+    expect(h['referrer-policy']).toBe('no-referrer');
+    expect(h['x-dns-prefetch-control']).toBe('off');
+    expect(h['strict-transport-security']).toBeUndefined();
+  });
+  it('HSTS only when secure', () => {
+    const h = buildSecurityHeaders(true, true);
+    expect(h['strict-transport-security']).toBe('max-age=15552000');
+  });
+  it('security:false → empty', () => {
+    expect(buildSecurityHeaders(false, true)).toEqual({});
+  });
+  it('object overrides: disable frameOptions, custom referrer, csp, hsts opts', () => {
+    const h = buildSecurityHeaders({ frameOptions: false, referrerPolicy: 'strict-origin',
+      csp: "default-src 'self'", hsts: { maxAge: 100, includeSubDomains: true } }, true);
+    expect(h['x-frame-options']).toBeUndefined();
+    expect(h['referrer-policy']).toBe('strict-origin');
+    expect(h['content-security-policy']).toBe("default-src 'self'");
+    expect(h['strict-transport-security']).toBe('max-age=100; includeSubDomains');
+  });
+});
+
+describe('resolveCors', () => {
+  const req = (origin?: string) => ({ headers: origin ? { origin } : {} });
+  it('exact-string allowlist echoes origin + Vary', () => {
+    const r = resolveCors({ origins: 'https://a.com' }, req('https://a.com') as any);
+    expect(r['access-control-allow-origin']).toBe('https://a.com');
+    expect(r['vary']).toBe('Origin');
+  });
+  it('disallowed origin → no allow-origin header', () => {
+    const r = resolveCors({ origins: 'https://a.com' }, req('https://evil.com') as any);
+    expect(r['access-control-allow-origin']).toBeUndefined();
+  });
+  it("'*' without credentials returns *", () => {
+    const r = resolveCors({ origins: '*' }, req('https://a.com') as any);
+    expect(r['access-control-allow-origin']).toBe('*');
+  });
+  it('credentials:true never returns * — echoes concrete origin', () => {
+    const r = resolveCors({ origins: '*', credentials: true }, req('https://a.com') as any);
+    expect(r['access-control-allow-origin']).toBe('https://a.com');
+    expect(r['access-control-allow-credentials']).toBe('true');
+  });
+  it('rejects malformed Origin (control char) even if predicate allows', () => {
+    const r = resolveCors({ origins: () => true }, req('https://a.com\r\nX: y') as any);
+    expect(r['access-control-allow-origin']).toBeUndefined();
+  });
+});
+
+describe('mergeVary', () => {
+  it('appends, dedupes, handles empty', () => {
+    expect(mergeVary(undefined, 'Origin')).toBe('Origin');
+    expect(mergeVary('Accept-Encoding', 'Origin')).toBe('Accept-Encoding, Origin');
+    expect(mergeVary('Origin', 'Origin')).toBe('Origin');
+  });
+});

From b87bdc698fa61f6564517319ddc6f5122a8b1a5a Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Mon, 6 Jul 2026 18:56:07 -0500
Subject: [PATCH 044/139] fix(security): reject all control bytes in Origin
 validation

Signed-off-by: Diego Resendez 
---
 src/security.ts       |  2 +-
 test/security.test.ts | 15 ++++++++++++++-
 2 files changed, 15 insertions(+), 2 deletions(-)

diff --git a/src/security.ts b/src/security.ts
index 988f627..18c58b8 100644
--- a/src/security.ts
+++ b/src/security.ts
@@ -23,7 +23,7 @@ type Headers = Record;
 const HSTS_DEFAULT_MAXAGE = 15552000; // 180 days
 
 // scheme "://" host [":" port], or literal "null". Rejects control chars/whitespace.
-const ORIGIN_RE = /^(?:null|[a-z][a-z0-9+.-]*:\/\/[^\s/?#]+)$/i;
+const ORIGIN_RE = /^(?:null|[a-z][a-z0-9+.-]*:\/\/[^\s/?#\x00-\x1f\x7f]+)$/i;
 export function isValidOrigin(o: string): boolean { return ORIGIN_RE.test(o); }
 
 export function mergeVary(existing: string | undefined, add: string): string {
diff --git a/test/security.test.ts b/test/security.test.ts
index 9ad2ad4..4cba1e9 100644
--- a/test/security.test.ts
+++ b/test/security.test.ts
@@ -1,5 +1,5 @@
 import { describe, it, expect } from 'vitest';
-import { buildSecurityHeaders, resolveCors, mergeVary } from '../src/security';
+import { buildSecurityHeaders, resolveCors, mergeVary, isValidOrigin } from '../src/security';
 
 describe('buildSecurityHeaders', () => {
   it('default set (security:true), no HSTS over insecure', () => {
@@ -53,6 +53,19 @@ describe('resolveCors', () => {
   });
 });
 
+describe('isValidOrigin', () => {
+  it('accepts valid origins and literal null', () => {
+    expect(isValidOrigin('https://a.com')).toBe(true);
+    expect(isValidOrigin('http://localhost:3000')).toBe(true);
+    expect(isValidOrigin('null')).toBe(true);
+  });
+  it('rejects CRLF and other control bytes', () => {
+    expect(isValidOrigin('https://a.com\r\nX: y')).toBe(false);
+    expect(isValidOrigin('https://a.com\x00evil')).toBe(false);
+    expect(isValidOrigin('https://a.com\x1bevil')).toBe(false);
+  });
+});
+
 describe('mergeVary', () => {
   it('appends, dedupes, handles empty', () => {
     expect(mergeVary(undefined, 'Origin')).toBe('Origin');

From b8ee1b14a53eee4d2df2e7a5d39da9ff09ddf7bc Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Mon, 6 Jul 2026 18:58:40 -0500
Subject: [PATCH 045/139] =?UTF-8?q?feat(http):=20native=20TLS=20terminatio?=
 =?UTF-8?q?n=20=E2=86=92=20https/wss=20via=20tls=20option?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Signed-off-by: Diego Resendez 
---
 src/app.ts                      |  5 ++--
 src/http.ts                     | 12 ++++++--
 test/fixtures/cert.pem          | 19 +++++++++++++
 test/fixtures/key.pem           | 28 +++++++++++++++++++
 test/helpers/tls.ts             |  9 ++++++
 test/transport-security.test.ts | 49 +++++++++++++++++++++++++++++++++
 6 files changed, 117 insertions(+), 5 deletions(-)
 create mode 100644 test/fixtures/cert.pem
 create mode 100644 test/fixtures/key.pem
 create mode 100644 test/helpers/tls.ts
 create mode 100644 test/transport-security.test.ts

diff --git a/src/app.ts b/src/app.ts
index 00a58ef..02b9fad 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -14,6 +14,7 @@ import {
 import { getArgs, getHandlerNeeds, resolveArgs } from './params';
 import { connectLink, type Link } from './mesh/link';
 import { Rooms } from './rooms';
+import type { TlsOptions } from './security';
 import { buildRemote } from './mesh/teacup';
 import { buildManifest, createMeshControl } from './mesh/teapot';
 import type { MeshControl } from './http';
@@ -52,7 +53,7 @@ export interface MeshConfig {
   timeoutMs?: number;
 }
 
-export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record }): App {
+export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record; tls?: TlsOptions }): App {
   const bus = new Bus();
   const container = new Container();
   let server: http.Server | undefined;
@@ -358,7 +359,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
         },
       }));
 
-    server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams });
+    server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams, tls: opts.tls });
     server.on('close', () => { for (const l of meshLinks) { try { l.close(); } catch { /* */ } } });
     await new Promise((resolve) => server!.listen(port, resolve));
     return server;
diff --git a/src/http.ts b/src/http.ts
index adf4252..6ab2874 100644
--- a/src/http.ts
+++ b/src/http.ts
@@ -1,4 +1,5 @@
 import http from 'http';
+import https from 'https';
 import { once } from 'events';
 import { channel } from './channel';
 import { errorToResponse } from './transformers';
@@ -7,6 +8,7 @@ import { sseEncoder, ndjsonEncoder, StreamEncoder } from './encoders';
 import { isStreamResult, type PipelineResult, type ResponseShape } from './pipeline';
 import type { Transport } from './metadata';
 import type { Bus } from './bus';
+import type { TlsOptions } from './security';
 
 export interface RequestLimits {
   maxBodyBytes?: number;       // default 1_000_000
@@ -14,7 +16,7 @@ export interface RequestLimits {
   headersTimeoutMs?: number;   // default 10_000
   keepAliveTimeoutMs?: number; // default 5_000
 }
-export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void> }
+export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void>; tls?: TlsOptions }
 
 export type RouteHandler = (req: {
   method: string; url: string;
@@ -186,7 +188,7 @@ export function createHttpServer(
   routes: RouteDef[], wsRoutes: WsRouteDef[] = [], bus?: Bus, meshControl?: MeshControl, opts?: HttpOptions,
 ): http.Server {
   const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000;
-  const server = http.createServer(async (req, res) => {
+  const handler = async (req: http.IncomingMessage, res: http.ServerResponse): Promise => {
     const url = req.url ?? '/';
     const path = url.split('?')[0];
     const matched = matchRoute(routes, req.method ?? 'GET', path);
@@ -233,7 +235,11 @@ export function createHttpServer(
     const r: ResponseShape = result;
     res.writeHead(r.status, r.headers);
     res.end(r.body);
-  });
+  };
+  // runtime-compatible; only @types differ (https.Server lacks the http-only timeout props)
+  const server: http.Server = (opts?.tls
+    ? https.createServer(opts.tls as https.ServerOptions, handler)
+    : http.createServer(handler)) as unknown as http.Server;
   server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000;
   server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000;
   server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000;
diff --git a/test/fixtures/cert.pem b/test/fixtures/cert.pem
new file mode 100644
index 0000000..5131dca
--- /dev/null
+++ b/test/fixtures/cert.pem
@@ -0,0 +1,19 @@
+-----BEGIN CERTIFICATE-----
+MIIDJTCCAg2gAwIBAgIUK+VdG3SgV5CP0vc6Yg0JETvNuHYwDQYJKoZIhvcNAQEL
+BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTI2MDcwNjIzNTcwOVoXDTM2MDcw
+MzIzNTcwOVowFDESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEF
+AAOCAQ8AMIIBCgKCAQEAud6rNrdOg8RgXNb1Kw/94JgUvrVm/5dmaq81/TwHeeRc
+1AIzj3rJk8KM/ZyHr8FtY0BUMrvun29hQO4F0kV7EOBu8jk/vmu+QscCjwIjpG3U
+BidYqa7dQay2R8RJVn4knr0bi6/IYYCrUZY+NTHRGbX9saX7DaLePSivmKfO4bsp
+2TpOkYWCqACeEs0XqIGvsOo7XpX5CYllr5uXz3iqP2P8/FUWXYC/NtwWXuL5Gefj
+4ltmyx7z0cFpQ9bOu6/z7VvMMHi3tM+HWHKZF29H/q8MeIThp1LWwD4GcSBV+idI
+fo3waL0utB0xHMZj2Jt9SA11NnyrDyIj7ShuO1BeOQIDAQABo28wbTAdBgNVHQ4E
+FgQU9sWqlq9NwCrJSgrOvJhNNBFzg90wHwYDVR0jBBgwFoAU9sWqlq9NwCrJSgrO
+vJhNNBFzg90wDwYDVR0TAQH/BAUwAwEB/zAaBgNVHREEEzARgglsb2NhbGhvc3SH
+BH8AAAEwDQYJKoZIhvcNAQELBQADggEBAKgkHesXrvwiucQi/0cVFvt3KH/OGfif
+gqNJvuVxnMPMMWe74ANcd5eOF9YDMjrxEfd2jMKtP0F0EXevLnI94ugQ5FRMJaIp
+laj2On0rNhxVt+nSWSP4mqj0Sp1lIRGzqz46+vnKZnydM4Q8kgzfwwQeXTMrOgMa
+ppxWNg+6gnDz1wEvO66M3eLxyaVMO8CFbzs1vahUANMi1lwa8BZiwRx5jhcIFOlh
+e4gdHPIFQcomuJX75LRry+OEnFOmHGyK1eYs8sT9D9F+TmJHVA51qvp3v7KRdxBS
+wGWh9ghqzXnyfyCkQgpxJfLJgAMR5j91IGXpSJg5D1ISXyLeqooCyw8=
+-----END CERTIFICATE-----
diff --git a/test/fixtures/key.pem b/test/fixtures/key.pem
new file mode 100644
index 0000000..278d9ad
--- /dev/null
+++ b/test/fixtures/key.pem
@@ -0,0 +1,28 @@
+-----BEGIN PRIVATE KEY-----
+MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC53qs2t06DxGBc
+1vUrD/3gmBS+tWb/l2ZqrzX9PAd55FzUAjOPesmTwoz9nIevwW1jQFQyu+6fb2FA
+7gXSRXsQ4G7yOT++a75CxwKPAiOkbdQGJ1iprt1BrLZHxElWfiSevRuLr8hhgKtR
+lj41MdEZtf2xpfsNot49KK+Yp87huynZOk6RhYKoAJ4SzReoga+w6jtelfkJiWWv
+m5fPeKo/Y/z8VRZdgL823BZe4vkZ5+PiW2bLHvPRwWlD1s67r/PtW8wweLe0z4dY
+cpkXb0f+rwx4hOGnUtbAPgZxIFX6J0h+jfBovS60HTEcxmPYm31IDXU2fKsPIiPt
+KG47UF45AgMBAAECggEAASvLkTLFTPQRNbHesGivd+QKvhXcrNpqboclPwUgY0P3
+/Wz4dVxicJV5TRrDScKdUBKxGnMP1+jRfcwndLxJKswjNCWosWgyi29UueEbUjdP
+7pb+X8P73bn7GbIn/SJv1CE1uc2qefTKf4nZC/2WR0Qb3FaYTEJyWy51BsWd5Sha
+4XfUzHBldJdZcELCBtwQFJWnqpc1qlnn4Uj9nmD+n7q5t54jqaa67qDhqDScU4DH
+nguXuH+Cb1zWGsKfoOc//jGWZKX3FJ6nKLHhh4QxxJa/A0VIoqf2lHDfKiJNUqMl
+BLq78MiFD1SnPXp/024EtEpC5KAS9oSHRusEmDbgAQKBgQDy6j5h9fgI5Bnxjv+E
++ASagBSYN4+mszHvZVXtXAl8OZVXkHUKoaco5IPe4/Ysg7WTPVAQAggtbqq/QE15
+S1sQZyPBmr2ewqQHKNJHMsB0u9AlXOHK3DHVq3+6kM7RGeuuWDvycsM2KHV9pUtA
+rIg1aMc9NGMkCsaQT2lJeyTOOQKBgQDD4cgK0a4XCot3fW4FaofDUE69TDJwk0Me
+IneH0BpK3iuSqS/mqjH8ZV6Z5lNVopUGGObnwLtEHZX8q2jakBPa7mCYnulnAsO9
+WTEZ5oHoN3Gr8O7WJW4LoOOIeci8qPiz58CazhBjK+Qa6/C+rRN0u5hbG3zTEAoS
+vsjMDYgQAQKBgC8P1OAzwEcwshoLo1OGnZW1RMgs04bvZrhDwL8Iusm3ekiJszNJ
+GFKi2y2eqr37En2hPlarnhv3OdttwNTEFbN62AGVUjFk8lR0wzCKE6FKFcx3T0N3
+H6yO2mMx1O/L/s47R/nz5AAlHIYoNQklpAn878Ta1m5QLCIfUH2s/vd5AoGBAL01
+9i6FNj2pgOiOL11p9vQyOaze0oYtqZKNRprY6NzS2JIVfWC5nAkqvgO5GVxJ7Ntz
+6G+KmxmD3qKvzFv6+kLrKkGiluBbKkpXwnc7UtbF37Zvx7TxeOggpEjrIn0iVwIo
+5cJjNC8ncXKT3/u/YWDL6LJwzdVu09whkAKTO5ABAoGBANGHFvW/LCn0R24Xk2lF
+tFXsj2M5TqjqEeAa37doHPsUx2Bvp/YTpkA6sRKzlHcfyEC/gUKjNaEjIil5836P
+qjd7abz8xF7STS+9SzGDBEbjKk/IRrBjcYEh9x6kGWqnN6w4wXHsoZyMi/zSP/OG
+KPTzBQvDzHuVu5n+/a7izTeb
+-----END PRIVATE KEY-----
diff --git a/test/helpers/tls.ts b/test/helpers/tls.ts
new file mode 100644
index 0000000..95f5cf5
--- /dev/null
+++ b/test/helpers/tls.ts
@@ -0,0 +1,9 @@
+import { readFileSync } from 'fs';
+import { join } from 'path';
+
+const dir = join(__dirname, '..', 'fixtures');
+
+export const selfSignedTls = () => ({
+  key: readFileSync(join(dir, 'key.pem')),
+  cert: readFileSync(join(dir, 'cert.pem')),
+});
diff --git a/test/transport-security.test.ts b/test/transport-security.test.ts
new file mode 100644
index 0000000..1372f59
--- /dev/null
+++ b/test/transport-security.test.ts
@@ -0,0 +1,49 @@
+import { describe, it, expect, afterEach } from 'vitest';
+import https from 'https';
+import WebSocket from 'ws';
+import { createApp, Route, Get, Ws, Module, inbound, channel } from '../src';
+import { selfSignedTls } from './helpers/tls';
+
+@Route('/')
+class Api {
+  @Get('/ping') ping() { return { ok: true }; }
+  @Ws('/echo') echo(@inbound() msgs: AsyncIterable) {
+    const out = channel();
+    (async () => { for await (const m of msgs) out.push(m); })();
+    return out;
+  }
+}
+
+@Module({ mountpoint: '/', controllers: [Api] })
+class ApiModule {}
+
+let app: any;
+afterEach(async () => { await app?.close(); });
+
+describe('TLS', () => {
+  it('serves https', async () => {
+    app = createApp({ modules: [ApiModule], tls: selfSignedTls() });
+    const server = await app.listen(0);
+    const port = (server.address() as any).port;
+    const body = await new Promise((resolve, reject) => {
+      https.get({ port, path: '/ping', rejectUnauthorized: false }, (res) => {
+        let d = ''; res.on('data', (c) => (d += c)); res.on('end', () => resolve(d));
+      }).on('error', reject);
+    });
+    expect(JSON.parse(body)).toEqual({ ok: true });
+  });
+
+  it('upgrades wss on the same server', async () => {
+    app = createApp({ modules: [ApiModule], tls: selfSignedTls() });
+    const server = await app.listen(0);
+    const port = (server.address() as any).port;
+    const ws = new WebSocket(`wss://127.0.0.1:${port}/echo`, { rejectUnauthorized: false });
+    const got = await new Promise((resolve, reject) => {
+      ws.on('open', () => ws.send('hi'));
+      ws.on('message', (d) => resolve(d.toString()));
+      ws.on('error', reject);
+    });
+    expect(got).toBe('hi');
+    ws.close();
+  });
+});

From 0dba41606a3c7268e450df49fc2cad2550ac5404 Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Mon, 6 Jul 2026 19:02:11 -0500
Subject: [PATCH 046/139] feat(http): trustProxy + ctx.protocol/ctx.ip from
 socket or X-Forwarded-*

Signed-off-by: Diego Resendez 
---
 src/app.ts                      | 11 +++++++----
 src/http.ts                     | 20 +++++++++++++++++++-
 test/transport-security.test.ts | 24 +++++++++++++++++++++++-
 3 files changed, 49 insertions(+), 6 deletions(-)

diff --git a/src/app.ts b/src/app.ts
index 02b9fad..d41aba1 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -53,7 +53,7 @@ export interface MeshConfig {
   timeoutMs?: number;
 }
 
-export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record; tls?: TlsOptions }): App {
+export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record; tls?: TlsOptions; trustProxy?: boolean }): App {
   const bus = new Bus();
   const container = new Container();
   let server: http.Server | undefined;
@@ -324,7 +324,8 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
             const provided = await providedSeed(plan);
             return runPipeline({
               steps: planSteps(plan), handler: plan.run, transformer: plan.transformer, bus,
-              seed: { ...provided, req, params: req.params, query: req.query, body: req.body, headers: req.headers },
+              seed: { ...provided, req, params: req.params, query: req.query, body: req.body, headers: req.headers,
+                      protocol: req.protocol, ip: req.ip },
             });
           },
         })),
@@ -350,8 +351,10 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
         pattern: plan.pattern,
         open: async ({ params, inbound, abort, req }) => {
           const provided = await providedSeed(plan);
+          // ws upgrades come in on the raw Node req; trustProxy derivation for ws is out of scope here
           let ctx: any = { ...provided, req, params, query: parseQuery(req.url ?? ''), body: undefined,
-                           headers: req.headers, inbound, abort };
+                           headers: req.headers, inbound, abort,
+                           protocol: (req.socket as any).encrypted ? 'https' : 'http', ip: req.socket.remoteAddress ?? '' };
           for (const s of planSteps(plan)) { ctx = { ...ctx, ...(await s.run(ctx)) }; }
           const out = plan.run(ctx);
           if (!isAsyncIterable(out)) throw new Error(`@Ws handler '${plan.handlerName}' must return an AsyncIterable`);
@@ -359,7 +362,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
         },
       }));
 
-    server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams, tls: opts.tls });
+    server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams, tls: opts.tls, trustProxy: opts.trustProxy });
     server.on('close', () => { for (const l of meshLinks) { try { l.close(); } catch { /* */ } } });
     await new Promise((resolve) => server!.listen(port, resolve));
     return server;
diff --git a/src/http.ts b/src/http.ts
index 6ab2874..345815b 100644
--- a/src/http.ts
+++ b/src/http.ts
@@ -16,7 +16,7 @@ export interface RequestLimits {
   headersTimeoutMs?: number;   // default 10_000
   keepAliveTimeoutMs?: number; // default 5_000
 }
-export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void>; tls?: TlsOptions }
+export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void>; tls?: TlsOptions; trustProxy?: boolean }
 
 export type RouteHandler = (req: {
   method: string; url: string;
@@ -24,6 +24,8 @@ export type RouteHandler = (req: {
   params: Record;
   query: Record;
   body: unknown;
+  protocol: 'http' | 'https';
+  ip: string;
 }) => Promise;
 
 export interface RouteDef { method: string; pattern: string; transport: Transport; handler: RouteHandler }
@@ -82,6 +84,19 @@ async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promis
   return raw === '' ? undefined : raw;
 }
 
+function firstToken(v: string | string[] | undefined): string | undefined {
+  const s = Array.isArray(v) ? v[0] : v;
+  return s?.split(',')[0].trim();
+}
+function deriveSecure(req: http.IncomingMessage, trustProxy: boolean): boolean {
+  if (trustProxy) { const p = firstToken(req.headers['x-forwarded-proto']); if (p) return p === 'https'; }
+  return (req.socket as any).encrypted === true;
+}
+function deriveIp(req: http.IncomingMessage, trustProxy: boolean): string {
+  if (trustProxy) { const f = firstToken(req.headers['x-forwarded-for']); if (f) return f; }
+  return req.socket.remoteAddress ?? '';
+}
+
 function pickEncoder(transport: Transport, accept: string): StreamEncoder {
   if (transport === 'sse') return sseEncoder;
   if (transport === 'ndjson') return ndjsonEncoder;
@@ -218,11 +233,14 @@ export function createHttpServer(
     } else if (raw !== undefined && ct.includes('application/x-www-form-urlencoded')) {
       body = Object.fromEntries(new URLSearchParams(raw));
     }
+    const trustProxy = opts?.trustProxy ?? false;
+    const secure = deriveSecure(req, trustProxy);
     let result: PipelineResult;
     try {
       result = await matched.def.handler({
         method: req.method ?? 'GET', url, headers: req.headers,
         params: matched.params, query: parseQuery(url), body,
+        protocol: secure ? 'https' : 'http', ip: deriveIp(req, trustProxy),
       });
     } catch (error) {
       result = errorToResponse(error);
diff --git a/test/transport-security.test.ts b/test/transport-security.test.ts
index 1372f59..19c0138 100644
--- a/test/transport-security.test.ts
+++ b/test/transport-security.test.ts
@@ -1,7 +1,7 @@
 import { describe, it, expect, afterEach } from 'vitest';
 import https from 'https';
 import WebSocket from 'ws';
-import { createApp, Route, Get, Ws, Module, inbound, channel } from '../src';
+import { createApp, Route, Get, Ws, Module, inbound, channel, ctx } from '../src';
 import { selfSignedTls } from './helpers/tls';
 
 @Route('/')
@@ -47,3 +47,25 @@ describe('TLS', () => {
     ws.close();
   });
 });
+
+describe('trustProxy', () => {
+  it('trustProxy honors X-Forwarded-Proto; ctx exposes protocol/ip', async () => {
+    @Route('/') class P { @Get('/who') who(@ctx() c: any) { return { proto: c.protocol, ip: c.ip }; } }
+    @Module({ mountpoint: '/', controllers: [P] }) class PMod {}
+    app = createApp({ modules: [PMod], trustProxy: true });
+    const server = await app.listen(0);
+    const port = (server.address() as any).port;
+    const r = await fetch(`http://127.0.0.1:${port}/who`, {
+      headers: { 'x-forwarded-proto': 'https', 'x-forwarded-for': '9.9.9.9' } });
+    expect(await r.json()).toEqual({ proto: 'https', ip: '9.9.9.9' });
+  });
+  it('without trustProxy, forwarded headers are ignored', async () => {
+    @Route('/') class P { @Get('/who') who(@ctx() c: any) { return { proto: c.protocol }; } }
+    @Module({ mountpoint: '/', controllers: [P] }) class PMod {}
+    app = createApp({ modules: [PMod] });
+    const server = await app.listen(0);
+    const port = (server.address() as any).port;
+    const r = await fetch(`http://127.0.0.1:${port}/who`, { headers: { 'x-forwarded-proto': 'https' } });
+    expect(await r.json()).toEqual({ proto: 'http' });
+  });
+});

From 04da79721f97fe848254e34a4ca749c609e02971 Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Mon, 6 Jul 2026 19:06:58 -0500
Subject: [PATCH 047/139] feat(http): inject security headers on every response
 via writeHead patch

Signed-off-by: Diego Resendez 
---
 src/app.ts                      |  6 ++--
 src/http.ts                     | 24 ++++++++++---
 test/transport-security.test.ts | 62 ++++++++++++++++++++++++++++++++-
 3 files changed, 84 insertions(+), 8 deletions(-)

diff --git a/src/app.ts b/src/app.ts
index d41aba1..3f5e4af 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -14,7 +14,7 @@ import {
 import { getArgs, getHandlerNeeds, resolveArgs } from './params';
 import { connectLink, type Link } from './mesh/link';
 import { Rooms } from './rooms';
-import type { TlsOptions } from './security';
+import type { TlsOptions, SecurityOptions } from './security';
 import { buildRemote } from './mesh/teacup';
 import { buildManifest, createMeshControl } from './mesh/teapot';
 import type { MeshControl } from './http';
@@ -53,7 +53,7 @@ export interface MeshConfig {
   timeoutMs?: number;
 }
 
-export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record; tls?: TlsOptions; trustProxy?: boolean }): App {
+export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions }): App {
   const bus = new Bus();
   const container = new Container();
   let server: http.Server | undefined;
@@ -362,7 +362,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
         },
       }));
 
-    server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams, tls: opts.tls, trustProxy: opts.trustProxy });
+    server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams, tls: opts.tls, trustProxy: opts.trustProxy, security: opts.security ?? true });
     server.on('close', () => { for (const l of meshLinks) { try { l.close(); } catch { /* */ } } });
     await new Promise((resolve) => server!.listen(port, resolve));
     return server;
diff --git a/src/http.ts b/src/http.ts
index 345815b..9f67fc9 100644
--- a/src/http.ts
+++ b/src/http.ts
@@ -8,7 +8,8 @@ import { sseEncoder, ndjsonEncoder, StreamEncoder } from './encoders';
 import { isStreamResult, type PipelineResult, type ResponseShape } from './pipeline';
 import type { Transport } from './metadata';
 import type { Bus } from './bus';
-import type { TlsOptions } from './security';
+import { buildSecurityHeaders, mergeVary } from './security';
+import type { TlsOptions, SecurityOptions } from './security';
 
 export interface RequestLimits {
   maxBodyBytes?: number;       // default 1_000_000
@@ -16,7 +17,7 @@ export interface RequestLimits {
   headersTimeoutMs?: number;   // default 10_000
   keepAliveTimeoutMs?: number; // default 5_000
 }
-export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void>; tls?: TlsOptions; trustProxy?: boolean }
+export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void>; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions }
 
 export type RouteHandler = (req: {
   method: string; url: string;
@@ -203,9 +204,26 @@ export function createHttpServer(
   routes: RouteDef[], wsRoutes: WsRouteDef[] = [], bus?: Bus, meshControl?: MeshControl, opts?: HttpOptions,
 ): http.Server {
   const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000;
+  const trustProxy = opts?.trustProxy ?? false;
   const handler = async (req: http.IncomingMessage, res: http.ServerResponse): Promise => {
     const url = req.url ?? '/';
     const path = url.split('?')[0];
+    // Install the security-header patch BEFORE any routing/response so every path
+    // (200, 404, error, stream) writes headers through the same patched writeHead.
+    const secure = deriveSecure(req, trustProxy);
+    const injected: Record = { ...buildSecurityHeaders(opts?.security ?? true, secure) };
+    // (CORS is folded into `injected` in Task 5; this task is security headers only.)
+    const orig = res.writeHead.bind(res);
+    (res as any).writeHead = (status: number, arg2?: any, arg3?: any) => {
+      // normalize (statusMessage?, headers?) overloads
+      const hdrs = (typeof arg2 === 'string' ? arg3 : arg2) as Record | undefined;
+      // injected LAST → CORS/security keys are authoritative (a handler cannot weaken them).
+      // Handler's non-injected headers (content-type, etc.) survive via ...hdrs.
+      const merged: Record = { ...(hdrs ?? {}), ...injected };
+      // Vary is list-valued: only merge when injected carries one (CORS active); else leave handler's Vary alone.
+      if (injected['vary']) merged['vary'] = mergeVary(hdrs?.['vary'], injected['vary']);
+      return typeof arg2 === 'string' ? orig(status, arg2, merged) : orig(status, merged);
+    };
     const matched = matchRoute(routes, req.method ?? 'GET', path);
     if (!matched) {
       res.writeHead(404, { 'content-type': 'application/json' });
@@ -233,8 +251,6 @@ export function createHttpServer(
     } else if (raw !== undefined && ct.includes('application/x-www-form-urlencoded')) {
       body = Object.fromEntries(new URLSearchParams(raw));
     }
-    const trustProxy = opts?.trustProxy ?? false;
-    const secure = deriveSecure(req, trustProxy);
     let result: PipelineResult;
     try {
       result = await matched.def.handler({
diff --git a/test/transport-security.test.ts b/test/transport-security.test.ts
index 19c0138..69b6b31 100644
--- a/test/transport-security.test.ts
+++ b/test/transport-security.test.ts
@@ -1,7 +1,7 @@
 import { describe, it, expect, afterEach } from 'vitest';
 import https from 'https';
 import WebSocket from 'ws';
-import { createApp, Route, Get, Ws, Module, inbound, channel, ctx } from '../src';
+import { createApp, Route, Get, Sse, Ws, Module, inbound, channel, ctx } from '../src';
 import { selfSignedTls } from './helpers/tls';
 
 @Route('/')
@@ -69,3 +69,63 @@ describe('trustProxy', () => {
     expect(await r.json()).toEqual({ proto: 'http' });
   });
 });
+
+describe('security headers', () => {
+  it('on 200, 404, error; HSTS only when secure', async () => {
+    @Route('/') class S {
+      @Get('/ok') ok() { return { a: 1 }; }
+      @Get('/boom') boom() { throw new Error('x'); }
+    }
+    @Module({ mountpoint: '/', controllers: [S] }) class SMod {}
+    app = createApp({ modules: [SMod] }); // security defaults on
+    const server = await app.listen(0);
+    const port = (server.address() as any).port;
+    const ok = await fetch(`http://127.0.0.1:${port}/ok`);
+    expect(ok.headers.get('x-content-type-options')).toBe('nosniff');
+    expect(ok.headers.get('strict-transport-security')).toBeNull(); // http, not secure
+    const nf = await fetch(`http://127.0.0.1:${port}/nope`);
+    expect(nf.status).toBe(404);
+    expect(nf.headers.get('x-frame-options')).toBe('SAMEORIGIN');
+    const boom = await fetch(`http://127.0.0.1:${port}/boom`);
+    expect(boom.status).toBe(500);
+    expect(boom.headers.get('x-content-type-options')).toBe('nosniff');
+  });
+
+  it('security:false emits none', async () => {
+    @Route('/') class S { @Get('/ok') ok() { return { a: 1 }; } }
+    @Module({ mountpoint: '/', controllers: [S] }) class SMod {}
+    app = createApp({ modules: [SMod], security: false });
+    const server = await app.listen(0);
+    const port = (server.address() as any).port;
+    const ok = await fetch(`http://127.0.0.1:${port}/ok`);
+    expect(ok.headers.get('x-content-type-options')).toBeNull();
+  });
+
+  it('HSTS present over https', async () => {
+    @Route('/') class S { @Get('/ok') ok() { return { a: 1 }; } }
+    @Module({ mountpoint: '/', controllers: [S] }) class SMod {}
+    app = createApp({ modules: [SMod], tls: selfSignedTls() });
+    const server = await app.listen(0);
+    const port = (server.address() as any).port;
+    const hsts = await new Promise((resolve, reject) => {
+      https.get({ port, path: '/ok', rejectUnauthorized: false }, (res) => {
+        res.resume();
+        resolve(res.headers['strict-transport-security'] as string | undefined);
+      }).on('error', reject);
+    });
+    expect(hsts).toContain('max-age=');
+  });
+
+  it('stream response carries security headers', async () => {
+    @Route('/') class S {
+      @Sse('/stream') async *stream() { yield 'a'; }
+    }
+    @Module({ mountpoint: '/', controllers: [S] }) class SMod {}
+    app = createApp({ modules: [SMod] });
+    const server = await app.listen(0);
+    const port = (server.address() as any).port;
+    const res = await fetch(`http://127.0.0.1:${port}/stream`, { headers: { accept: 'text/event-stream' } });
+    expect(res.headers.get('x-content-type-options')).toBe('nosniff');
+    await res.body?.cancel();
+  });
+});

From 09828734625116186fd9d66004209bec9e8d5208 Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Mon, 6 Jul 2026 19:14:17 -0500
Subject: [PATCH 048/139] fix(http): make injected security/CORS headers
 authoritative over case-variant handler keys

Signed-off-by: Diego Resendez 
---
 src/http.ts                     | 19 ++++++++++++++-----
 test/transport-security.test.ts | 31 ++++++++++++++++++++++++++++++-
 2 files changed, 44 insertions(+), 6 deletions(-)

diff --git a/src/http.ts b/src/http.ts
index 9f67fc9..6abc63c 100644
--- a/src/http.ts
+++ b/src/http.ts
@@ -217,11 +217,20 @@ export function createHttpServer(
     (res as any).writeHead = (status: number, arg2?: any, arg3?: any) => {
       // normalize (statusMessage?, headers?) overloads
       const hdrs = (typeof arg2 === 'string' ? arg3 : arg2) as Record | undefined;
-      // injected LAST → CORS/security keys are authoritative (a handler cannot weaken them).
-      // Handler's non-injected headers (content-type, etc.) survive via ...hdrs.
-      const merged: Record = { ...(hdrs ?? {}), ...injected };
-      // Vary is list-valued: only merge when injected carries one (CORS active); else leave handler's Vary alone.
-      if (injected['vary']) merged['vary'] = mergeVary(hdrs?.['vary'], injected['vary']);
+      // injected (security/CORS) is authoritative. Node's writeHead does NOT dedupe case-variant
+      // keys — both lines would ship and a browser honors the first — so drop any handler header
+      // whose name case-insensitively collides with an injected one before merging.
+      const merged: Record = {};
+      const injectedLower = new Set(Object.keys(injected).map((k) => k.toLowerCase()));
+      let handlerVary: string | undefined;
+      if (hdrs) for (const k of Object.keys(hdrs)) {
+        const lk = k.toLowerCase();
+        if (lk === 'vary') { handlerVary = hdrs[k]; continue; }        // merged separately below
+        if (!injectedLower.has(lk)) merged[k] = hdrs[k];
+      }
+      Object.assign(merged, injected);
+      if (injected['vary']) merged['vary'] = mergeVary(handlerVary, injected['vary']);
+      else if (handlerVary !== undefined) merged['vary'] = handlerVary; // preserve handler Vary when no CORS
       return typeof arg2 === 'string' ? orig(status, arg2, merged) : orig(status, merged);
     };
     const matched = matchRoute(routes, req.method ?? 'GET', path);
diff --git a/test/transport-security.test.ts b/test/transport-security.test.ts
index 69b6b31..043fc28 100644
--- a/test/transport-security.test.ts
+++ b/test/transport-security.test.ts
@@ -1,7 +1,7 @@
 import { describe, it, expect, afterEach } from 'vitest';
 import https from 'https';
 import WebSocket from 'ws';
-import { createApp, Route, Get, Sse, Ws, Module, inbound, channel, ctx } from '../src';
+import { createApp, Route, Get, Sse, Ws, Module, Transformer, inbound, channel, ctx } from '../src';
 import { selfSignedTls } from './helpers/tls';
 
 @Route('/')
@@ -116,6 +116,35 @@ describe('security headers', () => {
     expect(hsts).toContain('max-age=');
   });
 
+  it('injected header wins over a case-variant handler header (no double line)', async () => {
+    @Route('/') class S {
+      @Get('/sneaky')
+      @Transformer((v) => ({ status: 200, headers: { 'X-Content-Type-Options': 'SNIFF' }, body: JSON.stringify(v) }))
+      sneaky() { return { a: 1 }; }
+    }
+    @Module({ mountpoint: '/', controllers: [S] }) class SMod {}
+    app = createApp({ modules: [SMod] });
+    const server = await app.listen(0);
+    const port = (server.address() as any).port;
+    const res = await fetch(`http://127.0.0.1:${port}/sneaky`);
+    expect(res.headers.get('x-content-type-options')).toBe('nosniff'); // NOT 'SNIFF, nosniff'
+  });
+
+  it("preserves a handler's Title-Case Vary when no CORS is configured", async () => {
+    @Route('/') class S {
+      @Get('/vary')
+      @Transformer((v) => ({ status: 200, headers: { Vary: 'Accept-Encoding' }, body: JSON.stringify(v) }))
+      vary() { return { a: 1 }; }
+    }
+    @Module({ mountpoint: '/', controllers: [S] }) class SMod {}
+    app = createApp({ modules: [SMod] });
+    const server = await app.listen(0);
+    const port = (server.address() as any).port;
+    const res = await fetch(`http://127.0.0.1:${port}/vary`);
+    expect(res.headers.get('vary')).toBe('Accept-Encoding');
+    expect(res.headers.get('x-content-type-options')).toBe('nosniff');
+  });
+
   it('stream response carries security headers', async () => {
     @Route('/') class S {
       @Sse('/stream') async *stream() { yield 'a'; }

From cb77216a53d1a59ae71a780c059fe4d3d969df09 Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Mon, 6 Jul 2026 19:16:48 -0500
Subject: [PATCH 049/139] feat(http): configurable CORS with guarded OPTIONS
 preflight

Signed-off-by: Diego Resendez 
---
 src/app.ts                      |  6 ++--
 src/http.ts                     | 16 ++++++---
 src/index.ts                    |  1 +
 test/transport-security.test.ts | 57 +++++++++++++++++++++++++++++++++
 4 files changed, 73 insertions(+), 7 deletions(-)

diff --git a/src/app.ts b/src/app.ts
index 3f5e4af..ecc64fb 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -14,7 +14,7 @@ import {
 import { getArgs, getHandlerNeeds, resolveArgs } from './params';
 import { connectLink, type Link } from './mesh/link';
 import { Rooms } from './rooms';
-import type { TlsOptions, SecurityOptions } from './security';
+import type { TlsOptions, SecurityOptions, CorsOptions } from './security';
 import { buildRemote } from './mesh/teacup';
 import { buildManifest, createMeshControl } from './mesh/teapot';
 import type { MeshControl } from './http';
@@ -53,7 +53,7 @@ export interface MeshConfig {
   timeoutMs?: number;
 }
 
-export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions }): App {
+export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions; cors?: CorsOptions }): App {
   const bus = new Bus();
   const container = new Container();
   let server: http.Server | undefined;
@@ -362,7 +362,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
         },
       }));
 
-    server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams, tls: opts.tls, trustProxy: opts.trustProxy, security: opts.security ?? true });
+    server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams, tls: opts.tls, trustProxy: opts.trustProxy, security: opts.security ?? true, cors: opts.cors });
     server.on('close', () => { for (const l of meshLinks) { try { l.close(); } catch { /* */ } } });
     await new Promise((resolve) => server!.listen(port, resolve));
     return server;
diff --git a/src/http.ts b/src/http.ts
index 6abc63c..abc83a5 100644
--- a/src/http.ts
+++ b/src/http.ts
@@ -8,8 +8,8 @@ import { sseEncoder, ndjsonEncoder, StreamEncoder } from './encoders';
 import { isStreamResult, type PipelineResult, type ResponseShape } from './pipeline';
 import type { Transport } from './metadata';
 import type { Bus } from './bus';
-import { buildSecurityHeaders, mergeVary } from './security';
-import type { TlsOptions, SecurityOptions } from './security';
+import { buildSecurityHeaders, mergeVary, resolveCors, corsPreflightHeaders } from './security';
+import type { TlsOptions, SecurityOptions, CorsOptions } from './security';
 
 export interface RequestLimits {
   maxBodyBytes?: number;       // default 1_000_000
@@ -17,7 +17,7 @@ export interface RequestLimits {
   headersTimeoutMs?: number;   // default 10_000
   keepAliveTimeoutMs?: number; // default 5_000
 }
-export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void>; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions }
+export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void>; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions; cors?: CorsOptions }
 
 export type RouteHandler = (req: {
   method: string; url: string;
@@ -212,7 +212,6 @@ export function createHttpServer(
     // (200, 404, error, stream) writes headers through the same patched writeHead.
     const secure = deriveSecure(req, trustProxy);
     const injected: Record = { ...buildSecurityHeaders(opts?.security ?? true, secure) };
-    // (CORS is folded into `injected` in Task 5; this task is security headers only.)
     const orig = res.writeHead.bind(res);
     (res as any).writeHead = (status: number, arg2?: any, arg3?: any) => {
       // normalize (statusMessage?, headers?) overloads
@@ -233,6 +232,15 @@ export function createHttpServer(
       else if (handlerVary !== undefined) merged['vary'] = handlerVary; // preserve handler Vary when no CORS
       return typeof arg2 === 'string' ? orig(status, arg2, merged) : orig(status, merged);
     };
+    // CORS is added to `injected` AFTER the patch is installed — the patch reads it lazily
+    // by reference at writeHead time, so keys added here still land on every response.
+    if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req));
+    if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) {
+      const pf = corsPreflightHeaders(opts.cors, req);
+      res.writeHead(204, pf);
+      res.end();
+      return;
+    }
     const matched = matchRoute(routes, req.method ?? 'GET', path);
     if (!matched) {
       res.writeHead(404, { 'content-type': 'application/json' });
diff --git a/src/index.ts b/src/index.ts
index cbaa2e0..28cf546 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -24,6 +24,7 @@ export { sseEncoder, ndjsonEncoder } from './encoders';
 export type { StreamEncoder } from './encoders';
 export type { MeshConfig } from './app';
 export type { RequestLimits } from './http';
+export type { TlsOptions, CorsOptions, SecurityOptions } from './security';
 export { connectLink } from './mesh/link';
 export { buildRemote, envelopeFrom } from './mesh/teacup';
 export { buildManifest, createMeshControl, MESH_CONTROL_PATH } from './mesh/teapot';
diff --git a/test/transport-security.test.ts b/test/transport-security.test.ts
index 043fc28..7f880d9 100644
--- a/test/transport-security.test.ts
+++ b/test/transport-security.test.ts
@@ -158,3 +158,60 @@ describe('security headers', () => {
     await res.body?.cancel();
   });
 });
+
+describe('CORS', () => {
+  it('echoes allowed origin, sets Vary; preflight 204', async () => {
+    @Route('/') class C { @Get('/x') x() { return { ok: 1 }; } }
+    @Module({ mountpoint: '/', controllers: [C] }) class CMod {}
+    app = createApp({ modules: [CMod], cors: { origins: 'https://a.com' } });
+    const server = await app.listen(0);
+    const port = (server.address() as any).port;
+    const r = await fetch(`http://127.0.0.1:${port}/x`, { headers: { origin: 'https://a.com' } });
+    expect(r.headers.get('access-control-allow-origin')).toBe('https://a.com');
+    expect(r.headers.get('vary')).toContain('Origin');
+    const pre = await fetch(`http://127.0.0.1:${port}/x`, {
+      method: 'OPTIONS', headers: { origin: 'https://a.com', 'access-control-request-method': 'GET' } });
+    expect(pre.status).toBe(204);
+    expect(pre.headers.get('access-control-allow-methods')).toContain('GET');
+    expect(pre.headers.get('x-content-type-options')).toBe('nosniff'); // security headers on preflight too
+  });
+
+  it('credentials never returns *; echoes concrete origin', async () => {
+    @Route('/') class C { @Get('/x') x() { return { ok: 1 }; } }
+    @Module({ mountpoint: '/', controllers: [C] }) class CMod {}
+    app = createApp({ modules: [CMod], cors: { origins: '*', credentials: true } });
+    const server = await app.listen(0);
+    const port = (server.address() as any).port;
+    const r = await fetch(`http://127.0.0.1:${port}/x`, { headers: { origin: 'https://a.com' } });
+    expect(r.headers.get('access-control-allow-origin')).toBe('https://a.com');
+    expect(r.headers.get('access-control-allow-credentials')).toBe('true');
+  });
+
+  it('disallowed origin → no allow-origin; bare OPTIONS (no ACRM) falls through to 404', async () => {
+    @Route('/') class C { @Get('/x') x() { return { ok: 1 }; } }
+    @Module({ mountpoint: '/', controllers: [C] }) class CMod {}
+    app = createApp({ modules: [CMod], cors: { origins: 'https://a.com' } });
+    const server = await app.listen(0);
+    const port = (server.address() as any).port;
+    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();
+    const bare = await fetch(`http://127.0.0.1:${port}/x`, { method: 'OPTIONS' }); // no ACRM
+    expect(bare.status).toBe(404);
+  });
+
+  it("merges a handler's Title-Case Vary with CORS's Origin", async () => {
+    @Route('/') class C {
+      @Get('/x')
+      @Transformer((v) => ({ status: 200, headers: { Vary: 'Accept-Encoding' }, body: JSON.stringify(v) }))
+      x() { return { ok: 1 }; }
+    }
+    @Module({ mountpoint: '/', controllers: [C] }) class CMod {}
+    app = createApp({ modules: [CMod], cors: { origins: 'https://a.com' } });
+    const server = await app.listen(0);
+    const port = (server.address() as any).port;
+    const r = await fetch(`http://127.0.0.1:${port}/x`, { headers: { origin: 'https://a.com' } });
+    const vary = r.headers.get('vary');
+    expect(vary).toContain('Accept-Encoding');
+    expect(vary).toContain('Origin');
+  });
+});

From 258130bf3039c94ffa495a4bdea284de5299c242 Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Mon, 6 Jul 2026 19:20:34 -0500
Subject: [PATCH 050/139] docs: transport security (TLS/wss, trustProxy, CORS,
 security headers)

Signed-off-by: Diego Resendez 
---
 docs/quickstart.md | 79 ++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 79 insertions(+)

diff --git a/docs/quickstart.md b/docs/quickstart.md
index 552729c..2f0a365 100644
--- a/docs/quickstart.md
+++ b/docs/quickstart.md
@@ -228,6 +228,85 @@ 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) |
+
 ## Inspect & test the graph
 
 ### Visualize with Mermaid

From 0f7932c69667656abe089197a9e5da5af4cf61f7 Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Mon, 6 Jul 2026 20:07:32 -0500
Subject: [PATCH 051/139] feat(multipart): pure binary-safe multipart/form-data
 parser

Signed-off-by: Diego Resendez 
---
 src/multipart.ts       | 112 +++++++++++++++++++++++++++++++++++++++++
 test/multipart.test.ts |  82 ++++++++++++++++++++++++++++++
 2 files changed, 194 insertions(+)
 create mode 100644 src/multipart.ts
 create mode 100644 test/multipart.test.ts

diff --git a/src/multipart.ts b/src/multipart.ts
new file mode 100644
index 0000000..e4315b5
--- /dev/null
+++ b/src/multipart.ts
@@ -0,0 +1,112 @@
+// src/multipart.ts — pure, binary-safe multipart/form-data parser. No server deps.
+export interface UploadedFile { filename: string; contentType: string; data: Buffer; size: number }
+export interface MultipartBody {
+  fields: Record;
+  files: Record;
+}
+export interface MultipartOpts { maxParts: number; duplicates: 'array' | 'last' }
+
+const CRLF = Buffer.from('\r\n');
+
+// boundary token from a Content-Type value; supports quoted form.
+export function extractBoundary(contentType: string): string | undefined {
+  const m = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(contentType);
+  const b = (m?.[1] ?? m?.[2])?.trim();
+  return b || undefined;
+}
+
+// order-independent, quoted-or-unquoted param lookup within a header value.
+// The `(?:^|[;\s])` prefix anchors the key to a param boundary so `name=` does NOT
+// match the tail of `filename=`, and `filename=` does not match `filename*=`.
+function param(header: string, key: string): string | undefined {
+  const q = new RegExp(`(?:^|[;\\s])${key}="([^"]*)"`, 'i').exec(header);
+  if (q) return q[1];
+  const u = new RegExp(`(?:^|[;\\s])${key}=([^";]+)`, 'i').exec(header);
+  return u ? u[1].trim() : undefined;
+}
+
+function addField(fields: MultipartBody['fields'], name: string, value: string, dup: 'array' | 'last'): void {
+  if (dup === 'array') {
+    const ex = fields[name];
+    if (Array.isArray(ex)) ex.push(value);
+    else fields[name] = [value];
+  } else {
+    fields[name] = value; // last-wins
+  }
+}
+
+function addFile(files: MultipartBody['files'], name: string, file: UploadedFile): void {
+  const ex = files[name];
+  if (ex === undefined) files[name] = file;
+  else if (Array.isArray(ex)) ex.push(file);
+  else files[name] = [ex, file];
+}
+
+// Find the next REAL delimiter at/after `from`: a `\r\n--boundary` occurrence that is
+// followed by `\r\n` (a part) or `--` (the terminator). This skips false hits where the
+// exact `\r\n--boundary` byte sequence appears INSIDE a file body — the data-integrity case.
+function findDelim(buf: Buffer, delim: Buffer, from: number): number {
+  let i = buf.indexOf(delim, from);
+  while (i !== -1) {
+    const a = i + delim.length;
+    if ((buf[a] === 0x0d && buf[a + 1] === 0x0a) || (buf[a] === 0x2d && buf[a + 1] === 0x2d)) return i;
+    i = buf.indexOf(delim, i + delim.length); // false hit inside a body — keep searching
+  }
+  return -1;
+}
+
+export function parseMultipart(raw: Buffer, boundary: string, opts: MultipartOpts): MultipartBody {
+  const fields: MultipartBody['fields'] = {};
+  const files: MultipartBody['files'] = {};
+  const delim = Buffer.concat([CRLF, Buffer.from(`--${boundary}`)]); // \r\n--boundary
+  // Normalize: prepend CRLF so the FIRST boundary (which a browser sends with no
+  // leading CRLF) is also preceded by the delimiter and isn't dropped as preamble.
+  const buf = Buffer.concat([CRLF, raw]);
+
+  let pos = findDelim(buf, delim, 0);
+  if (pos === -1) throw new Error('Invalid multipart body');
+  let count = 0;
+  while (true) {
+    let start = pos + delim.length;
+    // terminator "--" immediately after the boundary → done
+    if (buf[start] === 0x2d && buf[start + 1] === 0x2d) break;
+    // skip the CRLF that ends the boundary line
+    if (buf[start] === 0x0d && buf[start + 1] === 0x0a) start += 2;
+    const next = findDelim(buf, delim, start);
+    if (next === -1) throw new Error('Invalid multipart body');
+    if (++count > opts.maxParts) throw new Error('Invalid multipart body');
+    const part = buf.subarray(start, next);
+    const sep = part.indexOf('\r\n\r\n');
+    if (sep === -1) throw new Error('Invalid multipart body');
+    const headerText = part.subarray(0, sep).toString('utf8');
+    const partBody = part.subarray(sep + 4);
+
+    let disposition = '';
+    let contentType = '';
+    for (const line of headerText.split('\r\n')) {
+      const c = line.indexOf(':');
+      if (c === -1) continue;
+      const k = line.slice(0, c).trim().toLowerCase();
+      const v = line.slice(c + 1).trim();
+      if (k === 'content-disposition') disposition = v;
+      else if (k === 'content-type') contentType = v;
+    }
+
+    const name = param(disposition, 'name');
+    if (name === undefined) throw new Error('Invalid multipart body');
+    const filename = param(disposition, 'filename');
+    if (filename !== undefined) {
+      if (filename === '' && partBody.length === 0) { pos = next; continue; } // unselected file input
+      addFile(files, name, {
+        filename,
+        contentType: contentType || 'application/octet-stream',
+        data: Buffer.from(partBody), // copy out of the shared buffer
+        size: partBody.length,
+      });
+    } else {
+      addField(fields, name, partBody.toString('utf8'), opts.duplicates);
+    }
+    pos = next;
+  }
+  return { fields, files };
+}
diff --git a/test/multipart.test.ts b/test/multipart.test.ts
new file mode 100644
index 0000000..e90366c
--- /dev/null
+++ b/test/multipart.test.ts
@@ -0,0 +1,82 @@
+import { describe, it, expect } from 'vitest';
+import { parseMultipart, extractBoundary } from '../src/multipart';
+
+const B = 'X-BOUND';
+function body(parts: string[]): Buffer {
+  return Buffer.concat([
+    ...parts.map((p) => Buffer.from(`--${B}\r\n${p}\r\n`)),
+    Buffer.from(`--${B}--\r\n`),
+  ]);
+}
+const field = (name: string, val: string) => `Content-Disposition: form-data; name="${name}"\r\n\r\n${val}`;
+const file = (name: string, fn: string, ct: string, data: string) =>
+  `Content-Disposition: form-data; name="${name}"; filename="${fn}"\r\nContent-Type: ${ct}\r\n\r\n${data}`;
+const opts = { maxParts: 1000, duplicates: 'last' as const };
+
+describe('extractBoundary', () => {
+  it('plain and quoted', () => {
+    expect(extractBoundary('multipart/form-data; boundary=abc')).toBe('abc');
+    expect(extractBoundary('multipart/form-data; boundary="a b"')).toBe('a b');
+    expect(extractBoundary('multipart/form-data')).toBeUndefined();
+  });
+});
+
+describe('parseMultipart', () => {
+  it('single text field is NOT lost (first-part off-by-one guard)', () => {
+    const r = parseMultipart(body([field('title', 'hello')]), B, opts);
+    expect(r.fields.title).toBe('hello');
+  });
+  it('multiple distinct fields', () => {
+    const r = parseMultipart(body([field('a', '1'), field('b', '2')]), B, opts);
+    expect(r.fields).toEqual({ a: '1', b: '2' });
+  });
+  it("duplicates 'last' vs 'array'", () => {
+    const b = body([field('t', 'x'), field('t', 'y')]);
+    expect(parseMultipart(b, B, { maxParts: 1000, duplicates: 'last' }).fields.t).toBe('y');
+    expect(parseMultipart(b, B, { maxParts: 1000, duplicates: 'array' }).fields.t).toEqual(['x', 'y']);
+  });
+  it('single file: metadata + exact bytes incl. embedded CRLF and boundary-like text', () => {
+    const payload = 'ab\r\n--X-BOUNDnope\r\ncd';
+    const r = parseMultipart(body([file('doc', 'a.txt', 'text/plain', payload)]), B, opts);
+    const f = r.files.doc as any;
+    expect(f.filename).toBe('a.txt');
+    expect(f.contentType).toBe('text/plain');
+    expect(f.size).toBe(Buffer.byteLength(payload));
+    expect(f.data.toString()).toBe(payload);
+  });
+  it('multiple files same name → array', () => {
+    const r = parseMultipart(body([file('f', '1', 'text/plain', 'a'), file('f', '2', 'text/plain', 'b')]), B, opts);
+    expect(Array.isArray(r.files.f)).toBe(true);
+    expect((r.files.f as any).length).toBe(2);
+  });
+  it('mixed fields + files', () => {
+    const r = parseMultipart(body([field('name', 'joe'), file('avatar', 'p.png', 'image/png', 'PNG')]), B, opts);
+    expect(r.fields.name).toBe('joe');
+    expect((r.files.avatar as any).filename).toBe('p.png');
+  });
+  it('case-insensitive headers + filename-before-name (order independent)', () => {
+    const part = `content-disposition: form-data; filename="z.bin"; name="up"\r\ncontent-type: application/octet-stream\r\n\r\nDATA`;
+    const r = parseMultipart(body([part]), B, opts);
+    expect((r.files.up as any).filename).toBe('z.bin');
+  });
+  it('filename="" with empty body is skipped', () => {
+    const part = `Content-Disposition: form-data; name="up"; filename=""\r\n\r\n`;
+    const r = parseMultipart(body([part]), B, opts);
+    expect(r.files.up).toBeUndefined();
+  });
+  it('malformed → throws: no boundary present', () => {
+    expect(() => parseMultipart(Buffer.from('garbage'), B, opts)).toThrow();
+  });
+  it('malformed → throws: part without name', () => {
+    const part = `Content-Disposition: form-data\r\n\r\nx`;
+    expect(() => parseMultipart(body([part]), B, opts)).toThrow();
+  });
+  it('malformed → throws: part with no header/body separator', () => {
+    const raw = Buffer.from(`--${B}\r\nContent-Disposition: form-data; name="a"\r\n--${B}--\r\n`);
+    expect(() => parseMultipart(raw, B, opts)).toThrow();
+  });
+  it('parts over maxParts → throws', () => {
+    const b = body([field('a', '1'), field('b', '2'), field('c', '3')]);
+    expect(() => parseMultipart(b, B, { maxParts: 2, duplicates: 'last' })).toThrow();
+  });
+});

From 5808da8012536418562d00c0dcf91b92d9853c6d Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Mon, 6 Jul 2026 20:11:10 -0500
Subject: [PATCH 052/139] feat(http): parse multipart/form-data; readBody
 yields Buffer, text fallthrough preserved

Signed-off-by: Diego Resendez 
---
 src/http.ts                 | 38 +++++++++++++++++++--------
 test/multipart-http.test.ts | 52 +++++++++++++++++++++++++++++++++++++
 2 files changed, 79 insertions(+), 11 deletions(-)
 create mode 100644 test/multipart-http.test.ts

diff --git a/src/http.ts b/src/http.ts
index abc83a5..106b777 100644
--- a/src/http.ts
+++ b/src/http.ts
@@ -10,12 +10,14 @@ import type { Transport } from './metadata';
 import type { Bus } from './bus';
 import { buildSecurityHeaders, mergeVary, resolveCors, corsPreflightHeaders } from './security';
 import type { TlsOptions, SecurityOptions, CorsOptions } from './security';
+import { parseMultipart, extractBoundary } from './multipart';
 
 export interface RequestLimits {
   maxBodyBytes?: number;       // default 1_000_000
   requestTimeoutMs?: number;   // default 30_000
   headersTimeoutMs?: number;   // default 10_000
   keepAliveTimeoutMs?: number; // default 5_000
+  maxParts?: number;           // default 1000
 }
 export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void>; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions; cors?: CorsOptions }
 
@@ -72,7 +74,7 @@ export function parseQuery(url: string): Record {
   return out;
 }
 
-async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise {
+async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise {
   const chunks: Buffer[] = [];
   let total = 0;
   for await (const chunk of req) {
@@ -80,9 +82,7 @@ async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promis
     if (total > maxBodyBytes) throw new HttpError(413, 'Payload Too Large');
     chunks.push(chunk as Buffer);
   }
-  if (chunks.length === 0) return undefined;
-  const raw = Buffer.concat(chunks).toString('utf8');
-  return raw === '' ? undefined : raw;
+  return chunks.length === 0 ? undefined : Buffer.concat(chunks);
 }
 
 function firstToken(v: string | string[] | undefined): string | undefined {
@@ -247,26 +247,42 @@ export function createHttpServer(
       res.end(JSON.stringify({ error: 'Not Found' }));
       return;
     }
-    let raw: string | undefined;
+    let buf: Buffer | undefined;
     try {
-      raw = await readBody(req, maxBody);
+      buf = await readBody(req, maxBody);
     } catch (error) {
       const r = errorToResponse(error);
       res.writeHead(r.status, { ...r.headers, connection: 'close' });
       res.end(r.body);
       return;
     }
-    let body: unknown = raw;
+    let body: unknown;
     const ct = String(req.headers['content-type'] ?? '');
-    if (raw !== undefined && ct.includes('application/json')) {
-      try { body = JSON.parse(raw); }
+    if (buf !== undefined && ct.includes('application/json')) {
+      try { body = JSON.parse(buf.toString('utf8')); }
       catch {
         res.writeHead(400, { 'content-type': 'application/json' });
         res.end(JSON.stringify({ error: 'Invalid JSON body' }));
         return;
       }
-    } else if (raw !== undefined && ct.includes('application/x-www-form-urlencoded')) {
-      body = Object.fromEntries(new URLSearchParams(raw));
+    } else if (buf !== undefined && ct.includes('application/x-www-form-urlencoded')) {
+      body = Object.fromEntries(new URLSearchParams(buf.toString('utf8'))); // duplicates policy added in Task 3
+    } else if (buf !== undefined && ct.includes('multipart/form-data')) {
+      const boundary = extractBoundary(ct);
+      if (!boundary) {
+        res.writeHead(400, { 'content-type': 'application/json' });
+        res.end(JSON.stringify({ error: 'Invalid multipart body' }));
+        return;
+      }
+      try { body = parseMultipart(buf, boundary, { maxParts: opts?.limits?.maxParts ?? 1000, duplicates: 'last' }); }
+      catch {
+        res.writeHead(400, { 'content-type': 'application/json' });
+        res.end(JSON.stringify({ error: 'Invalid multipart body' }));
+        return;
+      }
+    } else {
+      const s = buf?.toString('utf8');
+      body = s === '' ? undefined : s;
     }
     let result: PipelineResult;
     try {
diff --git a/test/multipart-http.test.ts b/test/multipart-http.test.ts
new file mode 100644
index 0000000..ad27a11
--- /dev/null
+++ b/test/multipart-http.test.ts
@@ -0,0 +1,52 @@
+import { describe, it, expect, afterEach } from 'vitest';
+import { createApp, Route, Post, Module, body } from '../src';
+
+let app: any;
+afterEach(async () => { await app?.close(); });
+
+describe('multipart over http', () => {
+  it('parses fields + a binary file round-trip', async () => {
+    @Route('/') class C {
+      @Post('/upload') up(@body() b: any) {
+        const f = b.files.file;
+        return { name: b.fields.name, filename: f.filename, bytes: [...f.data], type: f.contentType };
+      }
+    }
+    @Module({ mountpoint: '/', controllers: [C] }) class CMod {}
+    app = createApp({ modules: [CMod] });
+    const server = await app.listen(0);
+    const port = (server.address() as any).port;
+    const fd = new FormData();
+    fd.set('name', 'joe');
+    const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x00, 0x0d, 0x0a]);
+    fd.set('file', new Blob([bytes], { type: 'image/png' }), 'p.png');
+    const r = await fetch(`http://127.0.0.1:${port}/upload`, { method: 'POST', body: fd });
+    const out = (await r.json()) as any;
+    expect(out.name).toBe('joe');
+    expect(out.filename).toBe('p.png');
+    expect(out.type).toBe('image/png');
+    expect(out.bytes).toEqual([...bytes]);
+  });
+
+  it('text/plain body still arrives as a string (fallthrough preserved)', async () => {
+    @Route('/') class C { @Post('/t') t(@body() b: any) { return { isString: typeof b === 'string', b }; } }
+    @Module({ mountpoint: '/', controllers: [C] }) class CMod {}
+    app = createApp({ modules: [CMod] });
+    const server = await app.listen(0);
+    const port = (server.address() as any).port;
+    const r = await fetch(`http://127.0.0.1:${port}/t`, {
+      method: 'POST', headers: { 'content-type': 'text/plain' }, body: 'hello' });
+    expect(await r.json()).toEqual({ isString: true, b: 'hello' });
+  });
+
+  it('malformed multipart → 400', async () => {
+    @Route('/') class C { @Post('/u') u(@body() b: any) { return b; } }
+    @Module({ mountpoint: '/', controllers: [C] }) class CMod {}
+    app = createApp({ modules: [CMod] });
+    const server = await app.listen(0);
+    const port = (server.address() as any).port;
+    const r = await fetch(`http://127.0.0.1:${port}/u`, {
+      method: 'POST', headers: { 'content-type': 'multipart/form-data; boundary=' }, body: 'x' });
+    expect(r.status).toBe(400);
+  });
+});

From ec2e3a0e620a7fc2b1532ef7fd004b31fbc58f84 Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Mon, 6 Jul 2026 20:13:52 -0500
Subject: [PATCH 053/139] feat(http): configurable bodyDuplicates policy for
 urlencoded + multipart fields

Signed-off-by: Diego Resendez 
---
 src/app.ts                  |  4 ++--
 src/http.ts                 |  9 +++++----
 src/multipart.ts            | 10 ++++++++++
 test/multipart-http.test.ts | 23 +++++++++++++++++++++++
 4 files changed, 40 insertions(+), 6 deletions(-)

diff --git a/src/app.ts b/src/app.ts
index ecc64fb..4a3f30d 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -53,7 +53,7 @@ export interface MeshConfig {
   timeoutMs?: number;
 }
 
-export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions; cors?: CorsOptions }): App {
+export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions; cors?: CorsOptions; bodyDuplicates?: 'array' | 'last' }): App {
   const bus = new Bus();
   const container = new Container();
   let server: http.Server | undefined;
@@ -362,7 +362,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
         },
       }));
 
-    server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams, tls: opts.tls, trustProxy: opts.trustProxy, security: opts.security ?? true, cors: opts.cors });
+    server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams, tls: opts.tls, trustProxy: opts.trustProxy, security: opts.security ?? true, cors: opts.cors, bodyDuplicates: opts.bodyDuplicates });
     server.on('close', () => { for (const l of meshLinks) { try { l.close(); } catch { /* */ } } });
     await new Promise((resolve) => server!.listen(port, resolve));
     return server;
diff --git a/src/http.ts b/src/http.ts
index 106b777..1c0c97c 100644
--- a/src/http.ts
+++ b/src/http.ts
@@ -10,7 +10,7 @@ import type { Transport } from './metadata';
 import type { Bus } from './bus';
 import { buildSecurityHeaders, mergeVary, resolveCors, corsPreflightHeaders } from './security';
 import type { TlsOptions, SecurityOptions, CorsOptions } from './security';
-import { parseMultipart, extractBoundary } from './multipart';
+import { parseMultipart, extractBoundary, collapseDuplicates } from './multipart';
 
 export interface RequestLimits {
   maxBodyBytes?: number;       // default 1_000_000
@@ -19,7 +19,7 @@ export interface RequestLimits {
   keepAliveTimeoutMs?: number; // default 5_000
   maxParts?: number;           // default 1000
 }
-export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void>; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions; cors?: CorsOptions }
+export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void>; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions; cors?: CorsOptions; bodyDuplicates?: 'array' | 'last' }
 
 export type RouteHandler = (req: {
   method: string; url: string;
@@ -258,6 +258,7 @@ export function createHttpServer(
     }
     let body: unknown;
     const ct = String(req.headers['content-type'] ?? '');
+    const duplicates = opts?.bodyDuplicates ?? 'last';
     if (buf !== undefined && ct.includes('application/json')) {
       try { body = JSON.parse(buf.toString('utf8')); }
       catch {
@@ -266,7 +267,7 @@ export function createHttpServer(
         return;
       }
     } else if (buf !== undefined && ct.includes('application/x-www-form-urlencoded')) {
-      body = Object.fromEntries(new URLSearchParams(buf.toString('utf8'))); // duplicates policy added in Task 3
+      body = collapseDuplicates(new URLSearchParams(buf.toString('utf8')), duplicates);
     } else if (buf !== undefined && ct.includes('multipart/form-data')) {
       const boundary = extractBoundary(ct);
       if (!boundary) {
@@ -274,7 +275,7 @@ export function createHttpServer(
         res.end(JSON.stringify({ error: 'Invalid multipart body' }));
         return;
       }
-      try { body = parseMultipart(buf, boundary, { maxParts: opts?.limits?.maxParts ?? 1000, duplicates: 'last' }); }
+      try { body = parseMultipart(buf, boundary, { maxParts: opts?.limits?.maxParts ?? 1000, duplicates }); }
       catch {
         res.writeHead(400, { 'content-type': 'application/json' });
         res.end(JSON.stringify({ error: 'Invalid multipart body' }));
diff --git a/src/multipart.ts b/src/multipart.ts
index e4315b5..02fad20 100644
--- a/src/multipart.ts
+++ b/src/multipart.ts
@@ -35,6 +35,16 @@ function addField(fields: MultipartBody['fields'], name: string, value: string,
   }
 }
 
+// Reusable accumulator for any iterable of [key, value] pairs (e.g. URLSearchParams)
+// so urlencoded bodies collapse duplicates with the exact same policy as multipart fields.
+export function collapseDuplicates(
+  pairs: Iterable<[string, string]>, dup: 'array' | 'last',
+): Record {
+  const out: Record = {};
+  for (const [k, v] of pairs) addField(out, k, v, dup);
+  return out;
+}
+
 function addFile(files: MultipartBody['files'], name: string, file: UploadedFile): void {
   const ex = files[name];
   if (ex === undefined) files[name] = file;
diff --git a/test/multipart-http.test.ts b/test/multipart-http.test.ts
index ad27a11..cd5d550 100644
--- a/test/multipart-http.test.ts
+++ b/test/multipart-http.test.ts
@@ -50,3 +50,26 @@ describe('multipart over http', () => {
     expect(r.status).toBe(400);
   });
 });
+
+describe('bodyDuplicates', () => {
+  it('app "array" makes repeated urlencoded fields arrays', async () => {
+    @Route('/') class C { @Post('/f') f(@body() b: any) { return b; } }
+    @Module({ mountpoint: '/', controllers: [C] }) class CMod {}
+    app = createApp({ modules: [CMod], bodyDuplicates: 'array' });
+    const server = await app.listen(0);
+    const port = (server.address() as any).port;
+    const r = await fetch(`http://127.0.0.1:${port}/f`, {
+      method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: 'x=1&x=2&y=9' });
+    expect(await r.json()).toEqual({ x: ['1', '2'], y: ['9'] });
+  });
+  it('default (no option) keeps urlencoded last-wins', async () => {
+    @Route('/') class C { @Post('/f') f(@body() b: any) { return b; } }
+    @Module({ mountpoint: '/', controllers: [C] }) class CMod {}
+    app = createApp({ modules: [CMod] });
+    const server = await app.listen(0);
+    const port = (server.address() as any).port;
+    const r = await fetch(`http://127.0.0.1:${port}/f`, {
+      method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: 'x=1&x=2' });
+    expect(await r.json()).toEqual({ x: '2' });
+  });
+});

From 34017f6ab2b39fe9d24cf49898332f6366f2e9d9 Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Mon, 6 Jul 2026 20:16:46 -0500
Subject: [PATCH 054/139] feat(routes): per-endpoint duplicates override via
 @Post/@Get opts

Signed-off-by: Diego Resendez 
---
 src/app.ts                  |  4 +++-
 src/http.ts                 |  4 ++--
 src/metadata.ts             |  6 +++---
 test/multipart-http.test.ts | 15 +++++++++++++++
 4 files changed, 23 insertions(+), 6 deletions(-)

diff --git a/src/app.ts b/src/app.ts
index 4a3f30d..2161e75 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -45,6 +45,7 @@ interface RoutePlan {
   needs: string[];
   run: (ctx: any) => unknown;
   transformer: typeof JsonTransformer;
+  duplicates?: 'array' | 'last';
 }
 
 export interface MeshConfig {
@@ -115,6 +116,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
           needs: getHandlerNeeds(argSpecs),
           run: (c: any) => inst[route.handlerName](...resolveArgs(argSpecs, c)),
           transformer: getTransformer(C, route.handlerName) ?? JsonTransformer,
+          duplicates: route.duplicates,
         });
       }
     }
@@ -319,7 +321,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
       ...routePlans
         .filter((plan) => plan.transport !== 'ws')   // buffer | sse | ndjson | negotiate
         .map((plan): RouteDef => ({
-          method: plan.method, pattern: plan.pattern, transport: plan.transport,
+          method: plan.method, pattern: plan.pattern, transport: plan.transport, bodyDuplicates: plan.duplicates,
           handler: async (req) => {
             const provided = await providedSeed(plan);
             return runPipeline({
diff --git a/src/http.ts b/src/http.ts
index 1c0c97c..4b28355 100644
--- a/src/http.ts
+++ b/src/http.ts
@@ -31,7 +31,7 @@ export type RouteHandler = (req: {
   ip: string;
 }) => Promise;
 
-export interface RouteDef { method: string; pattern: string; transport: Transport; handler: RouteHandler }
+export interface RouteDef { method: string; pattern: string; transport: Transport; handler: RouteHandler; bodyDuplicates?: 'array' | 'last' }
 export interface MatchedRoute { params: Record; def: RouteDef }
 
 export interface WsOpenCtx {
@@ -258,7 +258,7 @@ export function createHttpServer(
     }
     let body: unknown;
     const ct = String(req.headers['content-type'] ?? '');
-    const duplicates = opts?.bodyDuplicates ?? 'last';
+    const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last';
     if (buf !== undefined && ct.includes('application/json')) {
       try { body = JSON.parse(buf.toString('utf8')); }
       catch {
diff --git a/src/metadata.ts b/src/metadata.ts
index 33e48dc..be4efce 100644
--- a/src/metadata.ts
+++ b/src/metadata.ts
@@ -7,7 +7,7 @@ export interface ProviderMeta { provides: string; needs: string[]; optional: boo
 export interface StepMeta { provides: string; needs: string[]; optional: boolean; export: boolean }
 export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
 export type Transport = 'buffer' | 'sse' | 'ndjson' | 'negotiate' | 'ws';
-export interface RouteMeta { method: HttpMethod; path: string; handlerName: string; transport: Transport; export: boolean }
+export interface RouteMeta { method: HttpMethod; path: string; handlerName: string; transport: Transport; export: boolean; duplicates?: 'array' | 'last' }
 export interface ModuleOptions {
   mountpoint: string; providers?: Ctor[]; steps?: Ctor[]; controllers?: Ctor[];
 }
@@ -40,11 +40,11 @@ export function Route(prefix: string): ClassDecorator {
 }
 
 function routeDecorator(method: HttpMethod, transport: Transport) {
-  return (path: string, opts?: { export?: boolean }): MethodDecorator =>
+  return (path: string, opts?: { export?: boolean; duplicates?: 'array' | 'last' }): MethodDecorator =>
     (target, propertyKey) => {
       const ctor = target.constructor;
       const routes = (Reflect.getMetadata(K.routes, ctor) as RouteMeta[]) ?? [];
-      routes.push({ method, path, handlerName: String(propertyKey), transport, export: opts?.export ?? false });
+      routes.push({ method, path, handlerName: String(propertyKey), transport, export: opts?.export ?? false, duplicates: opts?.duplicates });
       Reflect.defineMetadata(K.routes, routes, ctor);
     };
 }
diff --git a/test/multipart-http.test.ts b/test/multipart-http.test.ts
index cd5d550..871d157 100644
--- a/test/multipart-http.test.ts
+++ b/test/multipart-http.test.ts
@@ -72,4 +72,19 @@ describe('bodyDuplicates', () => {
       method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: 'x=1&x=2' });
     expect(await r.json()).toEqual({ x: '2' });
   });
+
+  it('per-endpoint override beats app default', async () => {
+    @Route('/') class C {
+      @Post('/a', { duplicates: 'last' }) a(@body() b: any) { return b; }
+      @Post('/b', { duplicates: 'array' }) b2(@body() b: any) { return b; }
+    }
+    @Module({ mountpoint: '/', controllers: [C] }) class CMod {}
+    app = createApp({ modules: [CMod], bodyDuplicates: 'last' });
+    const server = await app.listen(0);
+    const port = (server.address() as any).port;
+    const post = (p: string) => fetch(`http://127.0.0.1:${port}${p}`, {
+      method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: 'x=1&x=2' }).then((r) => r.json());
+    expect(await post('/a')).toEqual({ x: '2' });
+    expect(await post('/b')).toEqual({ x: ['1', '2'] });
+  });
 });

From 97284935aaa67c936f7432160974790f3860f041 Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Mon, 6 Jul 2026 20:19:29 -0500
Subject: [PATCH 055/139] docs: multipart/form-data uploads, bodyDuplicates,
 maxParts

Signed-off-by: Diego Resendez 
---
 docs/quickstart.md | 62 ++++++++++++++++++++++++++++++++++++++++++++++
 src/index.ts       |  1 +
 2 files changed, 63 insertions(+)

diff --git a/docs/quickstart.md b/docs/quickstart.md
index 2f0a365..31620ca 100644
--- a/docs/quickstart.md
+++ b/docs/quickstart.md
@@ -307,6 +307,68 @@ to the WebSocket handshake (101/upgrade) response.
 | `cors` | off (same-origin only) |
 | `security` | ON (HSTS only when the connection is secure) |
 
+## 8. File uploads / multipart
+
+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.
+
 ## Inspect & test the graph
 
 ### Visualize with Mermaid
diff --git a/src/index.ts b/src/index.ts
index 28cf546..344a578 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -25,6 +25,7 @@ export type { StreamEncoder } from './encoders';
 export type { MeshConfig } from './app';
 export type { RequestLimits } from './http';
 export type { TlsOptions, CorsOptions, SecurityOptions } from './security';
+export type { UploadedFile, MultipartBody } from './multipart';
 export { connectLink } from './mesh/link';
 export { buildRemote, envelopeFrom } from './mesh/teacup';
 export { buildManifest, createMeshControl, MESH_CONTROL_PATH } from './mesh/teapot';

From 81dc9d3a70221d2b0e9b35c80401746e84d41780 Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Mon, 6 Jul 2026 21:26:55 -0500
Subject: [PATCH 056/139] feat(validation): vendor Standard Schema types +
 isStandardSchema/flattenPath

Signed-off-by: Diego Resendez 
---
 src/standard-schema.ts       | 34 ++++++++++++++++++++++++++++++++++
 test/standard-schema.test.ts | 23 +++++++++++++++++++++++
 2 files changed, 57 insertions(+)
 create mode 100644 src/standard-schema.ts
 create mode 100644 test/standard-schema.test.ts

diff --git a/src/standard-schema.ts b/src/standard-schema.ts
new file mode 100644
index 0000000..dde28c1
--- /dev/null
+++ b/src/standard-schema.ts
@@ -0,0 +1,34 @@
+// src/standard-schema.ts — vendored Standard Schema (~standard) types + helpers. No imports.
+export interface StandardSchemaV1 {
+  readonly '~standard': {
+    readonly version: 1;
+    readonly vendor: string;
+    validate(value: unknown): StandardResult | Promise>;
+    readonly types?: { readonly input: Input; readonly output: Output };
+  };
+}
+
+export type StandardResult =
+  | { readonly value: T; readonly issues?: undefined }
+  | { readonly issues: ReadonlyArray };
+
+export interface StandardIssue {
+  readonly message: string;
+  readonly path?: ReadonlyArray;
+}
+
+export function isStandardSchema(x: unknown): x is StandardSchemaV1 {
+  return (
+    typeof x === 'object' && x !== null &&
+    '~standard' in x &&
+    typeof (x as { ['~standard']?: { validate?: unknown } })['~standard']?.validate === 'function'
+  );
+}
+
+export function flattenPath(issue: StandardIssue): string {
+  if (!issue.path) return '';
+  return issue.path
+    .map((seg) => (typeof seg === 'object' && seg !== null && 'key' in seg ? seg.key : seg))
+    .map((k) => String(k))
+    .join('.');
+}
diff --git a/test/standard-schema.test.ts b/test/standard-schema.test.ts
new file mode 100644
index 0000000..1c59d34
--- /dev/null
+++ b/test/standard-schema.test.ts
@@ -0,0 +1,23 @@
+import { describe, it, expect } from 'vitest';
+import { isStandardSchema, flattenPath } from '../src/standard-schema';
+
+const schema = { '~standard': { version: 1, vendor: 't', validate: (v: unknown) => ({ value: v }) } };
+
+describe('isStandardSchema', () => {
+  it('true for a Standard Schema, false for string/array/plain object/null', () => {
+    expect(isStandardSchema(schema)).toBe(true);
+    expect(isStandardSchema('id')).toBe(false);
+    expect(isStandardSchema(['a', 'b'])).toBe(false);
+    expect(isStandardSchema({})).toBe(false);
+    expect(isStandardSchema(null)).toBe(false);
+    expect(isStandardSchema({ '~standard': {} })).toBe(false); // no validate fn
+  });
+});
+
+describe('flattenPath', () => {
+  it('flattens key + {key} segments to a dot string', () => {
+    expect(flattenPath({ message: 'x', path: ['address', 'city'] })).toBe('address.city');
+    expect(flattenPath({ message: 'x', path: ['items', 0, { key: 'qty' }] })).toBe('items.0.qty');
+    expect(flattenPath({ message: 'x' })).toBe('');
+  });
+});

From 101833d52d6a060415c6b6722553792b69461040 Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Mon, 6 Jul 2026 21:29:27 -0500
Subject: [PATCH 057/139] =?UTF-8?q?feat(validation):=20ValidationError=20?=
 =?UTF-8?q?=E2=86=92=20422=20with=20source=20+=20issues=20(before=20HttpEr?=
 =?UTF-8?q?ror)?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Signed-off-by: Diego Resendez 
---
 src/signals.ts            |  8 ++++++++
 src/transformers.ts       | 14 +++++++++++++-
 test/transformers.test.ts | 21 +++++++++++++++++++--
 3 files changed, 40 insertions(+), 3 deletions(-)

diff --git a/src/signals.ts b/src/signals.ts
index d9f36a7..3b47c24 100644
--- a/src/signals.ts
+++ b/src/signals.ts
@@ -1,3 +1,5 @@
+import type { StandardIssue } from './standard-schema';
+
 export class HttpError extends Error {
   constructor(readonly status: number, message?: string, readonly body?: unknown) {
     super(message ?? `HTTP ${status}`);
@@ -21,6 +23,12 @@ export class Redirect extends HttpError {
   constructor(readonly location: string) { super(302); }
 }
 
+export class ValidationError extends HttpError {
+  constructor(public issues: StandardIssue[], public source: string) {
+    super(422, 'Validation failed');
+  }
+}
+
 export function isHttpError(e: unknown): e is HttpError {
   return e instanceof HttpError;
 }
diff --git a/src/transformers.ts b/src/transformers.ts
index b208385..57c5989 100644
--- a/src/transformers.ts
+++ b/src/transformers.ts
@@ -1,5 +1,6 @@
-import { isHttpError, Redirect } from './signals';
+import { isHttpError, Redirect, ValidationError } from './signals';
 import type { TransformerFn } from './metadata';
+import { flattenPath } from './standard-schema';
 
 export const JsonTransformer: TransformerFn = (value) => ({
   status: 200,
@@ -8,6 +9,17 @@ export const JsonTransformer: TransformerFn = (value) => ({
 });
 
 export function errorToResponse(e: unknown): { status: number; headers: Record; body: string } {
+  if (e instanceof ValidationError) {
+    return {
+      status: 422,
+      headers: { 'content-type': 'application/json' },
+      body: JSON.stringify({
+        error: 'Validation failed',
+        source: e.source,
+        issues: e.issues.map((i) => ({ path: flattenPath(i), message: i.message })),
+      }),
+    };
+  }
   if (isHttpError(e)) {
     const headers: Record = { 'content-type': 'application/json' };
     if (e instanceof Redirect) headers.location = e.location;
diff --git a/test/transformers.test.ts b/test/transformers.test.ts
index fa3909d..f67cdb5 100644
--- a/test/transformers.test.ts
+++ b/test/transformers.test.ts
@@ -1,6 +1,6 @@
-import { expect, test } from 'vitest';
+import { describe, expect, it, test } from 'vitest';
 import { JsonTransformer, errorToResponse } from '../src/transformers';
-import { Unauthorized, Redirect } from '../src/signals';
+import { HttpError, Unauthorized, Redirect, ValidationError } from '../src/signals';
 
 test('JsonTransformer serializes value with json content-type', () => {
   expect(JsonTransformer({ a: 1 })).toEqual({
@@ -21,3 +21,20 @@ test('errorToResponse sets location for Redirect', () => {
 test('unknown error becomes 500', () => {
   expect(errorToResponse(new Error('boom')).status).toBe(500);
 });
+
+describe('errorToResponse ValidationError', () => {
+  it('maps ValidationError to 422 with source + flattened issues (before generic HttpError)', () => {
+    const err = new ValidationError([{ message: 'Invalid email', path: ['email'] }], 'body');
+    const r = errorToResponse(err);
+    expect(r.status).toBe(422);
+    expect(JSON.parse(r.body)).toEqual({
+      error: 'Validation failed', source: 'body',
+      issues: [{ path: 'email', message: 'Invalid email' }],
+    });
+  });
+  it('still maps a plain HttpError to { error: message }', () => {
+    const r = errorToResponse(new HttpError(403, 'Nope'));
+    expect(r.status).toBe(403);
+    expect(JSON.parse(r.body)).toEqual({ error: 'Nope' });
+  });
+});

From eb494ff254e43a4cf304e4710775d39dd0239c3e Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Mon, 6 Jul 2026 21:33:13 -0500
Subject: [PATCH 058/139] feat(params): schema-aware arg decorators; async
 validating resolveArgs

Signed-off-by: Diego Resendez 
---
 src/app.ts          |  4 +--
 src/params.ts       | 32 +++++++++++++++-------
 test/params.test.ts | 65 ++++++++++++++++++++++++++++++++++++++++-----
 3 files changed, 83 insertions(+), 18 deletions(-)

diff --git a/src/app.ts b/src/app.ts
index 2161e75..0c4a5f5 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -114,7 +114,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
           steps: [],
           handlerName: route.handlerName,
           needs: getHandlerNeeds(argSpecs),
-          run: (c: any) => inst[route.handlerName](...resolveArgs(argSpecs, c)),
+          run: async (c: any) => inst[route.handlerName](...(await resolveArgs(argSpecs, c))),
           transformer: getTransformer(C, route.handlerName) ?? JsonTransformer,
           duplicates: route.duplicates,
         });
@@ -358,7 +358,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
                            headers: req.headers, inbound, abort,
                            protocol: (req.socket as any).encrypted ? 'https' : 'http', ip: req.socket.remoteAddress ?? '' };
           for (const s of planSteps(plan)) { ctx = { ...ctx, ...(await s.run(ctx)) }; }
-          const out = plan.run(ctx);
+          const out = await plan.run(ctx);
           if (!isAsyncIterable(out)) throw new Error(`@Ws handler '${plan.handlerName}' must return an AsyncIterable`);
           return out as AsyncIterable;
         },
diff --git a/src/params.ts b/src/params.ts
index 02f8a20..a431de3 100644
--- a/src/params.ts
+++ b/src/params.ts
@@ -1,12 +1,14 @@
 import 'reflect-metadata';
 import type { Ctor } from './metadata';
+import { isStandardSchema, type StandardSchemaV1 } from './standard-schema';
+import { ValidationError } from './signals';
 
 export type Query = Record;
 export type Headers = Record;
 export type Context = Record;
 
 type ArgSource = 'ctx' | 'needs' | 'params' | 'query' | 'body' | 'headers' | 'inbound' | 'abort';
-export interface ArgSpec { index: number; source: ArgSource; key?: string; keys?: string[] }
+export interface ArgSpec { index: number; source: ArgSource; key?: string; keys?: string[]; schema?: StandardSchemaV1 }
 
 const ARGS = Symbol('gt:args');
 
@@ -21,13 +23,17 @@ function record(target: object, methodKey: string | symbol | undefined, spec: Ar
 }
 
 function envelope(source: ArgSource) {
-  return (arg?: string | string[]): ParameterDecorator =>
+  return (arg?: string | string[] | StandardSchemaV1, schema?: StandardSchemaV1): ParameterDecorator =>
     (target, methodKey, index) => {
-      const spec: ArgSpec = Array.isArray(arg)
-        ? { index, source, keys: arg }
-        : typeof arg === 'string'
-        ? { index, source, key: arg }
-        : { index, source };
+      const spec: ArgSpec = { index, source };
+      if (Array.isArray(arg)) spec.keys = arg;
+      else if (typeof arg === 'string') spec.key = arg;
+      else if (isStandardSchema(arg)) spec.schema = arg;
+      else if (arg !== undefined) throw new Error(`@${source}: expected a Standard Schema or a string/array key`);
+      if (schema !== undefined) {
+        if (!isStandardSchema(schema)) throw new Error(`@${source}: second argument must be a Standard Schema`);
+        spec.schema = schema;
+      }
       record(target, methodKey, spec);
     };
 }
@@ -62,11 +68,19 @@ export function getHandlerNeeds(specs: ArgSpec[]): string[] {
   return specs.filter((s) => s.source === 'needs' && s.key).map((s) => s.key as string);
 }
 
-export function resolveArgs(specs: ArgSpec[], context: Context): unknown[] {
+export async function resolveArgs(specs: ArgSpec[], context: Context): Promise {
   if (specs.length === 0) return [];
   const max = Math.max(...specs.map((s) => s.index));
   const args: unknown[] = new Array(max + 1).fill(undefined);
-  for (const s of specs) args[s.index] = resolveOne(s, context);
+  for (const s of specs) {
+    let value = resolveOne(s, context);
+    if (s.schema) {
+      const result = await s.schema['~standard'].validate(value);
+      if (result.issues) throw new ValidationError([...result.issues], s.source);
+      value = result.value;
+    }
+    args[s.index] = value;
+  }
   return args;
 }
 
diff --git a/test/params.test.ts b/test/params.test.ts
index 833ffb9..7de01ec 100644
--- a/test/params.test.ts
+++ b/test/params.test.ts
@@ -1,6 +1,7 @@
 import 'reflect-metadata';
 import { expect, test, describe, it } from 'vitest';
-import { needs, ctx, param, query, inbound, abort, getArgs, getHandlerNeeds, resolveArgs } from '../src/params';
+import { needs, ctx, param, query, body, inbound, abort, getArgs, getHandlerNeeds, resolveArgs } from '../src/params';
+import { ValidationError } from '../src/signals';
 
 class Ctl {
   handler(
@@ -27,13 +28,13 @@ test('getHandlerNeeds extracts only @needs keys', () => {
   expect(getHandlerNeeds(getArgs(Ctl, 'handler'))).toEqual(['user']);
 });
 
-test('resolveArgs builds positional args from context', () => {
+test('resolveArgs builds positional args from context', async () => {
   const context = {
     user: { id: 'u1' },
     params: { id: '7' },
     query: { a: '1', b: '2', c: '3' },
   };
-  const args = resolveArgs(getArgs(Ctl, 'handler'), context);
+  const args = await resolveArgs(getArgs(Ctl, 'handler'), context);
   expect(args[0]).toEqual({ id: 'u1' });
   expect(args[1]).toBe('7');
   expect(args[2]).toEqual({ a: '1', b: '2', c: '3' });
@@ -41,18 +42,18 @@ test('resolveArgs builds positional args from context', () => {
   expect(args[4]).toBe(context);
 });
 
-test('a handler with no arg decorators resolves to no args', () => {
+test('a handler with no arg decorators resolves to no args', async () => {
   class Bare { ping() { return 1; } }
-  expect(resolveArgs(getArgs(Bare, 'ping'), {})).toEqual([]);
+  expect(await resolveArgs(getArgs(Bare, 'ping'), {})).toEqual([]);
 });
 
 describe('@inbound / @abort', () => {
-  it('resolves inbound and abort from reserved context keys, not as bags', () => {
+  it('resolves inbound and abort from reserved context keys, not as bags', async () => {
     class Ctl { handle(@inbound() inc: AsyncIterable, @abort() sig: AbortSignal) { return [inc, sig]; } }
     const specs = getArgs(Ctl, 'handle');
     const ac = new AbortController();
     const inc = (async function* () {})();
-    const args = resolveArgs(specs, { inbound: inc, abort: ac.signal });
+    const args = await resolveArgs(specs, { inbound: inc, abort: ac.signal });
     expect(args[0]).toBe(inc);
     expect(args[1]).toBe(ac.signal);
   });
@@ -62,3 +63,53 @@ describe('@inbound / @abort', () => {
     expect(getHandlerNeeds(getArgs(Ctl, 'handle'))).toEqual([]);
   });
 });
+
+const numFromStr = {
+  '~standard': {
+    version: 1 as const, vendor: 'test',
+    validate: (v: unknown) => {
+      const n = Number(v);
+      return Number.isNaN(n) ? { issues: [{ message: 'not a number', path: ['n'] }] } : { value: n };
+    },
+  },
+};
+const asyncSchema = {
+  '~standard': { version: 1 as const, vendor: 'test', validate: async (v: unknown) => ({ value: `async:${v}` }) },
+};
+
+describe('resolveArgs validation', () => {
+  it('valid: substitutes the parsed/coerced value; ctx source untouched', async () => {
+    class C { m(@query(numFromStr) _q: number) {} }
+    const specs = getArgs(C, 'm');
+    const ctx: any = { query: '42' };
+    const args = await resolveArgs(specs, ctx);
+    expect(args[0]).toBe(42);
+    expect(ctx.query).toBe('42');
+  });
+  it('invalid: throws ValidationError with source', async () => {
+    class C { m(@body(numFromStr) _b: number) {} }
+    const specs = getArgs(C, 'm');
+    await expect(resolveArgs(specs, { body: 'nope' })).rejects.toBeInstanceOf(ValidationError);
+    await resolveArgs(specs, { body: 'nope' }).catch((e) => { expect(e.source).toBe('body'); expect(e.issues[0].message).toBe('not a number'); });
+  });
+  it('async schema is awaited', async () => {
+    class C { m(@body(asyncSchema) _b: string) {} }
+    const args = await resolveArgs(getArgs(C, 'm'), { body: 'x' });
+    expect(args[0]).toBe('async:x');
+  });
+  it('@param(name, schema) validates the named param (slot-2 schema)', async () => {
+    class C { m(@param('id', numFromStr) _id: number) {} }
+    const args = await resolveArgs(getArgs(C, 'm'), { params: { id: '7' } });
+    expect(args[0]).toBe(7);
+  });
+  it('non-schema decorators unchanged: @body("key"), @body(), @query(["a","b"])', async () => {
+    class C { m(@body('x') _x: any, @body() _b: any, @query(['a', 'b']) _q: any) {} }
+    const args = await resolveArgs(getArgs(C, 'm'), { body: { x: 1, y: 2 }, query: { a: 'A', b: 'B', c: 'C' } });
+    expect(args[0]).toBe(1);
+    expect(args[1]).toEqual({ x: 1, y: 2 });
+    expect(args[2]).toEqual({ a: 'A', b: 'B' });
+  });
+  it('decoration-time guard: a non-schema object throws', () => {
+    expect(() => { class C { m(@body({} as any) _b: any) {} } return C; }).toThrow();
+  });
+});

From 456dd52df8dd396a8c1b075abc00d4fcff74d0a2 Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Mon, 6 Jul 2026 21:37:22 -0500
Subject: [PATCH 059/139] refactor(app): type RoutePlan.run as async; add
 validation e2e tests

Signed-off-by: Diego Resendez 
---
 src/app.ts                   |  2 +-
 test/validation-http.test.ts | 43 ++++++++++++++++++++++++++++++++++++
 2 files changed, 44 insertions(+), 1 deletion(-)
 create mode 100644 test/validation-http.test.ts

diff --git a/src/app.ts b/src/app.ts
index 0c4a5f5..74ead24 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -43,7 +43,7 @@ interface RoutePlan {
   steps: GraphNode[];
   handlerName: string;
   needs: string[];
-  run: (ctx: any) => unknown;
+  run: (ctx: any) => Promise;
   transformer: typeof JsonTransformer;
   duplicates?: 'array' | 'last';
 }
diff --git a/test/validation-http.test.ts b/test/validation-http.test.ts
new file mode 100644
index 0000000..a2291ac
--- /dev/null
+++ b/test/validation-http.test.ts
@@ -0,0 +1,43 @@
+import { describe, it, expect, afterEach } from 'vitest';
+import { createApp, Route, Get, Post, Module, body, query, param } from '../src';
+
+const numQuery = { '~standard': { version: 1 as const, vendor: 't', validate: (v: any) => {
+  const n = Number(v?.page); return Number.isNaN(n) ? { issues: [{ message: 'bad', path: ['page'] }] } : { value: { page: n } }; } } };
+const userBody = { '~standard': { version: 1 as const, vendor: 't', validate: (v: any) =>
+  (typeof v?.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'Invalid email', path: ['email'] }] } } };
+const idParam = { '~standard': { version: 1 as const, vendor: 't', validate: (v: any) => {
+  const n = Number(v); return Number.isNaN(n) ? { issues: [{ message: 'nan', path: [] }] } : { value: n }; } } };
+
+let app: any;
+afterEach(async () => { await app?.close(); });
+
+describe('validation over http', () => {
+  it('valid body → 200 with parsed value; query coerced to number; param coerced', async () => {
+    @Route('/') class C {
+      @Post('/u') create(@body(userBody) b: any) { return { ok: b.email }; }
+      @Get('/list') list(@query(numQuery) q: any) { return { page: q.page, isNum: typeof q.page === 'number' }; }
+      @Get('/u/:id') get(@param('id', idParam) id: any) { return { id, isNum: typeof id === 'number' }; }
+    }
+    @Module({ mountpoint: '/', controllers: [C] }) class CMod {}
+    app = createApp({ modules: [CMod] });
+    const server = await app.listen(0);
+    const port = (server.address() as any).port;
+    const ok = await fetch(`http://127.0.0.1:${port}/u`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ email: 'a@b.com' }) });
+    expect(await ok.json()).toEqual({ ok: 'a@b.com' });
+    const li = await fetch(`http://127.0.0.1:${port}/list?page=2`);
+    expect(await li.json()).toEqual({ page: 2, isNum: true });
+    const g = await fetch(`http://127.0.0.1:${port}/u/7`);
+    expect(await g.json()).toEqual({ id: 7, isNum: true });
+  });
+
+  it('invalid body → 422 with source + issues', async () => {
+    @Route('/') class C { @Post('/u') create(@body(userBody) b: any) { return b; } }
+    @Module({ mountpoint: '/', controllers: [C] }) class CMod {}
+    app = createApp({ modules: [CMod] });
+    const server = await app.listen(0);
+    const port = (server.address() as any).port;
+    const r = await fetch(`http://127.0.0.1:${port}/u`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ email: 'nope' }) });
+    expect(r.status).toBe(422);
+    expect(await r.json()).toEqual({ error: 'Validation failed', source: 'body', issues: [{ path: 'email', message: 'Invalid email' }] });
+  });
+});

From 0f11ad1e618920369f5958610346278087914f71 Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Mon, 6 Jul 2026 21:41:26 -0500
Subject: [PATCH 060/139] docs: input validation via Standard Schema

Signed-off-by: Diego Resendez 
---
 docs/quickstart.md | 63 ++++++++++++++++++++++++++++++++++++++++++++++
 src/index.ts       |  3 ++-
 2 files changed, 65 insertions(+), 1 deletion(-)

diff --git a/docs/quickstart.md b/docs/quickstart.md
index 31620ca..edd04ca 100644
--- a/docs/quickstart.md
+++ b/docs/quickstart.md
@@ -369,6 +369,69 @@ 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
diff --git a/src/index.ts b/src/index.ts
index 344a578..b7e7be5 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -8,7 +8,7 @@ export type { GraphView } from './graph-viz';
 export { Provider, Step, Route, Get, Module, Transformer } from './metadata';
 export type { Plugin } from './plugin';
 export { JsonTransformer } from './transformers';
-export { HttpError, Unauthorized, NotFound, Redirect, NotModified } from './signals';
+export { HttpError, Unauthorized, NotFound, Redirect, NotModified, ValidationError } from './signals';
 export { Bus } from './bus';
 export { flow, Flow } from './flow';
 export type { StepFn, CompiledFlow } from './flow';
@@ -26,6 +26,7 @@ export type { MeshConfig } from './app';
 export type { RequestLimits } from './http';
 export type { TlsOptions, CorsOptions, SecurityOptions } from './security';
 export type { UploadedFile, MultipartBody } from './multipart';
+export type { StandardSchemaV1 } from './standard-schema';
 export { connectLink } from './mesh/link';
 export { buildRemote, envelopeFrom } from './mesh/teacup';
 export { buildManifest, createMeshControl, MESH_CONTROL_PATH } from './mesh/teapot';

From 1fdb7e11e54e03cc0263caaf649010837342d620 Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Mon, 6 Jul 2026 22:25:05 -0500
Subject: [PATCH 061/139] =?UTF-8?q?chore(bench):=20scaffold=20benchmark=20?=
 =?UTF-8?q?harness=20=E2=80=94=20devDeps,=20scenarios,=20tsconfig?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Signed-off-by: Diego Resendez 
---
 bench/scenarios.ts  |   25 +
 bench/tsconfig.json |    5 +
 package-lock.json   | 2730 +++++++++++++++++++++++++++++++++++++++++++
 package.json        |    9 +-
 4 files changed, 2768 insertions(+), 1 deletion(-)
 create mode 100644 bench/scenarios.ts
 create mode 100644 bench/tsconfig.json

diff --git a/bench/scenarios.ts b/bench/scenarios.ts
new file mode 100644
index 0000000..f1d1919
--- /dev/null
+++ b/bench/scenarios.ts
@@ -0,0 +1,25 @@
+export interface Scenario {
+  name: string;        // key
+  title: string;       // display
+  method: 'GET' | 'POST';
+  path: string;        // route path (no host)
+  body?: unknown;      // JSON body for POST
+  approximation?: boolean;
+}
+
+// The always-valid validation body — every framework takes the success path.
+export const VALIDATE_BODY = { email: 'bench@example.com' };
+
+export const SCENARIOS: Scenario[] = [
+  { name: 'hello',    title: 'JSON hello (overhead)', method: 'GET',  path: '/hello' },
+  { name: 'param',    title: 'Route param',           method: 'GET',  path: '/users/42' },
+  { name: 'pipeline', title: 'Pipeline (3 steps)',    method: 'GET',  path: '/pipeline', approximation: true },
+  { name: 'validate', title: 'POST JSON + validation',method: 'POST', path: '/validate', body: VALIDATE_BODY },
+];
+
+// green-tea-only step-scaling routes
+export const STEP_ROUTES = [
+  { name: 'steps0', steps: 0, path: '/steps/0' },
+  { name: 'steps3', steps: 3, path: '/steps/3' },
+  { name: 'steps5', steps: 5, path: '/steps/5' },
+];
diff --git a/bench/tsconfig.json b/bench/tsconfig.json
new file mode 100644
index 0000000..09614f5
--- /dev/null
+++ b/bench/tsconfig.json
@@ -0,0 +1,5 @@
+{
+  "extends": "../tsconfig.json",
+  "compilerOptions": { "experimentalDecorators": true, "emitDecoratorMetadata": true, "noEmit": true },
+  "include": ["."]
+}
diff --git a/package-lock.json b/package-lock.json
index 1e3ee1c..03e6923 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -12,9 +12,15 @@
         "reflect-metadata": "0.2.2"
       },
       "devDependencies": {
+        "@types/autocannon": "^7.12.7",
+        "@types/express": "^5.0.6",
         "@types/node": "^18.19.0",
         "@types/ws": "^8.18.1",
+        "autocannon": "^8.0.0",
+        "express": "^5.2.1",
+        "fastify": "^5.10.0",
         "graphql": "^16.9.0",
+        "tsx": "^4.23.0",
         "typescript": "^5.5.0",
         "vitest": "^2.0.0",
         "ws": "^8.21.0"
@@ -28,6 +34,24 @@
         }
       }
     },
+    "node_modules/@assemblyscript/loader": {
+      "version": "0.19.23",
+      "resolved": "https://registry.npmjs.org/@assemblyscript/loader/-/loader-0.19.23.tgz",
+      "integrity": "sha512-ulkCYfFbYj01ie1MDOyxv2F6SpRN1TOj7fQxbP07D6HmeR+gr2JLSmINKjga2emB+b1L2KGrFKBTc+e00p54nw==",
+      "dev": true,
+      "license": "Apache-2.0"
+    },
+    "node_modules/@colors/colors": {
+      "version": "1.5.0",
+      "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz",
+      "integrity": "sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==",
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "engines": {
+        "node": ">=0.1.90"
+      }
+    },
     "node_modules/@esbuild/aix-ppc64": {
       "version": "0.21.5",
       "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz",
@@ -317,6 +341,23 @@
         "node": ">=12"
       }
     },
+    "node_modules/@esbuild/netbsd-arm64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz",
+      "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "netbsd"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
     "node_modules/@esbuild/netbsd-x64": {
       "version": "0.21.5",
       "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz",
@@ -334,6 +375,23 @@
         "node": ">=12"
       }
     },
+    "node_modules/@esbuild/openbsd-arm64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz",
+      "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "openbsd"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
     "node_modules/@esbuild/openbsd-x64": {
       "version": "0.21.5",
       "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz",
@@ -351,6 +409,23 @@
         "node": ">=12"
       }
     },
+    "node_modules/@esbuild/openharmony-arm64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz",
+      "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "openharmony"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
     "node_modules/@esbuild/sunos-x64": {
       "version": "0.21.5",
       "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz",
@@ -419,6 +494,123 @@
         "node": ">=12"
       }
     },
+    "node_modules/@fastify/ajv-compiler": {
+      "version": "4.0.5",
+      "resolved": "https://registry.npmjs.org/@fastify/ajv-compiler/-/ajv-compiler-4.0.5.tgz",
+      "integrity": "sha512-KoWKW+MhvfTRWL4qrhUwAAZoaChluo0m0vbiJlGMt2GXvL4LVPQEjt8kSpHI3IBq5Rez8fg+XeH3cneztq+C7A==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/fastify"
+        },
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/fastify"
+        }
+      ],
+      "license": "MIT",
+      "dependencies": {
+        "ajv": "^8.12.0",
+        "ajv-formats": "^3.0.1",
+        "fast-uri": "^3.0.0"
+      }
+    },
+    "node_modules/@fastify/error": {
+      "version": "4.2.0",
+      "resolved": "https://registry.npmjs.org/@fastify/error/-/error-4.2.0.tgz",
+      "integrity": "sha512-RSo3sVDXfHskiBZKBPRgnQTtIqpi/7zhJOEmAxCiBcM7d0uwdGdxLlsCaLzGs8v8NnxIRlfG0N51p5yFaOentQ==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/fastify"
+        },
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/fastify"
+        }
+      ],
+      "license": "MIT"
+    },
+    "node_modules/@fastify/fast-json-stringify-compiler": {
+      "version": "5.1.0",
+      "resolved": "https://registry.npmjs.org/@fastify/fast-json-stringify-compiler/-/fast-json-stringify-compiler-5.1.0.tgz",
+      "integrity": "sha512-PxcYtKLbQ8Z+yApiqjK8FwxIwvEj38k2OiLc17u8dkJSlmfi2wHHPaSnaoqBPQqtvF8YVsDgDpP2snDCfFrpfw==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/fastify"
+        },
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/fastify"
+        }
+      ],
+      "license": "MIT",
+      "dependencies": {
+        "fast-json-stringify": "^7.0.0"
+      }
+    },
+    "node_modules/@fastify/forwarded": {
+      "version": "3.0.1",
+      "resolved": "https://registry.npmjs.org/@fastify/forwarded/-/forwarded-3.0.1.tgz",
+      "integrity": "sha512-JqDochHFqXs3C3Ml3gOY58zM7OqO9ENqPo0UqAjAjH8L01fRZqwX9iLeX34//kiJubF7r2ZQHtBRU36vONbLlw==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/fastify"
+        },
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/fastify"
+        }
+      ],
+      "license": "MIT"
+    },
+    "node_modules/@fastify/merge-json-schemas": {
+      "version": "0.2.1",
+      "resolved": "https://registry.npmjs.org/@fastify/merge-json-schemas/-/merge-json-schemas-0.2.1.tgz",
+      "integrity": "sha512-OA3KGBCy6KtIvLf8DINC5880o5iBlDX4SxzLQS8HorJAbqluzLRn80UXU0bxZn7UOFhFgpRJDasfwn9nG4FG4A==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/fastify"
+        },
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/fastify"
+        }
+      ],
+      "license": "MIT",
+      "dependencies": {
+        "dequal": "^2.0.3"
+      }
+    },
+    "node_modules/@fastify/proxy-addr": {
+      "version": "5.1.0",
+      "resolved": "https://registry.npmjs.org/@fastify/proxy-addr/-/proxy-addr-5.1.0.tgz",
+      "integrity": "sha512-INS+6gh91cLUjB+PVHfu1UqcB76Sqtpyp7bnL+FYojhjygvOPA9ctiD/JDKsyD9Xgu4hUhCSJBPig/w7duNajw==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/fastify"
+        },
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/fastify"
+        }
+      ],
+      "license": "MIT",
+      "dependencies": {
+        "@fastify/forwarded": "^3.0.0",
+        "ipaddr.js": "^2.1.0"
+      }
+    },
     "node_modules/@jridgewell/sourcemap-codec": {
       "version": "1.5.5",
       "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
@@ -426,6 +618,23 @@
       "dev": true,
       "license": "MIT"
     },
+    "node_modules/@minimistjs/subarg": {
+      "version": "1.0.0",
+      "resolved": "https://registry.npmjs.org/@minimistjs/subarg/-/subarg-1.0.0.tgz",
+      "integrity": "sha512-Q/ONBiM2zNeYUy0mVSO44mWWKYM3UHuEK43PKIOzJCbvUnPoMH1K+gk3cf1kgnCVJFlWmddahQQCmrmBGlk9jQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "minimist": "^1.1.0"
+      }
+    },
+    "node_modules/@pinojs/redact": {
+      "version": "0.4.0",
+      "resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz",
+      "integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/@rollup/rollup-android-arm-eabi": {
       "version": "4.62.2",
       "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.62.2.tgz",
@@ -776,6 +985,37 @@
         "win32"
       ]
     },
+    "node_modules/@types/autocannon": {
+      "version": "7.12.7",
+      "resolved": "https://registry.npmjs.org/@types/autocannon/-/autocannon-7.12.7.tgz",
+      "integrity": "sha512-Pd4nPf7wRpacULa6D/EC9x3CwzFQXwA0z5WFuik/fvJjW44V3WzBTM3jtt8nSBoflUNgswPiMCtgrr1bwnAcMg==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@types/node": "*"
+      }
+    },
+    "node_modules/@types/body-parser": {
+      "version": "1.19.6",
+      "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz",
+      "integrity": "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@types/connect": "*",
+        "@types/node": "*"
+      }
+    },
+    "node_modules/@types/connect": {
+      "version": "3.4.38",
+      "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz",
+      "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@types/node": "*"
+      }
+    },
     "node_modules/@types/estree": {
       "version": "1.0.9",
       "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
@@ -783,6 +1023,38 @@
       "dev": true,
       "license": "MIT"
     },
+    "node_modules/@types/express": {
+      "version": "5.0.6",
+      "resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.6.tgz",
+      "integrity": "sha512-sKYVuV7Sv9fbPIt/442koC7+IIwK5olP1KWeD88e/idgoJqDm3JV/YUiPwkoKK92ylff2MGxSz1CSjsXelx0YA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@types/body-parser": "*",
+        "@types/express-serve-static-core": "^5.0.0",
+        "@types/serve-static": "^2"
+      }
+    },
+    "node_modules/@types/express-serve-static-core": {
+      "version": "5.1.1",
+      "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-5.1.1.tgz",
+      "integrity": "sha512-v4zIMr/cX7/d2BpAEX3KNKL/JrT1s43s96lLvvdTmza1oEvDudCqK9aF/djc/SWgy8Yh0h30TZx5VpzqFCxk5A==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@types/node": "*",
+        "@types/qs": "*",
+        "@types/range-parser": "*",
+        "@types/send": "*"
+      }
+    },
+    "node_modules/@types/http-errors": {
+      "version": "2.0.5",
+      "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz",
+      "integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/@types/node": {
       "version": "18.19.130",
       "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.130.tgz",
@@ -793,6 +1065,41 @@
         "undici-types": "~5.26.4"
       }
     },
+    "node_modules/@types/qs": {
+      "version": "6.15.1",
+      "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.15.1.tgz",
+      "integrity": "sha512-GZHUBZR9hckSUhrxmp1nG6NwdpM9fCunJwyThLW1X3AyHgd9IlHb6VANpQQqDr2o/qQp6McZ3y/IA2rVzKzSbw==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/@types/range-parser": {
+      "version": "1.2.7",
+      "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz",
+      "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/@types/send": {
+      "version": "1.2.1",
+      "resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz",
+      "integrity": "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@types/node": "*"
+      }
+    },
+    "node_modules/@types/serve-static": {
+      "version": "2.2.0",
+      "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-2.2.0.tgz",
+      "integrity": "sha512-8mam4H1NHLtu7nmtalF7eyBH14QyOASmcxHhSfEoRyr0nP/YdoesEtU+uSRvMe96TW/HPTtkoKqQLl53N7UXMQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@types/http-errors": "*",
+        "@types/node": "*"
+      }
+    },
     "node_modules/@types/ws": {
       "version": "8.18.1",
       "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
@@ -916,6 +1223,88 @@
         "url": "https://opencollective.com/vitest"
       }
     },
+    "node_modules/abstract-logging": {
+      "version": "2.0.1",
+      "resolved": "https://registry.npmjs.org/abstract-logging/-/abstract-logging-2.0.1.tgz",
+      "integrity": "sha512-2BjRTZxTPvheOvGbBslFSYOUkr+SjPtOnrLP33f+VIWLzezQpZcqVg7ja3L4dBXmzzgwT+a029jRx5PCi3JuiA==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/accepts": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",
+      "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "mime-types": "^3.0.0",
+        "negotiator": "^1.0.0"
+      },
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/ajv": {
+      "version": "8.20.0",
+      "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
+      "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "fast-deep-equal": "^3.1.3",
+        "fast-uri": "^3.0.1",
+        "json-schema-traverse": "^1.0.0",
+        "require-from-string": "^2.0.2"
+      },
+      "funding": {
+        "type": "github",
+        "url": "https://github.com/sponsors/epoberezkin"
+      }
+    },
+    "node_modules/ajv-formats": {
+      "version": "3.0.1",
+      "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz",
+      "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "ajv": "^8.0.0"
+      },
+      "peerDependencies": {
+        "ajv": "^8.0.0"
+      },
+      "peerDependenciesMeta": {
+        "ajv": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/ansi-regex": {
+      "version": "5.0.1",
+      "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
+      "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/ansi-styles": {
+      "version": "4.3.0",
+      "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
+      "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "color-convert": "^2.0.1"
+      },
+      "engines": {
+        "node": ">=8"
+      },
+      "funding": {
+        "url": "https://github.com/chalk/ansi-styles?sponsor=1"
+      }
+    },
     "node_modules/assertion-error": {
       "version": "2.0.1",
       "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
@@ -926,6 +1315,174 @@
         "node": ">=12"
       }
     },
+    "node_modules/asynckit": {
+      "version": "0.4.0",
+      "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
+      "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/atomic-sleep": {
+      "version": "1.0.0",
+      "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz",
+      "integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=8.0.0"
+      }
+    },
+    "node_modules/autocannon": {
+      "version": "8.0.0",
+      "resolved": "https://registry.npmjs.org/autocannon/-/autocannon-8.0.0.tgz",
+      "integrity": "sha512-fMMcWc2JPFcUaqHeR6+PbmEpTxCrPZyBUM95oG4w3ngJ8NfBNas/ZXA+pTHXLqJ0UlFVTcy05GC25WxKx/M20A==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@minimistjs/subarg": "^1.0.0",
+        "chalk": "^4.1.0",
+        "char-spinner": "^1.0.1",
+        "cli-table3": "^0.6.0",
+        "color-support": "^1.1.1",
+        "cross-argv": "^2.0.0",
+        "form-data": "^4.0.0",
+        "has-async-hooks": "^1.0.0",
+        "hdr-histogram-js": "^3.0.0",
+        "hdr-histogram-percentiles-obj": "^3.0.0",
+        "http-parser-js": "^0.5.2",
+        "hyperid": "^3.0.0",
+        "lodash.chunk": "^4.2.0",
+        "lodash.clonedeep": "^4.5.0",
+        "lodash.flatten": "^4.4.0",
+        "manage-path": "^2.0.0",
+        "on-net-listen": "^1.1.1",
+        "pretty-bytes": "^5.4.1",
+        "progress": "^2.0.3",
+        "reinterval": "^1.1.0",
+        "retimer": "^3.0.0",
+        "semver": "^7.3.2",
+        "timestring": "^6.0.0"
+      },
+      "bin": {
+        "autocannon": "autocannon.js"
+      }
+    },
+    "node_modules/avvio": {
+      "version": "9.2.0",
+      "resolved": "https://registry.npmjs.org/avvio/-/avvio-9.2.0.tgz",
+      "integrity": "sha512-2t/sy01ArdHHE0vRH5Hsay+RtCZt3dLPji7W7/MMOCEgze5b7SNDC4j5H6FnVgPkI1MTNFGzHdHrVXDDl7QSSQ==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/fastify"
+        },
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/fastify"
+        }
+      ],
+      "license": "MIT",
+      "dependencies": {
+        "@fastify/error": "^4.0.0",
+        "fastq": "^1.17.1"
+      }
+    },
+    "node_modules/base64-js": {
+      "version": "1.5.1",
+      "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
+      "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/feross"
+        },
+        {
+          "type": "patreon",
+          "url": "https://www.patreon.com/feross"
+        },
+        {
+          "type": "consulting",
+          "url": "https://feross.org/support"
+        }
+      ],
+      "license": "MIT"
+    },
+    "node_modules/body-parser": {
+      "version": "2.3.0",
+      "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz",
+      "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "bytes": "^3.1.2",
+        "content-type": "^2.0.0",
+        "debug": "^4.4.3",
+        "http-errors": "^2.0.1",
+        "iconv-lite": "^0.7.2",
+        "on-finished": "^2.4.1",
+        "qs": "^6.15.2",
+        "raw-body": "^3.0.2",
+        "type-is": "^2.1.0"
+      },
+      "engines": {
+        "node": ">=18"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/body-parser/node_modules/content-type": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz",
+      "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=18"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/buffer": {
+      "version": "5.7.1",
+      "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",
+      "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/feross"
+        },
+        {
+          "type": "patreon",
+          "url": "https://www.patreon.com/feross"
+        },
+        {
+          "type": "consulting",
+          "url": "https://feross.org/support"
+        }
+      ],
+      "license": "MIT",
+      "dependencies": {
+        "base64-js": "^1.3.1",
+        "ieee754": "^1.1.13"
+      }
+    },
+    "node_modules/bytes": {
+      "version": "3.1.2",
+      "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
+      "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
     "node_modules/cac": {
       "version": "6.7.14",
       "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz",
@@ -936,6 +1493,37 @@
         "node": ">=8"
       }
     },
+    "node_modules/call-bind-apply-helpers": {
+      "version": "1.0.2",
+      "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
+      "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "es-errors": "^1.3.0",
+        "function-bind": "^1.1.2"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/call-bound": {
+      "version": "1.0.4",
+      "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
+      "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "call-bind-apply-helpers": "^1.0.2",
+        "get-intrinsic": "^1.3.0"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
     "node_modules/chai": {
       "version": "5.3.3",
       "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz",
@@ -953,6 +1541,30 @@
         "node": ">=18"
       }
     },
+    "node_modules/chalk": {
+      "version": "4.1.2",
+      "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
+      "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "ansi-styles": "^4.1.0",
+        "supports-color": "^7.1.0"
+      },
+      "engines": {
+        "node": ">=10"
+      },
+      "funding": {
+        "url": "https://github.com/chalk/chalk?sponsor=1"
+      }
+    },
+    "node_modules/char-spinner": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/char-spinner/-/char-spinner-1.0.1.tgz",
+      "integrity": "sha512-acv43vqJ0+N0rD+Uw3pDHSxP30FHrywu2NO6/wBaHChJIizpDeBUd6NjqhNhy9LGaEAhZAXn46QzmlAvIWd16g==",
+      "dev": true,
+      "license": "ISC"
+    },
     "node_modules/check-error": {
       "version": "2.1.3",
       "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz",
@@ -963,6 +1575,116 @@
         "node": ">= 16"
       }
     },
+    "node_modules/cli-table3": {
+      "version": "0.6.5",
+      "resolved": "https://registry.npmjs.org/cli-table3/-/cli-table3-0.6.5.tgz",
+      "integrity": "sha512-+W/5efTR7y5HRD7gACw9yQjqMVvEMLBHmboM/kPWam+H+Hmyrgjh6YncVKK122YZkXrLudzTuAukUw9FnMf7IQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "string-width": "^4.2.0"
+      },
+      "engines": {
+        "node": "10.* || >= 12.*"
+      },
+      "optionalDependencies": {
+        "@colors/colors": "1.5.0"
+      }
+    },
+    "node_modules/color-convert": {
+      "version": "2.0.1",
+      "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
+      "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "color-name": "~1.1.4"
+      },
+      "engines": {
+        "node": ">=7.0.0"
+      }
+    },
+    "node_modules/color-name": {
+      "version": "1.1.4",
+      "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
+      "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/color-support": {
+      "version": "1.1.3",
+      "resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz",
+      "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==",
+      "dev": true,
+      "license": "ISC",
+      "bin": {
+        "color-support": "bin.js"
+      }
+    },
+    "node_modules/combined-stream": {
+      "version": "1.0.8",
+      "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
+      "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "delayed-stream": "~1.0.0"
+      },
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/content-disposition": {
+      "version": "1.1.0",
+      "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz",
+      "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=18"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/content-type": {
+      "version": "1.0.5",
+      "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
+      "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/cookie": {
+      "version": "0.7.2",
+      "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
+      "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/cookie-signature": {
+      "version": "1.2.2",
+      "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",
+      "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=6.6.0"
+      }
+    },
+    "node_modules/cross-argv": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/cross-argv/-/cross-argv-2.0.0.tgz",
+      "integrity": "sha512-YIaY9TR5Nxeb8SMdtrU8asWVM4jqJDNDYlKV21LxtYcfNJhp1kEsgSa6qXwXgzN0WQWGODps0+TlGp2xQSHwOg==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/debug": {
       "version": "4.4.3",
       "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
@@ -991,6 +1713,95 @@
         "node": ">=6"
       }
     },
+    "node_modules/delayed-stream": {
+      "version": "1.0.0",
+      "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
+      "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=0.4.0"
+      }
+    },
+    "node_modules/depd": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
+      "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/dequal": {
+      "version": "2.0.3",
+      "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",
+      "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=6"
+      }
+    },
+    "node_modules/dunder-proto": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
+      "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "call-bind-apply-helpers": "^1.0.1",
+        "es-errors": "^1.3.0",
+        "gopd": "^1.2.0"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/ee-first": {
+      "version": "1.1.1",
+      "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
+      "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/emoji-regex": {
+      "version": "8.0.0",
+      "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
+      "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/encodeurl": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
+      "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/es-define-property": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
+      "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/es-errors": {
+      "version": "1.3.0",
+      "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
+      "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
     "node_modules/es-module-lexer": {
       "version": "1.7.0",
       "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz",
@@ -998,6 +1809,35 @@
       "dev": true,
       "license": "MIT"
     },
+    "node_modules/es-object-atoms": {
+      "version": "1.1.2",
+      "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz",
+      "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "es-errors": "^1.3.0"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/es-set-tostringtag": {
+      "version": "2.1.0",
+      "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
+      "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "es-errors": "^1.3.0",
+        "get-intrinsic": "^1.2.6",
+        "has-tostringtag": "^1.0.2",
+        "hasown": "^2.0.2"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
     "node_modules/esbuild": {
       "version": "0.21.5",
       "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz",
@@ -1037,6 +1877,13 @@
         "@esbuild/win32-x64": "0.21.5"
       }
     },
+    "node_modules/escape-html": {
+      "version": "1.0.3",
+      "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
+      "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/estree-walker": {
       "version": "3.0.3",
       "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
@@ -1047,6 +1894,16 @@
         "@types/estree": "^1.0.0"
       }
     },
+    "node_modules/etag": {
+      "version": "1.8.1",
+      "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
+      "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
     "node_modules/expect-type": {
       "version": "1.4.0",
       "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
@@ -1057,6 +1914,257 @@
         "node": ">=12.0.0"
       }
     },
+    "node_modules/express": {
+      "version": "5.2.1",
+      "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz",
+      "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "accepts": "^2.0.0",
+        "body-parser": "^2.2.1",
+        "content-disposition": "^1.0.0",
+        "content-type": "^1.0.5",
+        "cookie": "^0.7.1",
+        "cookie-signature": "^1.2.1",
+        "debug": "^4.4.0",
+        "depd": "^2.0.0",
+        "encodeurl": "^2.0.0",
+        "escape-html": "^1.0.3",
+        "etag": "^1.8.1",
+        "finalhandler": "^2.1.0",
+        "fresh": "^2.0.0",
+        "http-errors": "^2.0.0",
+        "merge-descriptors": "^2.0.0",
+        "mime-types": "^3.0.0",
+        "on-finished": "^2.4.1",
+        "once": "^1.4.0",
+        "parseurl": "^1.3.3",
+        "proxy-addr": "^2.0.7",
+        "qs": "^6.14.0",
+        "range-parser": "^1.2.1",
+        "router": "^2.2.0",
+        "send": "^1.1.0",
+        "serve-static": "^2.2.0",
+        "statuses": "^2.0.1",
+        "type-is": "^2.0.1",
+        "vary": "^1.1.2"
+      },
+      "engines": {
+        "node": ">= 18"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/fast-decode-uri-component": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/fast-decode-uri-component/-/fast-decode-uri-component-1.0.1.tgz",
+      "integrity": "sha512-WKgKWg5eUxvRZGwW8FvfbaH7AXSh2cL+3j5fMGzUMCxWBJ3dV3a7Wz8y2f/uQ0e3B6WmodD3oS54jTQ9HVTIIg==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/fast-deep-equal": {
+      "version": "3.1.3",
+      "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
+      "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/fast-json-stringify": {
+      "version": "7.0.0",
+      "resolved": "https://registry.npmjs.org/fast-json-stringify/-/fast-json-stringify-7.0.0.tgz",
+      "integrity": "sha512-YV53BAbR3Qwq37wfD1oZ97YJ0nYj6CwfzKXQ38ock9XxI2EnLOdl5psKms6Evook6ACckytZJOaKY0ThmIi1uw==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/fastify"
+        },
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/fastify"
+        }
+      ],
+      "license": "MIT",
+      "dependencies": {
+        "@fastify/merge-json-schemas": "^0.2.0",
+        "ajv": "^8.12.0",
+        "ajv-formats": "^3.0.1",
+        "fast-uri": "^3.0.0",
+        "json-schema-ref-resolver": "^3.0.0",
+        "rfdc": "^1.2.0"
+      }
+    },
+    "node_modules/fast-querystring": {
+      "version": "1.1.2",
+      "resolved": "https://registry.npmjs.org/fast-querystring/-/fast-querystring-1.1.2.tgz",
+      "integrity": "sha512-g6KuKWmFXc0fID8WWH0jit4g0AGBoJhCkJMb1RmbsSEUNvQ+ZC8D6CUZ+GtF8nMzSPXnhiePyyqqipzNNEnHjg==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "fast-decode-uri-component": "^1.0.1"
+      }
+    },
+    "node_modules/fast-uri": {
+      "version": "3.1.3",
+      "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.3.tgz",
+      "integrity": "sha512-i70LwGWUduXqzicKXWshooq+sWL1K3WUU5rKZNG/0i3a1OSoX3HqhH5WbWwTmqWfor4urUakGPiRQcleRZTwOg==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/fastify"
+        },
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/fastify"
+        }
+      ],
+      "license": "BSD-3-Clause"
+    },
+    "node_modules/fastify": {
+      "version": "5.10.0",
+      "resolved": "https://registry.npmjs.org/fastify/-/fastify-5.10.0.tgz",
+      "integrity": "sha512-A9L0ziuWGQHgEEVgF3davQ9vbD93IuX+lo2IsxapQmu5b/Y/ynn9m9K5JHt9dvyJXOFc5iN0Zk5GHEOqnzhWjg==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/fastify"
+        },
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/fastify"
+        }
+      ],
+      "license": "MIT",
+      "dependencies": {
+        "@fastify/ajv-compiler": "^4.0.5",
+        "@fastify/error": "^4.0.0",
+        "@fastify/fast-json-stringify-compiler": "^5.0.0",
+        "@fastify/proxy-addr": "^5.0.0",
+        "abstract-logging": "^2.0.1",
+        "avvio": "^9.0.0",
+        "fast-json-stringify": "^7.0.0",
+        "find-my-way": "^9.6.0",
+        "light-my-request": "^6.0.0",
+        "pino": "^9.14.0 || ^10.1.0",
+        "process-warning": "^5.0.0",
+        "rfdc": "^1.3.1",
+        "secure-json-parse": "^4.0.0",
+        "semver": "^7.6.0",
+        "toad-cache": "^3.7.0"
+      }
+    },
+    "node_modules/fastq": {
+      "version": "1.20.1",
+      "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz",
+      "integrity": "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==",
+      "dev": true,
+      "license": "ISC",
+      "dependencies": {
+        "reusify": "^1.0.4"
+      }
+    },
+    "node_modules/finalhandler": {
+      "version": "2.1.1",
+      "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz",
+      "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "debug": "^4.4.0",
+        "encodeurl": "^2.0.0",
+        "escape-html": "^1.0.3",
+        "on-finished": "^2.4.1",
+        "parseurl": "^1.3.3",
+        "statuses": "^2.0.1"
+      },
+      "engines": {
+        "node": ">= 18.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/find-my-way": {
+      "version": "9.6.0",
+      "resolved": "https://registry.npmjs.org/find-my-way/-/find-my-way-9.6.0.tgz",
+      "integrity": "sha512-Zf4Xve4RymLl7NgaavNebZ01joJ8MfVerOG43wy7SHLO+r+K0C6d/SE0BiR7AV5V1VOCFlOP7ecdo+I4qmiHrQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "fast-deep-equal": "^3.1.3",
+        "fast-querystring": "^1.0.0",
+        "safe-regex2": "^5.0.0"
+      },
+      "engines": {
+        "node": ">=20"
+      }
+    },
+    "node_modules/form-data": {
+      "version": "4.0.6",
+      "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz",
+      "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "asynckit": "^0.4.0",
+        "combined-stream": "^1.0.8",
+        "es-set-tostringtag": "^2.1.0",
+        "hasown": "^2.0.4",
+        "mime-types": "^2.1.35"
+      },
+      "engines": {
+        "node": ">= 6"
+      }
+    },
+    "node_modules/form-data/node_modules/mime-db": {
+      "version": "1.52.0",
+      "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
+      "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/form-data/node_modules/mime-types": {
+      "version": "2.1.35",
+      "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
+      "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "mime-db": "1.52.0"
+      },
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/forwarded": {
+      "version": "0.2.0",
+      "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
+      "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/fresh": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz",
+      "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
     "node_modules/fsevents": {
       "version": "2.3.3",
       "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
@@ -1072,6 +2180,68 @@
         "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
       }
     },
+    "node_modules/function-bind": {
+      "version": "1.1.2",
+      "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
+      "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
+      "dev": true,
+      "license": "MIT",
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/get-intrinsic": {
+      "version": "1.3.0",
+      "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
+      "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "call-bind-apply-helpers": "^1.0.2",
+        "es-define-property": "^1.0.1",
+        "es-errors": "^1.3.0",
+        "es-object-atoms": "^1.1.1",
+        "function-bind": "^1.1.2",
+        "get-proto": "^1.0.1",
+        "gopd": "^1.2.0",
+        "has-symbols": "^1.1.0",
+        "hasown": "^2.0.2",
+        "math-intrinsics": "^1.1.0"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/get-proto": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
+      "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "dunder-proto": "^1.0.1",
+        "es-object-atoms": "^1.0.0"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/gopd": {
+      "version": "1.2.0",
+      "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
+      "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
     "node_modules/graphql": {
       "version": "16.14.2",
       "resolved": "https://registry.npmjs.org/graphql/-/graphql-16.14.2.tgz",
@@ -1082,6 +2252,300 @@
         "node": "^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0"
       }
     },
+    "node_modules/has-async-hooks": {
+      "version": "1.0.0",
+      "resolved": "https://registry.npmjs.org/has-async-hooks/-/has-async-hooks-1.0.0.tgz",
+      "integrity": "sha512-YF0VPGjkxr7AyyQQNykX8zK4PvtEDsUJAPqwu06UFz1lb6EvI53sPh5H1kWxg8NXI5LsfRCZ8uX9NkYDZBb/mw==",
+      "dev": true,
+      "license": "Apache-2.0"
+    },
+    "node_modules/has-flag": {
+      "version": "4.0.0",
+      "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
+      "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/has-symbols": {
+      "version": "1.1.0",
+      "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
+      "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/has-tostringtag": {
+      "version": "1.0.2",
+      "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
+      "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "has-symbols": "^1.0.3"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/hasown": {
+      "version": "2.0.4",
+      "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",
+      "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "function-bind": "^1.1.2"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/hdr-histogram-js": {
+      "version": "3.0.1",
+      "resolved": "https://registry.npmjs.org/hdr-histogram-js/-/hdr-histogram-js-3.0.1.tgz",
+      "integrity": "sha512-l3GSdZL1Jr1C0kyb461tUjEdrRPZr8Qry7jByltf5JGrA0xvqOSrxRBfcrJqqV/AMEtqqhHhC6w8HW0gn76tRQ==",
+      "dev": true,
+      "license": "BSD-2-Clause",
+      "dependencies": {
+        "@assemblyscript/loader": "^0.19.21",
+        "base64-js": "^1.2.0",
+        "pako": "^1.0.3"
+      },
+      "engines": {
+        "node": ">=14"
+      }
+    },
+    "node_modules/hdr-histogram-percentiles-obj": {
+      "version": "3.0.0",
+      "resolved": "https://registry.npmjs.org/hdr-histogram-percentiles-obj/-/hdr-histogram-percentiles-obj-3.0.0.tgz",
+      "integrity": "sha512-7kIufnBqdsBGcSZLPJwqHT3yhk1QTsSlFsVD3kx5ixH/AlgBs9yM1q6DPhXZ8f8gtdqgh7N7/5btRLpQsS2gHw==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/http-errors": {
+      "version": "2.0.1",
+      "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
+      "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "depd": "~2.0.0",
+        "inherits": "~2.0.4",
+        "setprototypeof": "~1.2.0",
+        "statuses": "~2.0.2",
+        "toidentifier": "~1.0.1"
+      },
+      "engines": {
+        "node": ">= 0.8"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/http-parser-js": {
+      "version": "0.5.10",
+      "resolved": "https://registry.npmjs.org/http-parser-js/-/http-parser-js-0.5.10.tgz",
+      "integrity": "sha512-Pysuw9XpUq5dVc/2SMHpuTY01RFl8fttgcyunjL7eEMhGM3cI4eOmiCycJDVCo/7O7ClfQD3SaI6ftDzqOXYMA==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/hyperid": {
+      "version": "3.3.0",
+      "resolved": "https://registry.npmjs.org/hyperid/-/hyperid-3.3.0.tgz",
+      "integrity": "sha512-7qhCVT4MJIoEsNcbhglhdmBKb09QtcmJNiIQGq7js/Khf5FtQQ9bzcAuloeqBeee7XD7JqDeve9KNlQya5tSGQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "buffer": "^5.2.1",
+        "uuid": "^8.3.2",
+        "uuid-parse": "^1.1.0"
+      }
+    },
+    "node_modules/iconv-lite": {
+      "version": "0.7.3",
+      "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz",
+      "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "safer-buffer": ">= 2.1.2 < 3.0.0"
+      },
+      "engines": {
+        "node": ">=0.10.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/ieee754": {
+      "version": "1.2.1",
+      "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
+      "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/feross"
+        },
+        {
+          "type": "patreon",
+          "url": "https://www.patreon.com/feross"
+        },
+        {
+          "type": "consulting",
+          "url": "https://feross.org/support"
+        }
+      ],
+      "license": "BSD-3-Clause"
+    },
+    "node_modules/inherits": {
+      "version": "2.0.4",
+      "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
+      "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
+      "dev": true,
+      "license": "ISC"
+    },
+    "node_modules/ipaddr.js": {
+      "version": "2.4.0",
+      "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-2.4.0.tgz",
+      "integrity": "sha512-9VGk3HGanVE6JoZXHiCpnGy5X0jYDnN4EA4lntFPj+1vIWlFhIylq2CrrCOJH9EAhc5CYhq18F2Av2tgoAPsYQ==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 10"
+      }
+    },
+    "node_modules/is-fullwidth-code-point": {
+      "version": "3.0.0",
+      "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
+      "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/is-promise": {
+      "version": "4.0.0",
+      "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",
+      "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/json-schema-ref-resolver": {
+      "version": "3.0.0",
+      "resolved": "https://registry.npmjs.org/json-schema-ref-resolver/-/json-schema-ref-resolver-3.0.0.tgz",
+      "integrity": "sha512-hOrZIVL5jyYFjzk7+y7n5JDzGlU8rfWDuYyHwGa2WA8/pcmMHezp2xsVwxrebD/Q9t8Nc5DboieySDpCp4WG4A==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/fastify"
+        },
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/fastify"
+        }
+      ],
+      "license": "MIT",
+      "dependencies": {
+        "dequal": "^2.0.3"
+      }
+    },
+    "node_modules/json-schema-traverse": {
+      "version": "1.0.0",
+      "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
+      "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/light-my-request": {
+      "version": "6.6.0",
+      "resolved": "https://registry.npmjs.org/light-my-request/-/light-my-request-6.6.0.tgz",
+      "integrity": "sha512-CHYbu8RtboSIoVsHZ6Ye4cj4Aw/yg2oAFimlF7mNvfDV192LR7nDiKtSIfCuLT7KokPSTn/9kfVLm5OGN0A28A==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/fastify"
+        },
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/fastify"
+        }
+      ],
+      "license": "BSD-3-Clause",
+      "dependencies": {
+        "cookie": "^1.0.1",
+        "process-warning": "^4.0.0",
+        "set-cookie-parser": "^2.6.0"
+      }
+    },
+    "node_modules/light-my-request/node_modules/cookie": {
+      "version": "1.1.1",
+      "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz",
+      "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=18"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/light-my-request/node_modules/process-warning": {
+      "version": "4.0.1",
+      "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-4.0.1.tgz",
+      "integrity": "sha512-3c2LzQ3rY9d0hc1emcsHhfT9Jwz0cChib/QN89oME2R451w5fy3f0afAhERFZAwrbDU43wk12d0ORBpDVME50Q==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/fastify"
+        },
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/fastify"
+        }
+      ],
+      "license": "MIT"
+    },
+    "node_modules/lodash.chunk": {
+      "version": "4.2.0",
+      "resolved": "https://registry.npmjs.org/lodash.chunk/-/lodash.chunk-4.2.0.tgz",
+      "integrity": "sha512-ZzydJKfUHJwHa+hF5X66zLFCBrWn5GeF28OHEr4WVWtNDXlQ/IjWKPBiikqKo2ne0+v6JgCgJ0GzJp8k8bHC7w==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/lodash.clonedeep": {
+      "version": "4.5.0",
+      "resolved": "https://registry.npmjs.org/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz",
+      "integrity": "sha512-H5ZhCF25riFd9uB5UCkVKo61m3S/xZk1x4wA6yp/L3RFP6Z/eHH1ymQcGLo7J3GMPfm0V/7m1tryHuGVxpqEBQ==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/lodash.flatten": {
+      "version": "4.4.0",
+      "resolved": "https://registry.npmjs.org/lodash.flatten/-/lodash.flatten-4.4.0.tgz",
+      "integrity": "sha512-C5N2Z3DgnnKr0LOpv/hKCgKdb7ZZwafIrsesve6lmzvZIRZRGaZ/l6Q8+2W7NaT+ZwO3fFlSCzCzrDCFdJfZ4g==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/loupe": {
       "version": "3.2.1",
       "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",
@@ -1099,6 +2563,83 @@
         "@jridgewell/sourcemap-codec": "^1.5.5"
       }
     },
+    "node_modules/manage-path": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/manage-path/-/manage-path-2.0.0.tgz",
+      "integrity": "sha512-NJhyB+PJYTpxhxZJ3lecIGgh4kwIY2RAh44XvAz9UlqthlQwtPBf62uBVR8XaD8CRuSjQ6TnZH2lNJkbLPZM2A==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/math-intrinsics": {
+      "version": "1.1.0",
+      "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
+      "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/media-typer": {
+      "version": "1.1.0",
+      "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz",
+      "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/merge-descriptors": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",
+      "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=18"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
+    "node_modules/mime-db": {
+      "version": "1.54.0",
+      "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",
+      "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/mime-types": {
+      "version": "3.0.2",
+      "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz",
+      "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "mime-db": "^1.54.0"
+      },
+      "engines": {
+        "node": ">=18"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/minimist": {
+      "version": "1.2.8",
+      "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
+      "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
+      "dev": true,
+      "license": "MIT",
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
     "node_modules/ms": {
       "version": "2.1.3",
       "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
@@ -1125,6 +2666,100 @@
         "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
       }
     },
+    "node_modules/negotiator": {
+      "version": "1.0.0",
+      "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",
+      "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/object-inspect": {
+      "version": "1.13.4",
+      "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
+      "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/on-exit-leak-free": {
+      "version": "2.1.2",
+      "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz",
+      "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=14.0.0"
+      }
+    },
+    "node_modules/on-finished": {
+      "version": "2.4.1",
+      "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
+      "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "ee-first": "1.1.1"
+      },
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/on-net-listen": {
+      "version": "1.1.2",
+      "resolved": "https://registry.npmjs.org/on-net-listen/-/on-net-listen-1.1.2.tgz",
+      "integrity": "sha512-y1HRYy8s/RlcBvDUwKXSmkODMdx4KSuIvloCnQYJ2LdBBC1asY4HtfhXwe3UWknLakATZDnbzht2Ijw3M1EqFg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=9.4.0 || ^8.9.4"
+      }
+    },
+    "node_modules/once": {
+      "version": "1.4.0",
+      "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
+      "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
+      "dev": true,
+      "license": "ISC",
+      "dependencies": {
+        "wrappy": "1"
+      }
+    },
+    "node_modules/pako": {
+      "version": "1.0.11",
+      "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz",
+      "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==",
+      "dev": true,
+      "license": "(MIT AND Zlib)"
+    },
+    "node_modules/parseurl": {
+      "version": "1.3.3",
+      "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
+      "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/path-to-regexp": {
+      "version": "8.4.2",
+      "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz",
+      "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==",
+      "dev": true,
+      "license": "MIT",
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
     "node_modules/pathe": {
       "version": "1.1.2",
       "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz",
@@ -1149,6 +2784,46 @@
       "dev": true,
       "license": "ISC"
     },
+    "node_modules/pino": {
+      "version": "10.3.1",
+      "resolved": "https://registry.npmjs.org/pino/-/pino-10.3.1.tgz",
+      "integrity": "sha512-r34yH/GlQpKZbU1BvFFqOjhISRo1MNx1tWYsYvmj6KIRHSPMT2+yHOEb1SG6NMvRoHRF0a07kCOox/9yakl1vg==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@pinojs/redact": "^0.4.0",
+        "atomic-sleep": "^1.0.0",
+        "on-exit-leak-free": "^2.1.0",
+        "pino-abstract-transport": "^3.0.0",
+        "pino-std-serializers": "^7.0.0",
+        "process-warning": "^5.0.0",
+        "quick-format-unescaped": "^4.0.3",
+        "real-require": "^0.2.0",
+        "safe-stable-stringify": "^2.3.1",
+        "sonic-boom": "^4.0.1",
+        "thread-stream": "^4.0.0"
+      },
+      "bin": {
+        "pino": "bin.js"
+      }
+    },
+    "node_modules/pino-abstract-transport": {
+      "version": "3.0.0",
+      "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-3.0.0.tgz",
+      "integrity": "sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "split2": "^4.0.0"
+      }
+    },
+    "node_modules/pino-std-serializers": {
+      "version": "7.1.0",
+      "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.1.0.tgz",
+      "integrity": "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/postcss": {
       "version": "8.5.15",
       "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.15.tgz",
@@ -1178,12 +2853,192 @@
         "node": "^10 || ^12 || >=14"
       }
     },
+    "node_modules/pretty-bytes": {
+      "version": "5.6.0",
+      "resolved": "https://registry.npmjs.org/pretty-bytes/-/pretty-bytes-5.6.0.tgz",
+      "integrity": "sha512-FFw039TmrBqFK8ma/7OL3sDz/VytdtJr044/QUJtH0wK9lb9jLq9tJyIxUwtQJHwar2BqtiA4iCWSwo9JLkzFg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=6"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
+    "node_modules/process-warning": {
+      "version": "5.0.0",
+      "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.0.0.tgz",
+      "integrity": "sha512-a39t9ApHNx2L4+HBnQKqxxHNs1r7KF+Intd8Q/g1bUh6q0WIp9voPXJ/x0j+ZL45KF1pJd9+q2jLIRMfvEshkA==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/fastify"
+        },
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/fastify"
+        }
+      ],
+      "license": "MIT"
+    },
+    "node_modules/progress": {
+      "version": "2.0.3",
+      "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz",
+      "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=0.4.0"
+      }
+    },
+    "node_modules/proxy-addr": {
+      "version": "2.0.7",
+      "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
+      "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "forwarded": "0.2.0",
+        "ipaddr.js": "1.9.1"
+      },
+      "engines": {
+        "node": ">= 0.10"
+      }
+    },
+    "node_modules/proxy-addr/node_modules/ipaddr.js": {
+      "version": "1.9.1",
+      "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
+      "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.10"
+      }
+    },
+    "node_modules/qs": {
+      "version": "6.15.3",
+      "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz",
+      "integrity": "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==",
+      "dev": true,
+      "license": "BSD-3-Clause",
+      "dependencies": {
+        "es-define-property": "^1.0.1",
+        "side-channel": "^1.1.1"
+      },
+      "engines": {
+        "node": ">=0.6"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/quick-format-unescaped": {
+      "version": "4.0.4",
+      "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz",
+      "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/range-parser": {
+      "version": "1.3.0",
+      "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz",
+      "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/raw-body": {
+      "version": "3.0.2",
+      "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz",
+      "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "bytes": "~3.1.2",
+        "http-errors": "~2.0.1",
+        "iconv-lite": "~0.7.0",
+        "unpipe": "~1.0.0"
+      },
+      "engines": {
+        "node": ">= 0.10"
+      }
+    },
+    "node_modules/real-require": {
+      "version": "0.2.0",
+      "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz",
+      "integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 12.13.0"
+      }
+    },
     "node_modules/reflect-metadata": {
       "version": "0.2.2",
       "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz",
       "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==",
       "license": "Apache-2.0"
     },
+    "node_modules/reinterval": {
+      "version": "1.1.0",
+      "resolved": "https://registry.npmjs.org/reinterval/-/reinterval-1.1.0.tgz",
+      "integrity": "sha512-QIRet3SYrGp0HUHO88jVskiG6seqUGC5iAG7AwI/BV4ypGcuqk9Du6YQBUOUqm9c8pw1eyLoIaONifRua1lsEQ==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/require-from-string": {
+      "version": "2.0.2",
+      "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
+      "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=0.10.0"
+      }
+    },
+    "node_modules/ret": {
+      "version": "0.5.0",
+      "resolved": "https://registry.npmjs.org/ret/-/ret-0.5.0.tgz",
+      "integrity": "sha512-I1XxrZSQ+oErkRR4jYbAyEEu2I0avBvvMM5JN+6EBprOGRCs63ENqZ3vjavq8fBw2+62G5LF5XelKwuJpcvcxw==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=10"
+      }
+    },
+    "node_modules/retimer": {
+      "version": "3.0.0",
+      "resolved": "https://registry.npmjs.org/retimer/-/retimer-3.0.0.tgz",
+      "integrity": "sha512-WKE0j11Pa0ZJI5YIk0nflGI7SQsfl2ljihVy7ogh7DeQSeYAUi0ubZ/yEueGtDfUPk6GH5LRw1hBdLq4IwUBWA==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/reusify": {
+      "version": "1.1.0",
+      "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz",
+      "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "iojs": ">=1.0.0",
+        "node": ">=0.10.0"
+      }
+    },
+    "node_modules/rfdc": {
+      "version": "1.4.1",
+      "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz",
+      "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/rollup": {
       "version": "4.62.2",
       "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.2.tgz",
@@ -1229,6 +3084,230 @@
         "fsevents": "~2.3.2"
       }
     },
+    "node_modules/router": {
+      "version": "2.2.0",
+      "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz",
+      "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "debug": "^4.4.0",
+        "depd": "^2.0.0",
+        "is-promise": "^4.0.0",
+        "parseurl": "^1.3.3",
+        "path-to-regexp": "^8.0.0"
+      },
+      "engines": {
+        "node": ">= 18"
+      }
+    },
+    "node_modules/safe-regex2": {
+      "version": "5.1.1",
+      "resolved": "https://registry.npmjs.org/safe-regex2/-/safe-regex2-5.1.1.tgz",
+      "integrity": "sha512-mOSBvHGDZMuIEZMdOz/aCEYDCv0E7nfcNsIhUF+/P+xC7Hyf3FkvymqgPbg9D1EdSGu+uKbJgy09K/RKKc7kJA==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/fastify"
+        },
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/fastify"
+        }
+      ],
+      "license": "MIT",
+      "dependencies": {
+        "ret": "~0.5.0"
+      },
+      "bin": {
+        "safe-regex2": "bin/safe-regex2.js"
+      }
+    },
+    "node_modules/safe-stable-stringify": {
+      "version": "2.5.0",
+      "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz",
+      "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=10"
+      }
+    },
+    "node_modules/safer-buffer": {
+      "version": "2.1.2",
+      "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
+      "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/secure-json-parse": {
+      "version": "4.1.0",
+      "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-4.1.0.tgz",
+      "integrity": "sha512-l4KnYfEyqYJxDwlNVyRfO2E4NTHfMKAWdUuA8J0yve2Dz/E/PdBepY03RvyJpssIpRFwJoCD55wA+mEDs6ByWA==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/fastify"
+        },
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/fastify"
+        }
+      ],
+      "license": "BSD-3-Clause"
+    },
+    "node_modules/semver": {
+      "version": "7.8.5",
+      "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
+      "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
+      "dev": true,
+      "license": "ISC",
+      "bin": {
+        "semver": "bin/semver.js"
+      },
+      "engines": {
+        "node": ">=10"
+      }
+    },
+    "node_modules/send": {
+      "version": "1.2.1",
+      "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz",
+      "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "debug": "^4.4.3",
+        "encodeurl": "^2.0.0",
+        "escape-html": "^1.0.3",
+        "etag": "^1.8.1",
+        "fresh": "^2.0.0",
+        "http-errors": "^2.0.1",
+        "mime-types": "^3.0.2",
+        "ms": "^2.1.3",
+        "on-finished": "^2.4.1",
+        "range-parser": "^1.2.1",
+        "statuses": "^2.0.2"
+      },
+      "engines": {
+        "node": ">= 18"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/serve-static": {
+      "version": "2.2.1",
+      "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz",
+      "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "encodeurl": "^2.0.0",
+        "escape-html": "^1.0.3",
+        "parseurl": "^1.3.3",
+        "send": "^1.2.0"
+      },
+      "engines": {
+        "node": ">= 18"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/set-cookie-parser": {
+      "version": "2.7.2",
+      "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz",
+      "integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/setprototypeof": {
+      "version": "1.2.0",
+      "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
+      "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
+      "dev": true,
+      "license": "ISC"
+    },
+    "node_modules/side-channel": {
+      "version": "1.1.1",
+      "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz",
+      "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "es-errors": "^1.3.0",
+        "object-inspect": "^1.13.4",
+        "side-channel-list": "^1.0.1",
+        "side-channel-map": "^1.0.1",
+        "side-channel-weakmap": "^1.0.2"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/side-channel-list": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",
+      "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "es-errors": "^1.3.0",
+        "object-inspect": "^1.13.4"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/side-channel-map": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
+      "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "call-bound": "^1.0.2",
+        "es-errors": "^1.3.0",
+        "get-intrinsic": "^1.2.5",
+        "object-inspect": "^1.13.3"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/side-channel-weakmap": {
+      "version": "1.0.2",
+      "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
+      "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "call-bound": "^1.0.2",
+        "es-errors": "^1.3.0",
+        "get-intrinsic": "^1.2.5",
+        "object-inspect": "^1.13.3",
+        "side-channel-map": "^1.0.1"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
     "node_modules/siginfo": {
       "version": "2.0.0",
       "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
@@ -1236,6 +3315,16 @@
       "dev": true,
       "license": "ISC"
     },
+    "node_modules/sonic-boom": {
+      "version": "4.2.1",
+      "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz",
+      "integrity": "sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "atomic-sleep": "^1.0.0"
+      }
+    },
     "node_modules/source-map-js": {
       "version": "1.2.1",
       "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
@@ -1246,6 +3335,16 @@
         "node": ">=0.10.0"
       }
     },
+    "node_modules/split2": {
+      "version": "4.2.0",
+      "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
+      "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",
+      "dev": true,
+      "license": "ISC",
+      "engines": {
+        "node": ">= 10.x"
+      }
+    },
     "node_modules/stackback": {
       "version": "0.0.2",
       "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
@@ -1253,6 +3352,16 @@
       "dev": true,
       "license": "MIT"
     },
+    "node_modules/statuses": {
+      "version": "2.0.2",
+      "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
+      "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
     "node_modules/std-env": {
       "version": "3.10.0",
       "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz",
@@ -1260,6 +3369,77 @@
       "dev": true,
       "license": "MIT"
     },
+    "node_modules/string-width": {
+      "version": "4.2.3",
+      "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
+      "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "emoji-regex": "^8.0.0",
+        "is-fullwidth-code-point": "^3.0.0",
+        "strip-ansi": "^6.0.1"
+      },
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/strip-ansi": {
+      "version": "6.0.1",
+      "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
+      "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "ansi-regex": "^5.0.1"
+      },
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/supports-color": {
+      "version": "7.2.0",
+      "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
+      "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "has-flag": "^4.0.0"
+      },
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/thread-stream": {
+      "version": "4.2.0",
+      "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-4.2.0.tgz",
+      "integrity": "sha512-e2zZ96wSChazBsbENf/Pcm/4swHt2cEKQ92rhUjkL9GCKiTDJIaTBenjE/m9DXi0QBmTMDkFDdOomUy20A1tDQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "real-require": "^1.0.0"
+      },
+      "engines": {
+        "node": ">=20"
+      }
+    },
+    "node_modules/thread-stream/node_modules/real-require": {
+      "version": "1.0.0",
+      "resolved": "https://registry.npmjs.org/real-require/-/real-require-1.0.0.tgz",
+      "integrity": "sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/timestring": {
+      "version": "6.0.0",
+      "resolved": "https://registry.npmjs.org/timestring/-/timestring-6.0.0.tgz",
+      "integrity": "sha512-wMctrWD2HZZLuIlchlkE2dfXJh7J2KDI9Dwl+2abPYg0mswQHfOAyQW3jJg1pY5VfttSINZuKcXoB3FGypVklA==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=8"
+      }
+    },
     "node_modules/tinybench": {
       "version": "2.9.0",
       "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
@@ -1304,6 +3484,511 @@
         "node": ">=14.0.0"
       }
     },
+    "node_modules/toad-cache": {
+      "version": "3.7.4",
+      "resolved": "https://registry.npmjs.org/toad-cache/-/toad-cache-3.7.4.tgz",
+      "integrity": "sha512-m1TdR/rvT7kgGJZhspNtXdsdYk0fddFpJJFlG5s+UkPFo6lkLoZ3YLOaovPYjq1R75NP5JfeTlSHaOsE09peCg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=20"
+      }
+    },
+    "node_modules/toidentifier": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
+      "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=0.6"
+      }
+    },
+    "node_modules/tsx": {
+      "version": "4.23.0",
+      "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.0.tgz",
+      "integrity": "sha512-eUdUIaCr963q2h5u3+QwvYp0+eqPvn+egeqZUm0hwERCqqx1E3kK5ehbGCvqSE5MQAULr67ww0cA3jKc3YkM1w==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "esbuild": "~0.28.0"
+      },
+      "bin": {
+        "tsx": "dist/cli.mjs"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      },
+      "optionalDependencies": {
+        "fsevents": "~2.3.3"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/aix-ppc64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",
+      "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==",
+      "cpu": [
+        "ppc64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "aix"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/android-arm": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz",
+      "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==",
+      "cpu": [
+        "arm"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "android"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/android-arm64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz",
+      "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "android"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/android-x64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz",
+      "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "android"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/darwin-arm64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz",
+      "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/darwin-x64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz",
+      "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/freebsd-arm64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz",
+      "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "freebsd"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/freebsd-x64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz",
+      "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "freebsd"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/linux-arm": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz",
+      "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==",
+      "cpu": [
+        "arm"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/linux-arm64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz",
+      "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/linux-ia32": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz",
+      "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==",
+      "cpu": [
+        "ia32"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/linux-loong64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz",
+      "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==",
+      "cpu": [
+        "loong64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/linux-mips64el": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz",
+      "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==",
+      "cpu": [
+        "mips64el"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/linux-ppc64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz",
+      "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==",
+      "cpu": [
+        "ppc64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/linux-riscv64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz",
+      "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==",
+      "cpu": [
+        "riscv64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/linux-s390x": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz",
+      "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==",
+      "cpu": [
+        "s390x"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/linux-x64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz",
+      "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/netbsd-x64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz",
+      "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "netbsd"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/openbsd-x64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz",
+      "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "openbsd"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/sunos-x64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz",
+      "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "sunos"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/win32-arm64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz",
+      "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/win32-ia32": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz",
+      "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==",
+      "cpu": [
+        "ia32"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/win32-x64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz",
+      "integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/esbuild": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",
+      "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==",
+      "dev": true,
+      "hasInstallScript": true,
+      "license": "MIT",
+      "bin": {
+        "esbuild": "bin/esbuild"
+      },
+      "engines": {
+        "node": ">=18"
+      },
+      "optionalDependencies": {
+        "@esbuild/aix-ppc64": "0.28.1",
+        "@esbuild/android-arm": "0.28.1",
+        "@esbuild/android-arm64": "0.28.1",
+        "@esbuild/android-x64": "0.28.1",
+        "@esbuild/darwin-arm64": "0.28.1",
+        "@esbuild/darwin-x64": "0.28.1",
+        "@esbuild/freebsd-arm64": "0.28.1",
+        "@esbuild/freebsd-x64": "0.28.1",
+        "@esbuild/linux-arm": "0.28.1",
+        "@esbuild/linux-arm64": "0.28.1",
+        "@esbuild/linux-ia32": "0.28.1",
+        "@esbuild/linux-loong64": "0.28.1",
+        "@esbuild/linux-mips64el": "0.28.1",
+        "@esbuild/linux-ppc64": "0.28.1",
+        "@esbuild/linux-riscv64": "0.28.1",
+        "@esbuild/linux-s390x": "0.28.1",
+        "@esbuild/linux-x64": "0.28.1",
+        "@esbuild/netbsd-arm64": "0.28.1",
+        "@esbuild/netbsd-x64": "0.28.1",
+        "@esbuild/openbsd-arm64": "0.28.1",
+        "@esbuild/openbsd-x64": "0.28.1",
+        "@esbuild/openharmony-arm64": "0.28.1",
+        "@esbuild/sunos-x64": "0.28.1",
+        "@esbuild/win32-arm64": "0.28.1",
+        "@esbuild/win32-ia32": "0.28.1",
+        "@esbuild/win32-x64": "0.28.1"
+      }
+    },
+    "node_modules/type-is": {
+      "version": "2.1.0",
+      "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz",
+      "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "content-type": "^2.0.0",
+        "media-typer": "^1.1.0",
+        "mime-types": "^3.0.0"
+      },
+      "engines": {
+        "node": ">= 18"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/type-is/node_modules/content-type": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz",
+      "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=18"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
     "node_modules/typescript": {
       "version": "5.9.3",
       "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
@@ -1325,6 +4010,44 @@
       "dev": true,
       "license": "MIT"
     },
+    "node_modules/unpipe": {
+      "version": "1.0.0",
+      "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
+      "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/uuid": {
+      "version": "8.3.2",
+      "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
+      "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
+      "deprecated": "uuid@10 and below is no longer supported.  For ESM codebases, update to uuid@latest.  For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).",
+      "dev": true,
+      "license": "MIT",
+      "bin": {
+        "uuid": "dist/bin/uuid"
+      }
+    },
+    "node_modules/uuid-parse": {
+      "version": "1.1.0",
+      "resolved": "https://registry.npmjs.org/uuid-parse/-/uuid-parse-1.1.0.tgz",
+      "integrity": "sha512-OdmXxA8rDsQ7YpNVbKSJkNzTw2I+S5WsbMDnCtIWSQaosNAcWtFuI/YK1TjzUI6nbkgiqEyh8gWngfcv8Asd9A==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/vary": {
+      "version": "1.1.2",
+      "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
+      "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
     "node_modules/vite": {
       "version": "5.4.21",
       "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz",
@@ -1491,6 +4214,13 @@
         "node": ">=8"
       }
     },
+    "node_modules/wrappy": {
+      "version": "1.0.2",
+      "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
+      "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
+      "dev": true,
+      "license": "ISC"
+    },
     "node_modules/ws": {
       "version": "8.21.0",
       "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",
diff --git a/package.json b/package.json
index 2e69fa2..f3b477c 100644
--- a/package.json
+++ b/package.json
@@ -10,7 +10,8 @@
     "build": "tsc -p tsconfig.json",
     "test": "vitest run",
     "test:dev": "vitest",
-    "typecheck": "tsc --noEmit -p tsconfig.json"
+    "typecheck": "tsc --noEmit -p tsconfig.json",
+    "bench": "tsx bench/run.ts"
   },
   "dependencies": {
     "reflect-metadata": "0.2.2"
@@ -24,9 +25,15 @@
     }
   },
   "devDependencies": {
+    "@types/autocannon": "^7.12.7",
+    "@types/express": "^5.0.6",
     "@types/node": "^18.19.0",
     "@types/ws": "^8.18.1",
+    "autocannon": "^8.0.0",
+    "express": "^5.2.1",
+    "fastify": "^5.10.0",
     "graphql": "^16.9.0",
+    "tsx": "^4.23.0",
     "typescript": "^5.5.0",
     "vitest": "^2.0.0",
     "ws": "^8.21.0"

From 67133ca4ce8ae474fcb7689952358aa3f964dd3c Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Mon, 6 Jul 2026 22:31:47 -0500
Subject: [PATCH 062/139] feat(bench): pure stats aggregate + BENCHMARKS.md
 renderer

Signed-off-by: Diego Resendez 
---
 bench/render.ts           | 201 ++++++++++++++++++++++++++++++++++++++
 bench/stats.ts            |  18 ++++
 test/bench-render.test.ts |  78 +++++++++++++++
 3 files changed, 297 insertions(+)
 create mode 100644 bench/render.ts
 create mode 100644 bench/stats.ts
 create mode 100644 test/bench-render.test.ts

diff --git a/bench/render.ts b/bench/render.ts
new file mode 100644
index 0000000..dd53142
--- /dev/null
+++ b/bench/render.ts
@@ -0,0 +1,201 @@
+export interface EnvInfo {
+  date: string;
+  commit: string;
+  node: string;
+  os: string;
+  cpu: string;
+  ram: string;
+  pinned: boolean;
+}
+
+export interface Config {
+  conns: number;
+  duration: number;
+  runs: number;
+  warmup: number;
+  pipelining: number;
+}
+
+export interface Row {
+  framework: string;
+  reqSec: { median: number; min: number; max: number; stddev: number; cv: number };
+  p50: number;
+  p99: number;
+  p999: number;
+}
+
+export interface ScenarioBlock {
+  title: string;
+  name: string;
+  approximation?: boolean;
+  rows: Row[];
+}
+
+export interface RenderData {
+  env: EnvInfo;
+  config: Config;
+  scenarios: ScenarioBlock[];
+  stepScaling: { path: string; steps: number; reqSec: number }[];
+  secureCost: { label: string; reqSec: number }[];
+}
+
+const fmtInt = (n: number): string => Math.round(n).toLocaleString('en-US');
+const fmtLatency = (n: number): string => n.toFixed(2);
+const fmtCv = (n: number): string => `${(n * 100).toFixed(1)}%`;
+const fmtRange = (min: number, max: number): string => `${fmtInt(min)}–${fmtInt(max)}`;
+
+function renderEnvSection(env: EnvInfo, config: Config): string {
+  return [
+    '## Environment',
+    '',
+    `- **Date**: ${env.date}`,
+    `- **Commit**: ${env.commit}`,
+    `- **Node**: ${env.node}`,
+    `- **OS**: ${env.os}`,
+    `- **CPU**: ${env.cpu}`,
+    `- **RAM**: ${env.ram}`,
+    `- **Core-pinned**: ${env.pinned ? 'yes' : 'no'}`,
+    `- **autocannon config**: ${config.conns} connections, ${config.duration}s duration, ` +
+      `${config.runs} runs (${config.warmup} warmup discarded), pipelining ${config.pipelining}`,
+    '',
+  ].join('\n');
+}
+
+function renderCaveat(): string {
+  return [
+    '> **A note on honesty: this is a single-box benchmark.** All frameworks were driven with autocannon over',
+    '> loopback on the same machine, sharing the same cores as the server processes they measured. That',
+    "> contention overstates absolute throughput for every framework and compresses the differences *between*",
+    '> frameworks — do not read the raw req/s numbers as what you would see on separate client/server hardware.',
+    '> The honest takeaway is the **ratio** between frameworks in the same table, not any single absolute',
+    '> number. Note also that green-tea runs with `security:false` in the cross-framework tables below, purely',
+    '> for response-header parity with the other frameworks (none of which set the same security headers by',
+    '> default) — the real cost of running green-tea secure-by-default is measured separately in its own',
+    '> section further down.',
+    '',
+  ].join('\n');
+}
+
+function renderScenarioTable(rows: Row[]): string {
+  const sorted = [...rows].sort((a, b) => b.reqSec.median - a.reqSec.median);
+  const header = '| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |';
+  const divider = '| --- | --- | --- | --- | --- | --- | --- |';
+  const lines = sorted.map((row) => {
+    const { framework, reqSec, p50, p99, p999 } = row;
+    return (
+      `| ${framework} | ${fmtInt(reqSec.median)} | ${fmtLatency(p50)} | ${fmtLatency(p99)} | ` +
+      `${fmtLatency(p999)} | ${fmtCv(reqSec.cv)} | ${fmtRange(reqSec.min, reqSec.max)} |`
+    );
+  });
+  return [header, divider, ...lines].join('\n');
+}
+
+function renderScenarios(scenarios: ScenarioBlock[]): string {
+  return scenarios
+    .map((scenario) => {
+      const heading = `### ${scenario.title}${scenario.approximation ? ' (approximation)' : ''}`;
+      return [heading, '', renderScenarioTable(scenario.rows), ''].join('\n');
+    })
+    .join('\n');
+}
+
+function renderStepScaling(stepScaling: RenderData['stepScaling']): string {
+  const sorted = [...stepScaling].sort((a, b) => a.steps - b.steps);
+  const header = '| Path | Steps | req/s |';
+  const divider = '| --- | --- | --- |';
+  const lines = sorted.map((row) => `| ${row.path} | ${row.steps} | ${fmtInt(row.reqSec)} |`);
+
+  let deltaNote = '';
+  if (sorted.length >= 2) {
+    const first = sorted[0];
+    const last = sorted[sorted.length - 1];
+    const stepDiff = last.steps - first.steps;
+    if (stepDiff > 0) {
+      const reqDiff = last.reqSec - first.reqSec;
+      const perStep = reqDiff / stepDiff;
+      const pct = first.reqSec ? (reqDiff / first.reqSec) * 100 : 0;
+      deltaNote =
+        `Each additional pipeline step costs roughly ${fmtInt(Math.abs(perStep))} req/s ` +
+        `(${pct <= 0 ? '-' : ''}${Math.abs(pct).toFixed(1)}% over ${stepDiff} step${stepDiff === 1 ? '' : 's'}), ` +
+        `on this box.`;
+    }
+  }
+
+  return ['## Step-scaling (green-tea)', '', header, divider, ...lines, '', deltaNote, ''].join('\n');
+}
+
+function renderSecureCost(secureCost: RenderData['secureCost']): string {
+  const header = '| Label | req/s |';
+  const divider = '| --- | --- |';
+  const lines = secureCost.map((row) => `| ${row.label} | ${fmtInt(row.reqSec)} |`);
+
+  let deltaNote = '';
+  if (secureCost.length >= 2) {
+    const baseline = secureCost[0];
+    const withSecurity = secureCost[secureCost.length - 1];
+    const reqDiff = baseline.reqSec - withSecurity.reqSec;
+    const pct = baseline.reqSec ? (reqDiff / baseline.reqSec) * 100 : 0;
+    deltaNote = `The real cost of running secure-by-default (rather than the parity-mode \`security:false\` used above) is ~${pct.toFixed(1)}% req/s on this box.`;
+  }
+
+  return [
+    '## Cost of secure-by-default (green-tea)',
+    '',
+    header,
+    divider,
+    ...lines,
+    '',
+    deltaNote,
+    '',
+  ].join('\n');
+}
+
+function renderMethodology(): string {
+  return [
+    '## Methodology',
+    '',
+    '- **Parity controls**: every framework is configured for the fairest possible comparison —',
+    '  security-header parity (matching header sets across frameworks, or green-tea running with',
+    '  `security:false` in the cross-framework tables), keep-alive parity, and Express\'s `etag` and',
+    "  `x-powered-by` disabled. The `/validate` scenario always sends a valid body so every framework",
+    '  takes its success path and performs equivalent validation work.',
+    '- **Pipeline approximation**: scenarios marked `(approximation)` (e.g. the multi-step pipeline route)',
+    "  do not have an exact one-to-one equivalent in every framework; the closest reasonable approximation",
+    '  is used for each framework and the result should be read as indicative, not as an exact apples-to-apples',
+    '  measurement.',
+    '- **Serialization parity**: all four frameworks serialize their JSON responses with plain',
+    '  `JSON.stringify` in these benchmarks. Fastify\'s `fast-json-stringify` response serializer is',
+    '  deliberately **not** engaged — only its input `schema.body` validation is used — so no framework',
+    '  gets a serialization fast path the others lack.',
+    '',
+  ].join('\n');
+}
+
+function renderLeaderboard(scenarios: ScenarioBlock[]): string {
+  const first = scenarios[0];
+  if (!first || first.rows.length === 0) return '';
+  const leader = [...first.rows].sort((a, b) => b.reqSec.median - a.reqSec.median)[0];
+  return [
+    `> **TL;DR**: \`${leader.framework}\` posted the highest median req/s in the first benchmarked scenario ` +
+      `on this box — see the single-box caveat below before reading anything into the absolute numbers.`,
+    '',
+  ].join('\n');
+}
+
+export function renderMarkdown(data: RenderData): string {
+  const { env, config, scenarios, stepScaling, secureCost } = data;
+
+  return [
+    renderLeaderboard(scenarios),
+    '# green-tea Benchmarks',
+    '',
+    renderEnvSection(env, config),
+    renderCaveat(),
+    '## Cross-framework scenarios',
+    '',
+    renderScenarios(scenarios),
+    renderStepScaling(stepScaling),
+    renderSecureCost(secureCost),
+    renderMethodology(),
+  ].join('\n');
+}
diff --git a/bench/stats.ts b/bench/stats.ts
new file mode 100644
index 0000000..669cc73
--- /dev/null
+++ b/bench/stats.ts
@@ -0,0 +1,18 @@
+export interface Agg {
+  median: number;
+  mean: number;
+  stddev: number;
+  cv: number;
+  min: number;
+  max: number;
+}
+
+export function aggregate(values: number[]): Agg {
+  const xs = [...values].sort((a, b) => a - b);
+  const n = xs.length;
+  const mean = xs.reduce((s, x) => s + x, 0) / n;
+  const median = n % 2 ? xs[(n - 1) / 2] : (xs[n / 2 - 1] + xs[n / 2]) / 2;
+  const variance = xs.reduce((s, x) => s + (x - mean) ** 2, 0) / n;
+  const stddev = Math.sqrt(variance);
+  return { median, mean, stddev, cv: mean ? stddev / mean : 0, min: xs[0], max: xs[n - 1] };
+}
diff --git a/test/bench-render.test.ts b/test/bench-render.test.ts
new file mode 100644
index 0000000..5546fd9
--- /dev/null
+++ b/test/bench-render.test.ts
@@ -0,0 +1,78 @@
+import { describe, it, expect } from 'vitest';
+import { aggregate } from '../bench/stats';
+import { renderMarkdown } from '../bench/render';
+
+describe('aggregate', () => {
+  it('median, stddev, cv, min/max over run req/s', () => {
+    const a = aggregate([100, 110, 120, 130, 140]);
+    expect(a.median).toBe(120);
+    expect(a.min).toBe(100);
+    expect(a.max).toBe(140);
+    expect(a.stddev).toBeGreaterThan(0);
+    expect(a.cv).toBeCloseTo(a.stddev / a.mean, 6);
+  });
+});
+
+describe('renderMarkdown', () => {
+  const data = {
+    env: {
+      date: '2026-07-06',
+      commit: 'abc123',
+      node: 'v18.19.0',
+      os: 'darwin',
+      cpu: 'M1 (8 cores)',
+      ram: '16 GB',
+      pinned: false,
+    },
+    config: { conns: 100, duration: 10, runs: 5, warmup: 1, pipelining: 1 },
+    scenarios: [
+      {
+        title: 'JSON hello (overhead)',
+        name: 'hello',
+        approximation: false,
+        rows: [
+          {
+            framework: 'fastify',
+            reqSec: { median: 50000, min: 49000, max: 51000, stddev: 700, cv: 0.014 },
+            p50: 1.5,
+            p99: 4,
+            p999: 9,
+          },
+          {
+            framework: 'green-tea',
+            reqSec: { median: 42000, min: 41000, max: 43000, stddev: 600, cv: 0.014 },
+            p50: 1.9,
+            p99: 5,
+            p999: 11,
+          },
+        ],
+      },
+    ],
+    stepScaling: [
+      { path: '/steps/0', steps: 0, reqSec: 45000 },
+      { path: '/steps/3', steps: 3, reqSec: 40000 },
+    ],
+    secureCost: [
+      { label: 'security:false (parity)', reqSec: 45000 },
+      { label: 'security:true (default)', reqSec: 43000 },
+    ],
+  };
+  it('renders env header, a per-scenario table with a row per framework, and the micro-bench sections', () => {
+    const md = renderMarkdown(data as any);
+    expect(md).toContain('# green-tea Benchmarks');
+    expect(md).toContain('abc123'); // commit
+    expect(md).toContain('single-box'); // contention caveat
+    expect(md).toContain('JSON hello (overhead)');
+    expect(md).toContain('fastify');
+    expect(md).toContain('green-tea');
+    expect(md).toMatch(/req\/s/i);
+    expect(md).toContain('p99');
+    expect(md).toContain('Step-scaling');
+    expect(md).toContain('secure-by-default');
+    expect(md).toContain('approximation'); // methodology mentions the pipeline approximation
+  });
+  it('sorts each scenario rows by median req/s descending', () => {
+    const md = renderMarkdown(data as any);
+    expect(md.indexOf('fastify')).toBeLessThan(md.indexOf('green-tea')); // fastify (50k) before green-tea (42k)
+  });
+});

From 92ca5f96dac2beb7aaf25655761ee9eae717df5e Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Mon, 6 Jul 2026 22:39:35 -0500
Subject: [PATCH 063/139] feat(bench): green-tea/express/fastify/raw-http
 servers with parity controls

Signed-off-by: Diego Resendez 
---
 bench/servers/express.ts   | 19 ++++++++++++++++
 bench/servers/fastify.ts   | 19 ++++++++++++++++
 bench/servers/green-tea.ts | 44 ++++++++++++++++++++++++++++++++++++++
 bench/servers/raw-http.ts  | 19 ++++++++++++++++
 4 files changed, 101 insertions(+)
 create mode 100644 bench/servers/express.ts
 create mode 100644 bench/servers/fastify.ts
 create mode 100644 bench/servers/green-tea.ts
 create mode 100644 bench/servers/raw-http.ts

diff --git a/bench/servers/express.ts b/bench/servers/express.ts
new file mode 100644
index 0000000..d9d6a4d
--- /dev/null
+++ b/bench/servers/express.ts
@@ -0,0 +1,19 @@
+import express from 'express';
+
+const app = express();
+app.disable('x-powered-by');
+app.set('etag', false);
+app.use(express.json());
+app.get('/hello', (_req, res) => { res.json({ hello: 'world' }); });
+app.get('/users/:id', (req, res) => { res.json({ id: req.params.id }); });
+const mw = (n: number) => (_req: any, res: any, next: any) => { res.locals[`s${n}`] = n; next(); };
+app.get('/pipeline', mw(1), mw(2), mw(3), (_req, res) => { res.json({ hello: 'world', s3: res.locals.s3 }); });
+app.post('/validate', (req: any, res) => {
+  const b = req.body;
+  if (!(b && typeof b.email === 'string' && b.email.includes('@'))) { res.status(422).json({ error: 'invalid' }); return; }
+  res.json({ email: b.email });
+});
+const server = app.listen(0, () => {
+  server.keepAliveTimeout = 5000;
+  console.log(`READY ${(server.address() as any).port}`);
+});
diff --git a/bench/servers/fastify.ts b/bench/servers/fastify.ts
new file mode 100644
index 0000000..5239128
--- /dev/null
+++ b/bench/servers/fastify.ts
@@ -0,0 +1,19 @@
+import Fastify from 'fastify';
+
+const app = Fastify({ logger: false });
+app.get('/hello', async () => ({ hello: 'world' }));
+app.get('/users/:id', async (req: any) => ({ id: req.params.id }));
+const hook = (n: number) => (req: any, _res: any, done: any) => { req[`s${n}`] = n; done(); };
+app.get('/pipeline', { preHandler: [hook(1), hook(2), hook(3)] }, async (req: any) => ({ hello: 'world', s3: req.s3 }));
+app.post('/validate', {
+  schema: { body: { type: 'object', required: ['email'], properties: { email: { type: 'string' } } } },
+}, async (req: any, reply) => {
+  const b = req.body;
+  if (!b.email.includes('@')) { reply.code(422); return { error: 'invalid' }; }
+  return { email: b.email };
+});
+app.listen({ port: 0 }, (err, addr) => {
+  if (err) { console.error(err); process.exit(1); }
+  (app.server as any).keepAliveTimeout = 5000;
+  console.log(`READY ${Number(new URL(addr).port)}`);
+});
diff --git a/bench/servers/green-tea.ts b/bench/servers/green-tea.ts
new file mode 100644
index 0000000..10bd623
--- /dev/null
+++ b/bench/servers/green-tea.ts
@@ -0,0 +1,44 @@
+import 'reflect-metadata';
+import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../src/index';
+
+// email schema (Standard Schema, hand-rolled — same field check the others do)
+const emailSchema = {
+  '~standard': { version: 1 as const, vendor: 'bench', validate: (v: any) =>
+    (v && typeof v.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'invalid email' }] } },
+};
+
+// 5 chained steps: s1..s5, each needs the previous. Routes @needs the Nth to pull exactly N.
+function makeStep(n: number) {
+  @Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] })
+  class S { run() { return { [`s${n}`]: n }; } }
+  return S;
+}
+const steps = [1, 2, 3, 4, 5].map(makeStep);
+
+@Route('/')
+class Bench {
+  @Get('/hello') hello() { return { hello: 'world' }; }
+  @Get('/users/:id') user(@param('id') id: string) { return { id }; }
+  @Get('/pipeline') pipeline(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
+  @Post('/validate') validate(@body(emailSchema) b: any) { return { email: b.email }; }
+  @Get('/steps/0') steps0() { return { hello: 'world' }; }
+  @Get('/steps/3') steps3(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
+  @Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; }
+}
+
+@Module({ mountpoint: '/', steps, controllers: [Bench] })
+class BenchModule {}
+
+// PARITY: security OFF for the cross-framework table. GT_SECURE=1 flips it on for the secure-cost micro-bench.
+const secure = process.env.GT_SECURE === '1';
+const app = createApp({ modules: [BenchModule], security: secure });
+
+async function main() {
+  // fail loudly if decorators didn't apply (inspect throws "no route" on empty plan, so wrap)
+  try { if (app.inspect('/hello').length === 0) throw new Error('empty'); }
+  catch { console.error('DECORATORS_NOT_APPLIED'); process.exit(1); }
+  const server = await app.listen(0);
+  server.keepAliveTimeout = 5000; // parity value (all servers use 5000)
+  console.log(`READY ${(server.address() as any).port}`);
+}
+main().catch((e) => { console.error(e); process.exit(1); });
diff --git a/bench/servers/raw-http.ts b/bench/servers/raw-http.ts
new file mode 100644
index 0000000..c5d75ab
--- /dev/null
+++ b/bench/servers/raw-http.ts
@@ -0,0 +1,19 @@
+import http from 'http';
+
+const server = http.createServer((req, res) => {
+  const url = (req.url ?? '/').split('?')[0];
+  const send = (obj: unknown, code = 200) => { res.writeHead(code, { 'content-type': 'application/json' }); res.end(JSON.stringify(obj)); };
+  if (req.method === 'GET' && url === '/hello') return send({ hello: 'world' });
+  if (req.method === 'GET' && url.startsWith('/users/')) return send({ id: url.slice('/users/'.length) });
+  if (req.method === 'GET' && url === '/pipeline') { const s: any = {}; [1, 2, 3].forEach((n) => (s[`s${n}`] = n)); return send({ hello: 'world', s3: s.s3 }); }
+  if (req.method === 'GET' && url === '/steps/0') return send({ hello: 'world' });
+  if (req.method === 'POST' && url === '/validate') {
+    let raw = ''; req.on('data', (c) => (raw += c)); req.on('end', () => {
+      try { const b = JSON.parse(raw); if (typeof b.email === 'string' && b.email.includes('@')) return send({ email: b.email }); return send({ error: 'invalid' }, 422); }
+      catch { return send({ error: 'bad json' }, 400); }
+    }); return;
+  }
+  send({ error: 'not found' }, 404);
+});
+server.keepAliveTimeout = 5000;
+server.listen(0, () => console.log(`READY ${(server.address() as any).port}`));

From 768d8d0fd53e3c92d549368be90d012bf5063da0 Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Mon, 6 Jul 2026 22:49:22 -0500
Subject: [PATCH 064/139] fix(bench): Fastify keep-alive parity via
 constructor; drop dead raw-http route

Signed-off-by: Diego Resendez 
---
 bench/servers/fastify.ts  | 3 +--
 bench/servers/raw-http.ts | 1 -
 2 files changed, 1 insertion(+), 3 deletions(-)

diff --git a/bench/servers/fastify.ts b/bench/servers/fastify.ts
index 5239128..9cd8833 100644
--- a/bench/servers/fastify.ts
+++ b/bench/servers/fastify.ts
@@ -1,6 +1,6 @@
 import Fastify from 'fastify';
 
-const app = Fastify({ logger: false });
+const app = Fastify({ logger: false, keepAliveTimeout: 5000 });
 app.get('/hello', async () => ({ hello: 'world' }));
 app.get('/users/:id', async (req: any) => ({ id: req.params.id }));
 const hook = (n: number) => (req: any, _res: any, done: any) => { req[`s${n}`] = n; done(); };
@@ -14,6 +14,5 @@ app.post('/validate', {
 });
 app.listen({ port: 0 }, (err, addr) => {
   if (err) { console.error(err); process.exit(1); }
-  (app.server as any).keepAliveTimeout = 5000;
   console.log(`READY ${Number(new URL(addr).port)}`);
 });
diff --git a/bench/servers/raw-http.ts b/bench/servers/raw-http.ts
index c5d75ab..4b0bdd9 100644
--- a/bench/servers/raw-http.ts
+++ b/bench/servers/raw-http.ts
@@ -6,7 +6,6 @@ const server = http.createServer((req, res) => {
   if (req.method === 'GET' && url === '/hello') return send({ hello: 'world' });
   if (req.method === 'GET' && url.startsWith('/users/')) return send({ id: url.slice('/users/'.length) });
   if (req.method === 'GET' && url === '/pipeline') { const s: any = {}; [1, 2, 3].forEach((n) => (s[`s${n}`] = n)); return send({ hello: 'world', s3: s.s3 }); }
-  if (req.method === 'GET' && url === '/steps/0') return send({ hello: 'world' });
   if (req.method === 'POST' && url === '/validate') {
     let raw = ''; req.on('data', (c) => (raw += c)); req.on('end', () => {
       try { const b = JSON.parse(raw); if (typeof b.email === 'string' && b.email.includes('@')) return send({ email: b.email }); return send({ error: 'invalid' }, 422); }

From 32b0087650384b1440f1c0522ebaa54a05b6f8ac Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Mon, 6 Jul 2026 22:52:27 -0500
Subject: [PATCH 065/139] =?UTF-8?q?feat(bench):=20orchestrator=20=E2=80=94?=
 =?UTF-8?q?=20isolated=20spawns,=20warmup+median=20runs,=20renders=20BENCH?=
 =?UTF-8?q?MARKS.md?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Signed-off-by: Diego Resendez 
---
 bench/run.ts | 170 +++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 170 insertions(+)
 create mode 100644 bench/run.ts

diff --git a/bench/run.ts b/bench/run.ts
new file mode 100644
index 0000000..4d328ee
--- /dev/null
+++ b/bench/run.ts
@@ -0,0 +1,170 @@
+import autocannon from 'autocannon';
+import { spawn, execSync } from 'child_process';
+import os from 'os';
+import { writeFileSync } from 'fs';
+import { SCENARIOS, STEP_ROUTES } from './scenarios';
+import { aggregate } from './stats';
+import { renderMarkdown, type RenderData, type Row, type ScenarioBlock } from './render';
+
+const SMOKE = process.env.BENCH_SMOKE === '1';
+const CONNS = Number(process.env.BENCH_CONNS ?? 100);
+const DURATION = SMOKE ? 1 : Number(process.env.BENCH_DURATION ?? 10);
+const RUNS = SMOKE ? 1 : Number(process.env.BENCH_RUNS ?? 5);
+const WARMUP = SMOKE ? 0 : Number(process.env.BENCH_WARMUP ?? 1);
+
+function log(msg: string): void {
+  process.stderr.write(`[bench] ${msg}\n`);
+}
+
+interface RunResult {
+  reqSec: number;
+  p50: number;
+  p99: number;
+  p999: number;
+}
+
+async function spawnServer(
+  name: string,
+  extraEnv: Record = {},
+): Promise<{ port: number; kill: () => Promise }> {
+  const child = spawn(process.execPath, ['--import', 'tsx', `bench/servers/${name}.ts`], {
+    env: { ...process.env, TSX_TSCONFIG_PATH: 'bench/tsconfig.json', ...extraEnv },
+  });
+  let stderr = '';
+  child.stderr.on('data', (d) => (stderr += d));
+  const port = await new Promise((resolve, reject) => {
+    const t = setTimeout(() => {
+      child.kill('SIGKILL');
+      reject(new Error(`${name} failed to boot (no READY in 10s):\n${stderr}`));
+    }, 10000);
+    let buf = '';
+    child.stdout.on('data', (d) => {
+      buf += d;
+      const m = /READY (\d+)/.exec(buf);
+      if (m) {
+        clearTimeout(t);
+        resolve(Number(m[1]));
+      }
+    });
+    child.on('exit', (code) => {
+      clearTimeout(t);
+      reject(new Error(`${name} exited early (code ${code}):\n${stderr}`));
+    });
+  });
+  const kill = (): Promise =>
+    new Promise((resolve) => {
+      child.on('exit', () => resolve());
+      child.kill('SIGTERM');
+      setTimeout(() => {
+        try {
+          child.kill('SIGKILL');
+        } catch {
+          /* already dead */
+        }
+      }, 2000);
+    });
+  return { port, kill };
+}
+
+async function bench(port: number, path: string, method: 'GET' | 'POST', body?: unknown): Promise {
+  const r: any = await autocannon({
+    url: `http://127.0.0.1:${port}${path}`,
+    connections: CONNS,
+    duration: DURATION,
+    pipelining: 1,
+    method,
+    headers: body ? { 'content-type': 'application/json' } : undefined,
+    body: body ? JSON.stringify(body) : undefined,
+  });
+  return { reqSec: r.requests.average, p50: r.latency.p50, p99: r.latency.p99, p999: r.latency.p99_9 };
+}
+
+async function measure(port: number, path: string, method: 'GET' | 'POST', body?: unknown): Promise {
+  for (let i = 0; i < WARMUP; i++) await bench(port, path, method, body); // discarded
+  const runs: RunResult[] = [];
+  for (let i = 0; i < RUNS; i++) runs.push(await bench(port, path, method, body));
+  return runs;
+}
+
+async function main(): Promise {
+  const frameworks = ['raw-http', 'fastify', 'express', 'green-tea'];
+  const scenarioBlocks: ScenarioBlock[] = SCENARIOS.map((s) => ({
+    title: s.title,
+    name: s.name,
+    approximation: s.approximation,
+    rows: [],
+  }));
+  const stepScaling: RenderData['stepScaling'] = [];
+  const secureCost: RenderData['secureCost'] = [];
+
+  for (const fw of frameworks) {
+    log(`booting ${fw}`);
+    const { port, kill } = await spawnServer(fw);
+    try {
+      for (const s of SCENARIOS) {
+        log(`${fw} / ${s.name}`);
+        const runs = await measure(port, s.path, s.method, s.body);
+        const agg = aggregate(runs.map((r) => r.reqSec));
+        const last = runs[runs.length - 1];
+        const row: Row = {
+          framework: fw,
+          reqSec: { median: agg.median, min: agg.min, max: agg.max, stddev: agg.stddev, cv: agg.cv },
+          p50: last.p50,
+          p99: last.p99,
+          p999: last.p999,
+        };
+        scenarioBlocks.find((b) => b.name === s.name)!.rows.push(row);
+      }
+      if (fw === 'green-tea') {
+        for (const sr of STEP_ROUTES) {
+          const runs = await measure(port, sr.path, 'GET');
+          stepScaling.push({ path: sr.path, steps: sr.steps, reqSec: aggregate(runs.map((r) => r.reqSec)).median });
+        }
+        secureCost.push({
+          label: 'security:false (parity)',
+          reqSec: aggregate((await measure(port, '/hello', 'GET')).map((r) => r.reqSec)).median,
+        });
+      }
+    } finally {
+      await kill();
+    }
+  }
+
+  log('booting green-tea (GT_SECURE=1)');
+  {
+    const { port, kill } = await spawnServer('green-tea', { GT_SECURE: '1' });
+    try {
+      secureCost.push({
+        label: 'security:true (default)',
+        reqSec: aggregate((await measure(port, '/hello', 'GET')).map((r) => r.reqSec)).median,
+      });
+    } finally {
+      await kill();
+    }
+  }
+
+  const commit = execSync('git rev-parse --short HEAD').toString().trim();
+  const data: RenderData = {
+    env: {
+      date: new Date().toISOString().slice(0, 10),
+      commit,
+      node: process.version,
+      os: os.platform(),
+      cpu: `${os.cpus()[0].model} (${os.cpus().length} cores)`,
+      ram: `${Math.round(os.totalmem() / 1e9)} GB`,
+      pinned: false,
+    },
+    config: { conns: CONNS, duration: DURATION, runs: RUNS, warmup: WARMUP, pipelining: 1 },
+    scenarios: scenarioBlocks,
+    stepScaling,
+    secureCost,
+  };
+  writeFileSync('BENCHMARKS.md', renderMarkdown(data));
+  writeFileSync('bench/results.json', JSON.stringify(data, null, 2));
+  log('wrote BENCHMARKS.md + bench/results.json');
+}
+
+main().catch((e) => {
+  console.error(e);
+  process.exit(1);
+});

From 926ca3901ccff3824cbf19176a3b7fe1b530f3c2 Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Mon, 6 Jul 2026 22:57:22 -0500
Subject: [PATCH 066/139] fix(bench): reuse hello median for secure-cost parity
 row (consistent numbers)

Signed-off-by: Diego Resendez 
---
 bench/run.ts | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/bench/run.ts b/bench/run.ts
index 4d328ee..431269d 100644
--- a/bench/run.ts
+++ b/bench/run.ts
@@ -120,10 +120,12 @@ async function main(): Promise {
           const runs = await measure(port, sr.path, 'GET');
           stepScaling.push({ path: sr.path, steps: sr.steps, reqSec: aggregate(runs.map((r) => r.reqSec)).median });
         }
-        secureCost.push({
-          label: 'security:false (parity)',
-          reqSec: aggregate((await measure(port, '/hello', 'GET')).map((r) => r.reqSec)).median,
-        });
+        // Reuse the hello scenario's already-computed median so the parity row exactly matches
+        // the green-tea hello-table number (rather than re-measuring the same server/config).
+        const helloMedian = scenarioBlocks
+          .find((b) => b.name === 'hello')!
+          .rows.find((r) => r.framework === 'green-tea')!.reqSec.median;
+        secureCost.push({ label: 'security:false (parity)', reqSec: helloMedian });
       }
     } finally {
       await kill();

From daa13f6f7826a73024c51c8170ecb5e2d22f661e Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Mon, 6 Jul 2026 23:06:01 -0500
Subject: [PATCH 067/139] docs(bench): generate BENCHMARKS.md and link from
 README

Signed-off-by: Diego Resendez 
---
 BENCHMARKS.md      |  97 ++++++++++++++++
 README.md          |  11 ++
 bench/results.json | 280 +++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 388 insertions(+)
 create mode 100644 BENCHMARKS.md
 create mode 100644 bench/results.json

diff --git a/BENCHMARKS.md b/BENCHMARKS.md
new file mode 100644
index 0000000..91ded90
--- /dev/null
+++ b/BENCHMARKS.md
@@ -0,0 +1,97 @@
+> **TL;DR**: `raw-http` posted the highest median req/s in the first benchmarked scenario on this box — see the single-box caveat below before reading anything into the absolute numbers.
+
+# green-tea Benchmarks
+
+## Environment
+
+- **Date**: 2026-07-07
+- **Commit**: 926ca39
+- **Node**: v22.22.2
+- **OS**: darwin
+- **CPU**: Apple M4 Max (16 cores)
+- **RAM**: 69 GB
+- **Core-pinned**: no
+- **autocannon config**: 100 connections, 5s duration, 3 runs (1 warmup discarded), pipelining 1
+
+> **A note on honesty: this is a single-box benchmark.** All frameworks were driven with autocannon over
+> loopback on the same machine, sharing the same cores as the server processes they measured. That
+> contention overstates absolute throughput for every framework and compresses the differences *between*
+> frameworks — do not read the raw req/s numbers as what you would see on separate client/server hardware.
+> The honest takeaway is the **ratio** between frameworks in the same table, not any single absolute
+> number. Note also that green-tea runs with `security:false` in the cross-framework tables below, purely
+> for response-header parity with the other frameworks (none of which set the same security headers by
+> default) — the real cost of running green-tea secure-by-default is measured separately in its own
+> section further down.
+
+## Cross-framework scenarios
+
+### JSON hello (overhead)
+
+| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
+| --- | --- | --- | --- | --- | --- | --- |
+| raw-http | 115,398 | 0.00 | 1.00 | 1.00 | 0.4% | 115,078–116,077 |
+| green-tea | 98,912 | 0.00 | 1.00 | 2.00 | 0.5% | 98,835–99,962 |
+| fastify | 85,882 | 1.00 | 2.00 | 2.00 | 0.3% | 85,382–86,074 |
+| express | 24,126 | 3.00 | 5.00 | 8.00 | 0.1% | 24,072–24,158 |
+
+### Route param
+
+| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
+| --- | --- | --- | --- | --- | --- | --- |
+| raw-http | 115,437 | 0.00 | 1.00 | 1.00 | 0.3% | 115,245–116,013 |
+| green-tea | 93,114 | 1.00 | 2.00 | 2.00 | 0.1% | 92,947–93,126 |
+| fastify | 85,805 | 1.00 | 2.00 | 2.00 | 0.2% | 85,498–85,856 |
+| express | 23,739 | 4.00 | 5.00 | 8.00 | 0.1% | 23,694–23,778 |
+
+### Pipeline (3 steps) (approximation)
+
+| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
+| --- | --- | --- | --- | --- | --- | --- |
+| raw-http | 114,016 | 0.00 | 1.00 | 1.00 | 0.1% | 114,003–114,157 |
+| green-tea | 84,230 | 1.00 | 2.00 | 2.00 | 0.5% | 84,179–85,050 |
+| fastify | 83,808 | 1.00 | 2.00 | 2.00 | 0.1% | 83,770–83,898 |
+| express | 23,758 | 4.00 | 5.00 | 8.00 | 0.1% | 23,720–23,778 |
+
+### POST JSON + validation
+
+| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
+| --- | --- | --- | --- | --- | --- | --- |
+| raw-http | 99,014 | 0.00 | 1.00 | 2.00 | 0.3% | 98,438–99,181 |
+| green-tea | 76,486 | 1.00 | 2.00 | 2.00 | 0.2% | 76,397–76,691 |
+| fastify | 63,869 | 1.00 | 2.00 | 3.00 | 0.3% | 63,837–64,323 |
+| express | 19,986 | 4.00 | 7.00 | 26.00 | 0.4% | 19,886–20,069 |
+
+## Step-scaling (green-tea)
+
+| Path | Steps | req/s |
+| --- | --- | --- |
+| /steps/0 | 0 | 92,858 |
+| /steps/3 | 3 | 81,658 |
+| /steps/5 | 5 | 71,968 |
+
+Each additional pipeline step costs roughly 4,178 req/s (-22.5% over 5 steps), on this box.
+
+## Cost of secure-by-default (green-tea)
+
+| Label | req/s |
+| --- | --- |
+| security:false (parity) | 98,912 |
+| security:true (default) | 93,178 |
+
+The real cost of running secure-by-default (rather than the parity-mode `security:false` used above) is ~5.8% req/s on this box.
+
+## Methodology
+
+- **Parity controls**: every framework is configured for the fairest possible comparison —
+  security-header parity (matching header sets across frameworks, or green-tea running with
+  `security:false` in the cross-framework tables), keep-alive parity, and Express's `etag` and
+  `x-powered-by` disabled. The `/validate` scenario always sends a valid body so every framework
+  takes its success path and performs equivalent validation work.
+- **Pipeline approximation**: scenarios marked `(approximation)` (e.g. the multi-step pipeline route)
+  do not have an exact one-to-one equivalent in every framework; the closest reasonable approximation
+  is used for each framework and the result should be read as indicative, not as an exact apples-to-apples
+  measurement.
+- **Serialization parity**: all four frameworks serialize their JSON responses with plain
+  `JSON.stringify` in these benchmarks. Fastify's `fast-json-stringify` response serializer is
+  deliberately **not** engaged — only its input `schema.body` validation is used — so no framework
+  gets a serialization fast path the others lack.
diff --git a/README.md b/README.md
index abc6a39..751a2d3 100644
--- a/README.md
+++ b/README.md
@@ -131,6 +131,17 @@ The handler signature declares exactly what it wants — in any order, nothing m
 1. **Typed functional core (`flow`)** — `flow().step(...).step(...).handle(...)`; step outputs accumulate into the context type (`Acc & Out`). This is where the compile-time guarantee lives.
 2. **Declarative decorator layer** — `@Provider/@Step/@Module/@Route/@Get/@Transformer` + argument decorators. Emits runtime metadata, builds and topologically sorts the graph, validates at boot.
 
+## Benchmarks
+
+Reproducible autocannon comparison vs Express 5, Fastify 5, and raw Node `http`
+lives in [BENCHMARKS.md](./BENCHMARKS.md) (regenerate with `npm run bench`).
+
+Numbers are single-box + loopback — absolute req/s is overstated and
+inter-framework differences are compressed; treat cross-framework *ratios* as
+the honest signal, not the raw throughput. The cross-framework table runs
+green-tea with `security:false` for header parity; the real cost of green-tea's
+secure-by-default headers/validation is measured separately in that file.
+
 ## Development
 
 ```bash
diff --git a/bench/results.json b/bench/results.json
new file mode 100644
index 0000000..5c99373
--- /dev/null
+++ b/bench/results.json
@@ -0,0 +1,280 @@
+{
+  "env": {
+    "date": "2026-07-07",
+    "commit": "926ca39",
+    "node": "v22.22.2",
+    "os": "darwin",
+    "cpu": "Apple M4 Max (16 cores)",
+    "ram": "69 GB",
+    "pinned": false
+  },
+  "config": {
+    "conns": 100,
+    "duration": 5,
+    "runs": 3,
+    "warmup": 1,
+    "pipelining": 1
+  },
+  "scenarios": [
+    {
+      "title": "JSON hello (overhead)",
+      "name": "hello",
+      "rows": [
+        {
+          "framework": "raw-http",
+          "reqSec": {
+            "median": 115398.4,
+            "min": 115078.4,
+            "max": 116076.8,
+            "stddev": 416.2570146222469,
+            "cv": 0.003603399427582749
+          },
+          "p50": 0,
+          "p99": 1,
+          "p999": 1
+        },
+        {
+          "framework": "fastify",
+          "reqSec": {
+            "median": 85881.6,
+            "min": 85382.4,
+            "max": 86073.6,
+            "stddev": 291.32305092457597,
+            "cv": 0.0033961968743538755
+          },
+          "p50": 1,
+          "p99": 2,
+          "p999": 2
+        },
+        {
+          "framework": "express",
+          "reqSec": {
+            "median": 24126.4,
+            "min": 24072,
+            "max": 24158.4,
+            "stddev": 35.66560746090835,
+            "cv": 0.0014787390042501193
+          },
+          "p50": 3,
+          "p99": 5,
+          "p999": 8
+        },
+        {
+          "framework": "green-tea",
+          "reqSec": {
+            "median": 98912,
+            "min": 98835.2,
+            "max": 99961.6,
+            "stddev": 513.8455626180164,
+            "cv": 0.005178001751557391
+          },
+          "p50": 0,
+          "p99": 1,
+          "p999": 2
+        }
+      ]
+    },
+    {
+      "title": "Route param",
+      "name": "param",
+      "rows": [
+        {
+          "framework": "raw-http",
+          "reqSec": {
+            "median": 115436.8,
+            "min": 115244.8,
+            "max": 116012.8,
+            "stddev": 326.3372488699382,
+            "cv": 0.0028238464382747876
+          },
+          "p50": 0,
+          "p99": 1,
+          "p999": 1
+        },
+        {
+          "framework": "fastify",
+          "reqSec": {
+            "median": 85804.8,
+            "min": 85497.6,
+            "max": 85856,
+            "stddev": 158.26975565645782,
+            "cv": 0.0018463688799174882
+          },
+          "p50": 1,
+          "p99": 2,
+          "p999": 2
+        },
+        {
+          "framework": "express",
+          "reqSec": {
+            "median": 23739.2,
+            "min": 23694.4,
+            "max": 23777.6,
+            "stddev": 33.99973856108518,
+            "cv": 0.001432347940819078
+          },
+          "p50": 4,
+          "p99": 5,
+          "p999": 8
+        },
+        {
+          "framework": "green-tea",
+          "reqSec": {
+            "median": 93113.6,
+            "min": 92947.2,
+            "max": 93126.4,
+            "stddev": 81.62613960409276,
+            "cv": 0.000877111912051406
+          },
+          "p50": 1,
+          "p99": 2,
+          "p999": 2
+        }
+      ]
+    },
+    {
+      "title": "Pipeline (3 steps)",
+      "name": "pipeline",
+      "approximation": true,
+      "rows": [
+        {
+          "framework": "raw-http",
+          "reqSec": {
+            "median": 114016,
+            "min": 114003.2,
+            "max": 114156.8,
+            "stddev": 69.58722743594919,
+            "cv": 0.0006101003060058202
+          },
+          "p50": 0,
+          "p99": 1,
+          "p999": 1
+        },
+        {
+          "framework": "fastify",
+          "reqSec": {
+            "median": 83808,
+            "min": 83769.61,
+            "max": 83897.6,
+            "stddev": 53.62772106538676,
+            "cv": 0.0006397575458676833
+          },
+          "p50": 1,
+          "p99": 2,
+          "p999": 2
+        },
+        {
+          "framework": "express",
+          "reqSec": {
+            "median": 23758.4,
+            "min": 23720,
+            "max": 23777.6,
+            "stddev": 23.946607275352836,
+            "cv": 0.001008193300579018
+          },
+          "p50": 4,
+          "p99": 5,
+          "p999": 8
+        },
+        {
+          "framework": "green-tea",
+          "reqSec": {
+            "median": 84230.4,
+            "min": 84179.2,
+            "max": 85049.6,
+            "stddev": 398.7907053413738,
+            "cv": 0.004720176328277377
+          },
+          "p50": 1,
+          "p99": 2,
+          "p999": 2
+        }
+      ]
+    },
+    {
+      "title": "POST JSON + validation",
+      "name": "validate",
+      "rows": [
+        {
+          "framework": "raw-http",
+          "reqSec": {
+            "median": 99014.4,
+            "min": 98438.4,
+            "max": 99180.8,
+            "stddev": 318.0885131881125,
+            "cv": 0.0032169839814651393
+          },
+          "p50": 0,
+          "p99": 1,
+          "p999": 2
+        },
+        {
+          "framework": "fastify",
+          "reqSec": {
+            "median": 63868.8,
+            "min": 63836.8,
+            "max": 64323.2,
+            "stddev": 222.1331732692473,
+            "cv": 0.0034703102857891206
+          },
+          "p50": 1,
+          "p99": 2,
+          "p999": 3
+        },
+        {
+          "framework": "express",
+          "reqSec": {
+            "median": 19985.6,
+            "min": 19886.41,
+            "max": 20068.8,
+            "stddev": 74.55572725597027,
+            "cv": 0.003731467455443308
+          },
+          "p50": 4,
+          "p99": 7,
+          "p999": 26
+        },
+        {
+          "framework": "green-tea",
+          "reqSec": {
+            "median": 76486.4,
+            "min": 76396.8,
+            "max": 76691.2,
+            "stddev": 123.21731480058412,
+            "cv": 0.0016101618664875192
+          },
+          "p50": 1,
+          "p99": 2,
+          "p999": 2
+        }
+      ]
+    }
+  ],
+  "stepScaling": [
+    {
+      "path": "/steps/0",
+      "steps": 0,
+      "reqSec": 92857.6
+    },
+    {
+      "path": "/steps/3",
+      "steps": 3,
+      "reqSec": 81657.61
+    },
+    {
+      "path": "/steps/5",
+      "steps": 5,
+      "reqSec": 71968
+    }
+  ],
+  "secureCost": [
+    {
+      "label": "security:false (parity)",
+      "reqSec": 98912
+    },
+    {
+      "label": "security:true (default)",
+      "reqSec": 93177.6
+    }
+  ]
+}
\ No newline at end of file

From 7593d1425ae43768552e4a1172c1c41528e3e1d1 Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Mon, 6 Jul 2026 23:17:58 -0500
Subject: [PATCH 068/139] docs(bench): disclose charset + secure-cost scope;
 add typecheck:bench script

Signed-off-by: Diego Resendez 
---
 BENCHMARKS.md      |  55 ++++++++------
 bench/render.ts    |   7 ++
 bench/results.json | 178 ++++++++++++++++++++++-----------------------
 package.json       |   1 +
 4 files changed, 128 insertions(+), 113 deletions(-)

diff --git a/BENCHMARKS.md b/BENCHMARKS.md
index 91ded90..3133702 100644
--- a/BENCHMARKS.md
+++ b/BENCHMARKS.md
@@ -5,7 +5,7 @@
 ## Environment
 
 - **Date**: 2026-07-07
-- **Commit**: 926ca39
+- **Commit**: daa13f6
 - **Node**: v22.22.2
 - **OS**: darwin
 - **CPU**: Apple M4 Max (16 cores)
@@ -29,56 +29,60 @@
 
 | Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
 | --- | --- | --- | --- | --- | --- | --- |
-| raw-http | 115,398 | 0.00 | 1.00 | 1.00 | 0.4% | 115,078–116,077 |
-| green-tea | 98,912 | 0.00 | 1.00 | 2.00 | 0.5% | 98,835–99,962 |
-| fastify | 85,882 | 1.00 | 2.00 | 2.00 | 0.3% | 85,382–86,074 |
-| express | 24,126 | 3.00 | 5.00 | 8.00 | 0.1% | 24,072–24,158 |
+| raw-http | 116,166 | 0.00 | 1.00 | 1.00 | 0.6% | 115,590–117,242 |
+| green-tea | 97,760 | 0.00 | 1.00 | 2.00 | 0.3% | 97,094–97,837 |
+| fastify | 86,470 | 1.00 | 2.00 | 2.00 | 0.3% | 86,202–86,829 |
+| express | 24,005 | 3.00 | 6.00 | 9.00 | 0.3% | 23,989–24,136 |
 
 ### Route param
 
 | Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
 | --- | --- | --- | --- | --- | --- | --- |
-| raw-http | 115,437 | 0.00 | 1.00 | 1.00 | 0.3% | 115,245–116,013 |
-| green-tea | 93,114 | 1.00 | 2.00 | 2.00 | 0.1% | 92,947–93,126 |
-| fastify | 85,805 | 1.00 | 2.00 | 2.00 | 0.2% | 85,498–85,856 |
-| express | 23,739 | 4.00 | 5.00 | 8.00 | 0.1% | 23,694–23,778 |
+| raw-http | 117,024 | 0.00 | 1.00 | 1.00 | 0.3% | 116,538–117,242 |
+| green-tea | 92,384 | 1.00 | 2.00 | 2.00 | 0.5% | 91,795–92,998 |
+| fastify | 85,754 | 1.00 | 2.00 | 2.00 | 0.3% | 85,651–86,317 |
+| express | 23,666 | 4.00 | 5.00 | 8.00 | 0.1% | 23,666–23,720 |
 
 ### Pipeline (3 steps) (approximation)
 
 | Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
 | --- | --- | --- | --- | --- | --- | --- |
-| raw-http | 114,016 | 0.00 | 1.00 | 1.00 | 0.1% | 114,003–114,157 |
-| green-tea | 84,230 | 1.00 | 2.00 | 2.00 | 0.5% | 84,179–85,050 |
-| fastify | 83,808 | 1.00 | 2.00 | 2.00 | 0.1% | 83,770–83,898 |
-| express | 23,758 | 4.00 | 5.00 | 8.00 | 0.1% | 23,720–23,778 |
+| raw-http | 114,157 | 0.00 | 1.00 | 1.00 | 0.2% | 113,862–114,554 |
+| fastify | 84,320 | 1.00 | 2.00 | 2.00 | 0.1% | 84,269–84,422 |
+| green-tea | 83,962 | 1.00 | 2.00 | 2.00 | 0.4% | 83,590–84,358 |
+| express | 23,829 | 4.00 | 5.00 | 8.00 | 0.1% | 23,768–23,851 |
 
 ### POST JSON + validation
 
 | Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
 | --- | --- | --- | --- | --- | --- | --- |
-| raw-http | 99,014 | 0.00 | 1.00 | 2.00 | 0.3% | 98,438–99,181 |
-| green-tea | 76,486 | 1.00 | 2.00 | 2.00 | 0.2% | 76,397–76,691 |
-| fastify | 63,869 | 1.00 | 2.00 | 3.00 | 0.3% | 63,837–64,323 |
-| express | 19,986 | 4.00 | 7.00 | 26.00 | 0.4% | 19,886–20,069 |
+| raw-http | 100,230 | 0.00 | 1.00 | 2.00 | 0.1% | 100,064–100,294 |
+| green-tea | 76,243 | 1.00 | 2.00 | 2.00 | 0.2% | 76,192–76,550 |
+| fastify | 63,222 | 1.00 | 2.00 | 3.00 | 0.7% | 62,307–63,229 |
+| express | 19,870 | 4.00 | 7.00 | 23.00 | 0.3% | 19,758–19,883 |
 
 ## Step-scaling (green-tea)
 
 | Path | Steps | req/s |
 | --- | --- | --- |
-| /steps/0 | 0 | 92,858 |
-| /steps/3 | 3 | 81,658 |
-| /steps/5 | 5 | 71,968 |
+| /steps/0 | 0 | 91,386 |
+| /steps/3 | 3 | 81,530 |
+| /steps/5 | 5 | 72,237 |
 
-Each additional pipeline step costs roughly 4,178 req/s (-22.5% over 5 steps), on this box.
+Each additional pipeline step costs roughly 3,830 req/s (-21.0% over 5 steps), on this box.
 
 ## Cost of secure-by-default (green-tea)
 
 | Label | req/s |
 | --- | --- |
-| security:false (parity) | 98,912 |
-| security:true (default) | 93,178 |
+| security:false (parity) | 97,760 |
+| security:true (default) | 93,306 |
 
-The real cost of running secure-by-default (rather than the parity-mode `security:false` used above) is ~5.8% req/s on this box.
+The real cost of running secure-by-default (rather than the parity-mode `security:false` used above) is ~4.6% req/s on this box.
+
+> Scope: this micro-bench currently measures the security-**headers** cost only (`security:false` vs
+> `security:true` on `/hello`). The incremental cost of `@body` validation and CORS is not separately
+> measured yet (deferred) — so this table is narrower than the design spec's 4-point plan.
 
 ## Methodology
 
@@ -95,3 +99,6 @@ The real cost of running secure-by-default (rather than the parity-mode `securit
   `JSON.stringify` in these benchmarks. Fastify's `fast-json-stringify` response serializer is
   deliberately **not** engaged — only its input `schema.body` validation is used — so no framework
   gets a serialization fast path the others lack.
+- **Content-type charset asymmetry (disclosed, not controlled)**: green-tea and raw-http send
+  `Content-Type: application/json` while Express and Fastify send `application/json; charset=utf-8`.
+  This is a minor header-byte asymmetry that is disclosed here rather than normalized away.
diff --git a/bench/render.ts b/bench/render.ts
index dd53142..198dbec 100644
--- a/bench/render.ts
+++ b/bench/render.ts
@@ -147,6 +147,10 @@ function renderSecureCost(secureCost: RenderData['secureCost']): string {
     '',
     deltaNote,
     '',
+    '> Scope: this micro-bench currently measures the security-**headers** cost only (`security:false` vs',
+    '> `security:true` on `/hello`). The incremental cost of `@body` validation and CORS is not separately',
+    '> measured yet (deferred) — so this table is narrower than the design spec\'s 4-point plan.',
+    '',
   ].join('\n');
 }
 
@@ -167,6 +171,9 @@ function renderMethodology(): string {
     '  `JSON.stringify` in these benchmarks. Fastify\'s `fast-json-stringify` response serializer is',
     '  deliberately **not** engaged — only its input `schema.body` validation is used — so no framework',
     '  gets a serialization fast path the others lack.',
+    '- **Content-type charset asymmetry (disclosed, not controlled)**: green-tea and raw-http send',
+    '  `Content-Type: application/json` while Express and Fastify send `application/json; charset=utf-8`.',
+    '  This is a minor header-byte asymmetry that is disclosed here rather than normalized away.',
     '',
   ].join('\n');
 }
diff --git a/bench/results.json b/bench/results.json
index 5c99373..df932d3 100644
--- a/bench/results.json
+++ b/bench/results.json
@@ -1,7 +1,7 @@
 {
   "env": {
     "date": "2026-07-07",
-    "commit": "926ca39",
+    "commit": "daa13f6",
     "node": "v22.22.2",
     "os": "darwin",
     "cpu": "Apple M4 Max (16 cores)",
@@ -23,11 +23,11 @@
         {
           "framework": "raw-http",
           "reqSec": {
-            "median": 115398.4,
-            "min": 115078.4,
-            "max": 116076.8,
-            "stddev": 416.2570146222469,
-            "cv": 0.003603399427582749
+            "median": 116166.4,
+            "min": 115590.4,
+            "max": 117241.6,
+            "stddev": 684.2913999167365,
+            "cv": 0.005882187997853885
           },
           "p50": 0,
           "p99": 1,
@@ -36,11 +36,11 @@
         {
           "framework": "fastify",
           "reqSec": {
-            "median": 85881.6,
-            "min": 85382.4,
-            "max": 86073.6,
-            "stddev": 291.32305092457597,
-            "cv": 0.0033961968743538755
+            "median": 86470.4,
+            "min": 86201.6,
+            "max": 86828.8,
+            "stddev": 256.92278130900564,
+            "cv": 0.0029701964075911015
           },
           "p50": 1,
           "p99": 2,
@@ -49,24 +49,24 @@
         {
           "framework": "express",
           "reqSec": {
-            "median": 24126.4,
-            "min": 24072,
-            "max": 24158.4,
-            "stddev": 35.66560746090835,
-            "cv": 0.0014787390042501193
+            "median": 24004.8,
+            "min": 23988.8,
+            "max": 24136,
+            "stddev": 65.9438144685816,
+            "cv": 0.002742722036525155
           },
           "p50": 3,
-          "p99": 5,
-          "p999": 8
+          "p99": 6,
+          "p999": 9
         },
         {
           "framework": "green-tea",
           "reqSec": {
-            "median": 98912,
-            "min": 98835.2,
-            "max": 99961.6,
-            "stddev": 513.8455626180164,
-            "cv": 0.005178001751557391
+            "median": 97760,
+            "min": 97094.4,
+            "max": 97836.8,
+            "stddev": 333.34655973759686,
+            "cv": 0.003416705658430423
           },
           "p50": 0,
           "p99": 1,
@@ -81,11 +81,11 @@
         {
           "framework": "raw-http",
           "reqSec": {
-            "median": 115436.8,
-            "min": 115244.8,
-            "max": 116012.8,
-            "stddev": 326.3372488699382,
-            "cv": 0.0028238464382747876
+            "median": 117024,
+            "min": 116537.6,
+            "max": 117241.6,
+            "stddev": 294.3072317607338,
+            "cv": 0.0025168575864821115
           },
           "p50": 0,
           "p99": 1,
@@ -94,11 +94,11 @@
         {
           "framework": "fastify",
           "reqSec": {
-            "median": 85804.8,
-            "min": 85497.6,
-            "max": 85856,
-            "stddev": 158.26975565645782,
-            "cv": 0.0018463688799174882
+            "median": 85753.6,
+            "min": 85651.2,
+            "max": 86316.8,
+            "stddev": 292.6323746044982,
+            "cv": 0.0034063777495308683
           },
           "p50": 1,
           "p99": 2,
@@ -107,11 +107,11 @@
         {
           "framework": "express",
           "reqSec": {
-            "median": 23739.2,
-            "min": 23694.4,
-            "max": 23777.6,
-            "stddev": 33.99973856108518,
-            "cv": 0.001432347940819078
+            "median": 23665.6,
+            "min": 23665.6,
+            "max": 23720,
+            "stddev": 25.64440593103281,
+            "cv": 0.0010827856221020677
           },
           "p50": 4,
           "p99": 5,
@@ -120,11 +120,11 @@
         {
           "framework": "green-tea",
           "reqSec": {
-            "median": 93113.6,
-            "min": 92947.2,
-            "max": 93126.4,
-            "stddev": 81.62613960409276,
-            "cv": 0.000877111912051406
+            "median": 92384,
+            "min": 91795.2,
+            "max": 92998.4,
+            "stddev": 491.24140252584004,
+            "cv": 0.005316895043385614
           },
           "p50": 1,
           "p99": 2,
@@ -140,11 +140,11 @@
         {
           "framework": "raw-http",
           "reqSec": {
-            "median": 114016,
-            "min": 114003.2,
-            "max": 114156.8,
-            "stddev": 69.58722743594919,
-            "cv": 0.0006101003060058202
+            "median": 114156.8,
+            "min": 113862.4,
+            "max": 114553.6,
+            "stddev": 283.21155029804993,
+            "cv": 0.0024801579427618002
           },
           "p50": 0,
           "p99": 1,
@@ -153,11 +153,11 @@
         {
           "framework": "fastify",
           "reqSec": {
-            "median": 83808,
-            "min": 83769.61,
-            "max": 83897.6,
-            "stddev": 53.62772106538676,
-            "cv": 0.0006397575458676833
+            "median": 84320,
+            "min": 84268.8,
+            "max": 84422.4,
+            "stddev": 63.857619400938304,
+            "cv": 0.0007571714540811431
           },
           "p50": 1,
           "p99": 2,
@@ -166,11 +166,11 @@
         {
           "framework": "express",
           "reqSec": {
-            "median": 23758.4,
-            "min": 23720,
-            "max": 23777.6,
-            "stddev": 23.946607275352836,
-            "cv": 0.001008193300579018
+            "median": 23828.8,
+            "min": 23768,
+            "max": 23851.2,
+            "stddev": 35.151481713672865,
+            "cv": 0.001475960770644645
           },
           "p50": 4,
           "p99": 5,
@@ -179,11 +179,11 @@
         {
           "framework": "green-tea",
           "reqSec": {
-            "median": 84230.4,
-            "min": 84179.2,
-            "max": 85049.6,
-            "stddev": 398.7907053413738,
-            "cv": 0.004720176328277377
+            "median": 83961.6,
+            "min": 83590.4,
+            "max": 84358.4,
+            "stddev": 313.5927436802211,
+            "cv": 0.0037345747973909107
           },
           "p50": 1,
           "p99": 2,
@@ -198,11 +198,11 @@
         {
           "framework": "raw-http",
           "reqSec": {
-            "median": 99014.4,
-            "min": 98438.4,
-            "max": 99180.8,
-            "stddev": 318.0885131881125,
-            "cv": 0.0032169839814651393
+            "median": 100230.4,
+            "min": 100064,
+            "max": 100294.4,
+            "stddev": 97.10768364152092,
+            "cv": 0.0009691746695970135
           },
           "p50": 0,
           "p99": 1,
@@ -211,11 +211,11 @@
         {
           "framework": "fastify",
           "reqSec": {
-            "median": 63868.8,
-            "min": 63836.8,
-            "max": 64323.2,
-            "stddev": 222.1331732692473,
-            "cv": 0.0034703102857891206
+            "median": 63222.4,
+            "min": 62307.2,
+            "max": 63228.8,
+            "stddev": 432.9457959401203,
+            "cv": 0.006880951458691962
           },
           "p50": 1,
           "p99": 2,
@@ -224,24 +224,24 @@
         {
           "framework": "express",
           "reqSec": {
-            "median": 19985.6,
-            "min": 19886.41,
-            "max": 20068.8,
-            "stddev": 74.55572725597027,
-            "cv": 0.003731467455443308
+            "median": 19870.41,
+            "min": 19758.41,
+            "max": 19883.2,
+            "stddev": 56.05565508195131,
+            "cv": 0.0028257646983895677
           },
           "p50": 4,
           "p99": 7,
-          "p999": 26
+          "p999": 23
         },
         {
           "framework": "green-tea",
           "reqSec": {
-            "median": 76486.4,
-            "min": 76396.8,
-            "max": 76691.2,
-            "stddev": 123.21731480058412,
-            "cv": 0.0016101618664875192
+            "median": 76243.2,
+            "min": 76192,
+            "max": 76550.4,
+            "stddev": 158.26975565645782,
+            "cv": 0.0020735333006502306
           },
           "p50": 1,
           "p99": 2,
@@ -254,27 +254,27 @@
     {
       "path": "/steps/0",
       "steps": 0,
-      "reqSec": 92857.6
+      "reqSec": 91385.6
     },
     {
       "path": "/steps/3",
       "steps": 3,
-      "reqSec": 81657.61
+      "reqSec": 81529.61
     },
     {
       "path": "/steps/5",
       "steps": 5,
-      "reqSec": 71968
+      "reqSec": 72236.8
     }
   ],
   "secureCost": [
     {
       "label": "security:false (parity)",
-      "reqSec": 98912
+      "reqSec": 97760
     },
     {
       "label": "security:true (default)",
-      "reqSec": 93177.6
+      "reqSec": 93305.6
     }
   ]
 }
\ No newline at end of file
diff --git a/package.json b/package.json
index f3b477c..ba216c5 100644
--- a/package.json
+++ b/package.json
@@ -11,6 +11,7 @@
     "test": "vitest run",
     "test:dev": "vitest",
     "typecheck": "tsc --noEmit -p tsconfig.json",
+    "typecheck:bench": "tsc --noEmit -p bench/tsconfig.json",
     "bench": "tsx bench/run.ts"
   },
   "dependencies": {

From fe1831a80abdd6bccb97557916ebf7a87e98292b Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Mon, 6 Jul 2026 23:30:40 -0500
Subject: [PATCH 069/139] feat(bench): add NestJS (platform-express +
 platform-fastify) servers

Signed-off-by: Diego Resendez 
---
 bench/render.ts                 |   6 +
 bench/run.ts                    |   2 +-
 bench/servers/_nest-shared.ts   |  20 +
 bench/servers/nestjs-express.ts |  17 +
 bench/servers/nestjs-fastify.ts |  13 +
 package-lock.json               | 675 ++++++++++++++++++++++++++++++++
 package.json                    |   5 +
 7 files changed, 737 insertions(+), 1 deletion(-)
 create mode 100644 bench/servers/_nest-shared.ts
 create mode 100644 bench/servers/nestjs-express.ts
 create mode 100644 bench/servers/nestjs-fastify.ts

diff --git a/bench/render.ts b/bench/render.ts
index 198dbec..f6cf4ab 100644
--- a/bench/render.ts
+++ b/bench/render.ts
@@ -174,6 +174,12 @@ function renderMethodology(): string {
     '- **Content-type charset asymmetry (disclosed, not controlled)**: green-tea and raw-http send',
     '  `Content-Type: application/json` while Express and Fastify send `application/json; charset=utf-8`.',
     '  This is a minor header-byte asymmetry that is disclosed here rather than normalized away.',
+    '- **NestJS runs on an underlying adapter** (Express or Fastify): the `nestjs-express` / `nestjs-fastify`',
+    "  rows measure Nest's DI / decorator / routing overhead **on top of** that adapter, so compare each",
+    '  against its own base (`express` / `fastify`) rather than against the field. Nest\'s idiomatic',
+    '  `ValidationPipe` / class-validator is **not** used — `/validate` performs the same manual field check',
+    '  as every other server (parity). The same parity controls apply: `etag` and `x-powered-by` are disabled',
+    '  on the underlying Express instance, and `keepAliveTimeout` is 5000 on both adapters.',
     '',
   ].join('\n');
 }
diff --git a/bench/run.ts b/bench/run.ts
index 431269d..cf4398b 100644
--- a/bench/run.ts
+++ b/bench/run.ts
@@ -87,7 +87,7 @@ async function measure(port: number, path: string, method: 'GET' | 'POST', body?
 }
 
 async function main(): Promise {
-  const frameworks = ['raw-http', 'fastify', 'express', 'green-tea'];
+  const frameworks = ['raw-http', 'fastify', 'express', 'green-tea', 'nestjs-express', 'nestjs-fastify'];
   const scenarioBlocks: ScenarioBlock[] = SCENARIOS.map((s) => ({
     title: s.title,
     name: s.name,
diff --git a/bench/servers/_nest-shared.ts b/bench/servers/_nest-shared.ts
new file mode 100644
index 0000000..43e89d8
--- /dev/null
+++ b/bench/servers/_nest-shared.ts
@@ -0,0 +1,20 @@
+import { Module, Controller, Get, Post, Param, Body, HttpException, MiddlewareConsumer, NestModule } from '@nestjs/common';
+
+@Controller()
+export class BenchController {
+  @Get('hello') hello() { return { hello: 'world' }; }
+  @Get('users/:id') user(@Param('id') id: string) { return { id }; }
+  @Get('pipeline') pipeline() { return { hello: 'world', s3: 3 }; }
+  @Post('validate') validate(@Body() b: any) {
+    if (!(b && typeof b.email === 'string' && b.email.includes('@'))) throw new HttpException({ error: 'invalid' }, 422);
+    return { email: b.email };
+  }
+}
+
+// pipeline parity: 3 middleware hops on /pipeline (approximation of 3 @Steps), adapter-agnostic
+const mw = (_n: number) => (_req: any, _res: any, next: any) => next();
+
+@Module({ controllers: [BenchController] })
+export class BenchModule implements NestModule {
+  configure(c: MiddlewareConsumer) { c.apply(mw(1), mw(2), mw(3)).forRoutes('pipeline'); }
+}
diff --git a/bench/servers/nestjs-express.ts b/bench/servers/nestjs-express.ts
new file mode 100644
index 0000000..7945244
--- /dev/null
+++ b/bench/servers/nestjs-express.ts
@@ -0,0 +1,17 @@
+import 'reflect-metadata';
+import { NestFactory } from '@nestjs/core';
+import { ExpressAdapter } from '@nestjs/platform-express';
+import express from 'express';
+import { BenchModule } from './_nest-shared';
+
+async function main() {
+  const inst = express();
+  inst.disable('x-powered-by');
+  inst.set('etag', false);
+  const app = await NestFactory.create(BenchModule, new ExpressAdapter(inst), { logger: false });
+  await app.listen(0, '127.0.0.1');
+  const server = app.getHttpServer();
+  server.keepAliveTimeout = 5000; // parity (works on Node http.Server after listen)
+  console.log(`READY ${server.address().port}`);
+}
+main().catch((e) => { console.error(e); process.exit(1); });
diff --git a/bench/servers/nestjs-fastify.ts b/bench/servers/nestjs-fastify.ts
new file mode 100644
index 0000000..4b95565
--- /dev/null
+++ b/bench/servers/nestjs-fastify.ts
@@ -0,0 +1,13 @@
+import 'reflect-metadata';
+import { NestFactory } from '@nestjs/core';
+import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
+import { BenchModule } from './_nest-shared';
+
+async function main() {
+  const adapter = new FastifyAdapter({ logger: false, keepAliveTimeout: 5000 }); // parity via constructor
+  const app = await NestFactory.create(BenchModule, adapter, { logger: false });
+  await app.listen(0, '127.0.0.1');
+  const server = app.getHttpServer();
+  console.log(`READY ${(server.address() as any).port}`);
+}
+main().catch((e) => { console.error(e); process.exit(1); });
diff --git a/package-lock.json b/package-lock.json
index 03e6923..579edfa 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -12,6 +12,10 @@
         "reflect-metadata": "0.2.2"
       },
       "devDependencies": {
+        "@nestjs/common": "^11.1.27",
+        "@nestjs/core": "^11.1.27",
+        "@nestjs/platform-express": "^11.1.27",
+        "@nestjs/platform-fastify": "^11.1.27",
         "@types/autocannon": "^7.12.7",
         "@types/express": "^5.0.6",
         "@types/node": "^18.19.0",
@@ -20,6 +24,7 @@
         "express": "^5.2.1",
         "fastify": "^5.10.0",
         "graphql": "^16.9.0",
+        "rxjs": "^7.8.2",
         "tsx": "^4.23.0",
         "typescript": "^5.5.0",
         "vitest": "^2.0.0",
@@ -41,6 +46,17 @@
       "dev": true,
       "license": "Apache-2.0"
     },
+    "node_modules/@borewit/text-codec": {
+      "version": "0.2.2",
+      "resolved": "https://registry.npmjs.org/@borewit/text-codec/-/text-codec-0.2.2.tgz",
+      "integrity": "sha512-DDaRehssg1aNrH4+2hnj1B7vnUGEjU6OIlyRdkMd0aUdIUvKXrJfXsy8LVtXAy7DRvYVluWbMspsRhz2lcW0mQ==",
+      "dev": true,
+      "license": "MIT",
+      "funding": {
+        "type": "github",
+        "url": "https://github.com/sponsors/Borewit"
+      }
+    },
     "node_modules/@colors/colors": {
       "version": "1.5.0",
       "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz",
@@ -516,6 +532,44 @@
         "fast-uri": "^3.0.0"
       }
     },
+    "node_modules/@fastify/cors": {
+      "version": "11.2.0",
+      "resolved": "https://registry.npmjs.org/@fastify/cors/-/cors-11.2.0.tgz",
+      "integrity": "sha512-LbLHBuSAdGdSFZYTLVA3+Ch2t+sA6nq3Ejc6XLAKiQ6ViS2qFnvicpj0htsx03FyYeLs04HfRNBsz/a8SvbcUw==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/fastify"
+        },
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/fastify"
+        }
+      ],
+      "license": "MIT",
+      "dependencies": {
+        "fastify-plugin": "^5.0.0",
+        "toad-cache": "^3.7.0"
+      }
+    },
+    "node_modules/@fastify/cors/node_modules/fastify-plugin": {
+      "version": "5.1.0",
+      "resolved": "https://registry.npmjs.org/fastify-plugin/-/fastify-plugin-5.1.0.tgz",
+      "integrity": "sha512-FAIDA8eovSt5qcDgcBvDuX/v0Cjz0ohGhENZ/wpc3y+oZCY2afZ9Baqql3g/lC+OHRnciQol4ww7tuthOb9idw==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/fastify"
+        },
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/fastify"
+        }
+      ],
+      "license": "MIT"
+    },
     "node_modules/@fastify/error": {
       "version": "4.2.0",
       "resolved": "https://registry.npmjs.org/@fastify/error/-/error-4.2.0.tgz",
@@ -553,6 +607,44 @@
         "fast-json-stringify": "^7.0.0"
       }
     },
+    "node_modules/@fastify/formbody": {
+      "version": "8.0.2",
+      "resolved": "https://registry.npmjs.org/@fastify/formbody/-/formbody-8.0.2.tgz",
+      "integrity": "sha512-84v5J2KrkXzjgBpYnaNRPqwgMsmY7ZDjuj0YVuMR3NXCJRCgKEZy/taSP1wUYGn0onfxJpLyRGDLa+NMaDJtnA==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/fastify"
+        },
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/fastify"
+        }
+      ],
+      "license": "MIT",
+      "dependencies": {
+        "fast-querystring": "^1.1.2",
+        "fastify-plugin": "^5.0.0"
+      }
+    },
+    "node_modules/@fastify/formbody/node_modules/fastify-plugin": {
+      "version": "5.1.0",
+      "resolved": "https://registry.npmjs.org/fastify-plugin/-/fastify-plugin-5.1.0.tgz",
+      "integrity": "sha512-FAIDA8eovSt5qcDgcBvDuX/v0Cjz0ohGhENZ/wpc3y+oZCY2afZ9Baqql3g/lC+OHRnciQol4ww7tuthOb9idw==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/fastify"
+        },
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/fastify"
+        }
+      ],
+      "license": "MIT"
+    },
     "node_modules/@fastify/forwarded": {
       "version": "3.0.1",
       "resolved": "https://registry.npmjs.org/@fastify/forwarded/-/forwarded-3.0.1.tgz",
@@ -618,6 +710,16 @@
       "dev": true,
       "license": "MIT"
     },
+    "node_modules/@lukeed/csprng": {
+      "version": "1.1.0",
+      "resolved": "https://registry.npmjs.org/@lukeed/csprng/-/csprng-1.1.0.tgz",
+      "integrity": "sha512-Z7C/xXCiGWsg0KuKsHTKJxbWhpI3Vs5GwLfOean7MGyVFGqdRgBbAjOCh6u4bbjPc/8MJ2pZmK/0DLdCbivLDA==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=8"
+      }
+    },
     "node_modules/@minimistjs/subarg": {
       "version": "1.0.0",
       "resolved": "https://registry.npmjs.org/@minimistjs/subarg/-/subarg-1.0.0.tgz",
@@ -628,6 +730,196 @@
         "minimist": "^1.1.0"
       }
     },
+    "node_modules/@nestjs/common": {
+      "version": "11.1.27",
+      "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-11.1.27.tgz",
+      "integrity": "sha512-kEGSzqM2lWr4whh4Ubflw+oPZSEzxvRMu9WL+LveZploJWTjec5bBlCiRVlVzTPg2kIwBiLwWSvCCW7Wnin1gg==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "file-type": "21.3.4",
+        "iterare": "1.2.1",
+        "load-esm": "1.0.3",
+        "tslib": "2.8.1",
+        "uid": "2.0.2"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/nest"
+      },
+      "peerDependencies": {
+        "class-transformer": ">=0.4.1",
+        "class-validator": ">=0.13.2",
+        "reflect-metadata": "^0.1.12 || ^0.2.0",
+        "rxjs": "^7.1.0"
+      },
+      "peerDependenciesMeta": {
+        "class-transformer": {
+          "optional": true
+        },
+        "class-validator": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/@nestjs/core": {
+      "version": "11.1.27",
+      "resolved": "https://registry.npmjs.org/@nestjs/core/-/core-11.1.27.tgz",
+      "integrity": "sha512-K6DX7hcqmZdeXkv7tsPakKBRCgqL19a4mtbX4FluY0hWtFdtPKp6lbe+lb8gWPfvLdbOWr/CPScn7BSjBX+Ecg==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "fast-safe-stringify": "2.1.1",
+        "iterare": "1.2.1",
+        "path-to-regexp": "8.4.2",
+        "tslib": "2.8.1",
+        "uid": "2.0.2"
+      },
+      "engines": {
+        "node": ">= 20"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/nest"
+      },
+      "peerDependencies": {
+        "@nestjs/common": "^11.0.0",
+        "@nestjs/microservices": "^11.0.0",
+        "@nestjs/platform-express": "^11.0.0",
+        "@nestjs/websockets": "^11.0.0",
+        "reflect-metadata": "^0.1.12 || ^0.2.0",
+        "rxjs": "^7.1.0"
+      },
+      "peerDependenciesMeta": {
+        "@nestjs/microservices": {
+          "optional": true
+        },
+        "@nestjs/platform-express": {
+          "optional": true
+        },
+        "@nestjs/websockets": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/@nestjs/platform-express": {
+      "version": "11.1.27",
+      "resolved": "https://registry.npmjs.org/@nestjs/platform-express/-/platform-express-11.1.27.tgz",
+      "integrity": "sha512-0ZFhz6H6EdGh4xQVbUNwjoAwBuz73P7FvUAl67h9CTdMqQlJDaQYJApBv8pKfVZ1fGjMCbl0m9DcC6pXaZPWSQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "cors": "2.8.6",
+        "express": "5.2.1",
+        "multer": "2.1.1",
+        "path-to-regexp": "8.4.2",
+        "tslib": "2.8.1"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/nest"
+      },
+      "peerDependencies": {
+        "@nestjs/common": "^11.0.0",
+        "@nestjs/core": "^11.0.0"
+      }
+    },
+    "node_modules/@nestjs/platform-fastify": {
+      "version": "11.1.27",
+      "resolved": "https://registry.npmjs.org/@nestjs/platform-fastify/-/platform-fastify-11.1.27.tgz",
+      "integrity": "sha512-rZMPS0RMP9P2O7Y/shAP0kKwrHElGO9cPTlgtdWpQ6JEX58uhYEJLGsU/X9a9l18DNSxxb3YjrEiVVuI2Iv6MA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@fastify/cors": "11.2.0",
+        "@fastify/formbody": "8.0.2",
+        "fast-querystring": "1.1.2",
+        "fastify": "5.8.5",
+        "fastify-plugin": "6.0.0",
+        "find-my-way": "9.6.0",
+        "light-my-request": "6.6.0",
+        "path-to-regexp": "8.4.2",
+        "reusify": "1.1.0",
+        "tslib": "2.8.1"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/nest"
+      },
+      "peerDependencies": {
+        "@fastify/static": "^8.0.0 || ^9.0.0",
+        "@fastify/view": "^10.0.0 || ^11.0.0 || ^12.0.0",
+        "@nestjs/common": "^11.0.0",
+        "@nestjs/core": "^11.0.0"
+      },
+      "peerDependenciesMeta": {
+        "@fastify/static": {
+          "optional": true
+        },
+        "@fastify/view": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/@nestjs/platform-fastify/node_modules/fast-json-stringify": {
+      "version": "6.4.0",
+      "resolved": "https://registry.npmjs.org/fast-json-stringify/-/fast-json-stringify-6.4.0.tgz",
+      "integrity": "sha512-ibRCQ0GZKJIQ+P3Et1h0LhPgp3PMTYk0MH8O+kW3lNYsvmaQww5Nn3f1jf73Q0jR1Yz3a1CDP4/NZD3vOajWJQ==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/fastify"
+        },
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/fastify"
+        }
+      ],
+      "license": "MIT",
+      "dependencies": {
+        "@fastify/merge-json-schemas": "^0.2.0",
+        "ajv": "^8.12.0",
+        "ajv-formats": "^3.0.1",
+        "fast-uri": "^3.0.0",
+        "json-schema-ref-resolver": "^3.0.0",
+        "rfdc": "^1.2.0"
+      }
+    },
+    "node_modules/@nestjs/platform-fastify/node_modules/fastify": {
+      "version": "5.8.5",
+      "resolved": "https://registry.npmjs.org/fastify/-/fastify-5.8.5.tgz",
+      "integrity": "sha512-Yqptv59pQzPgQUSIm87hMqHJmdkb1+GPxdE6vW6FRyVE9G86mt7rOghitiU4JHRaTyDUk9pfeKmDeu70lAwM4Q==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/fastify"
+        },
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/fastify"
+        }
+      ],
+      "license": "MIT",
+      "dependencies": {
+        "@fastify/ajv-compiler": "^4.0.5",
+        "@fastify/error": "^4.0.0",
+        "@fastify/fast-json-stringify-compiler": "^5.0.0",
+        "@fastify/proxy-addr": "^5.0.0",
+        "abstract-logging": "^2.0.1",
+        "avvio": "^9.0.0",
+        "fast-json-stringify": "^6.0.0",
+        "find-my-way": "^9.0.0",
+        "light-my-request": "^6.0.0",
+        "pino": "^9.14.0 || ^10.1.0",
+        "process-warning": "^5.0.0",
+        "rfdc": "^1.3.1",
+        "secure-json-parse": "^4.0.0",
+        "semver": "^7.6.0",
+        "toad-cache": "^3.7.0"
+      }
+    },
     "node_modules/@pinojs/redact": {
       "version": "0.4.0",
       "resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz",
@@ -985,6 +1277,31 @@
         "win32"
       ]
     },
+    "node_modules/@tokenizer/inflate": {
+      "version": "0.4.1",
+      "resolved": "https://registry.npmjs.org/@tokenizer/inflate/-/inflate-0.4.1.tgz",
+      "integrity": "sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "debug": "^4.4.3",
+        "token-types": "^6.1.1"
+      },
+      "engines": {
+        "node": ">=18"
+      },
+      "funding": {
+        "type": "github",
+        "url": "https://github.com/sponsors/Borewit"
+      }
+    },
+    "node_modules/@tokenizer/token": {
+      "version": "0.3.0",
+      "resolved": "https://registry.npmjs.org/@tokenizer/token/-/token-0.3.0.tgz",
+      "integrity": "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/@types/autocannon": {
       "version": "7.12.7",
       "resolved": "https://registry.npmjs.org/@types/autocannon/-/autocannon-7.12.7.tgz",
@@ -1305,6 +1622,13 @@
         "url": "https://github.com/chalk/ansi-styles?sponsor=1"
       }
     },
+    "node_modules/append-field": {
+      "version": "1.0.0",
+      "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz",
+      "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/assertion-error": {
       "version": "2.0.1",
       "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
@@ -1473,6 +1797,25 @@
         "ieee754": "^1.1.13"
       }
     },
+    "node_modules/buffer-from": {
+      "version": "1.1.2",
+      "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
+      "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/busboy": {
+      "version": "1.6.0",
+      "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
+      "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==",
+      "dev": true,
+      "dependencies": {
+        "streamsearch": "^1.1.0"
+      },
+      "engines": {
+        "node": ">=10.16.0"
+      }
+    },
     "node_modules/bytes": {
       "version": "3.1.2",
       "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
@@ -1634,6 +1977,22 @@
         "node": ">= 0.8"
       }
     },
+    "node_modules/concat-stream": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz",
+      "integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==",
+      "dev": true,
+      "engines": [
+        "node >= 6.0"
+      ],
+      "license": "MIT",
+      "dependencies": {
+        "buffer-from": "^1.0.0",
+        "inherits": "^2.0.3",
+        "readable-stream": "^3.0.2",
+        "typedarray": "^0.0.6"
+      }
+    },
     "node_modules/content-disposition": {
       "version": "1.1.0",
       "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz",
@@ -1678,6 +2037,24 @@
         "node": ">=6.6.0"
       }
     },
+    "node_modules/cors": {
+      "version": "2.8.6",
+      "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz",
+      "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "object-assign": "^4",
+        "vary": "^1"
+      },
+      "engines": {
+        "node": ">= 0.10"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
     "node_modules/cross-argv": {
       "version": "2.0.0",
       "resolved": "https://registry.npmjs.org/cross-argv/-/cross-argv-2.0.0.tgz",
@@ -2007,6 +2384,13 @@
         "fast-decode-uri-component": "^1.0.1"
       }
     },
+    "node_modules/fast-safe-stringify": {
+      "version": "2.1.1",
+      "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz",
+      "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/fast-uri": {
       "version": "3.1.3",
       "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.3.tgz",
@@ -2058,6 +2442,23 @@
         "toad-cache": "^3.7.0"
       }
     },
+    "node_modules/fastify-plugin": {
+      "version": "6.0.0",
+      "resolved": "https://registry.npmjs.org/fastify-plugin/-/fastify-plugin-6.0.0.tgz",
+      "integrity": "sha512-fZOty7z3O7vOliF6d8bHE3wiEh1KcNnKEQensSgTk9C1DvN6nRLS++XVd86v33Hw/8u9Un8A1zDrQ8ujcQDHEg==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/fastify"
+        },
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/fastify"
+        }
+      ],
+      "license": "MIT"
+    },
     "node_modules/fastq": {
       "version": "1.20.1",
       "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz",
@@ -2068,6 +2469,25 @@
         "reusify": "^1.0.4"
       }
     },
+    "node_modules/file-type": {
+      "version": "21.3.4",
+      "resolved": "https://registry.npmjs.org/file-type/-/file-type-21.3.4.tgz",
+      "integrity": "sha512-Ievi/yy8DS3ygGvT47PjSfdFoX+2isQueoYP1cntFW1JLYAuS4GD7NUPGg4zv2iZfV52uDyk5w5Z0TdpRS6Q1g==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@tokenizer/inflate": "^0.4.1",
+        "strtok3": "^10.3.4",
+        "token-types": "^6.1.1",
+        "uint8array-extras": "^1.4.0"
+      },
+      "engines": {
+        "node": ">=20"
+      },
+      "funding": {
+        "url": "https://github.com/sindresorhus/file-type?sponsor=1"
+      }
+    },
     "node_modules/finalhandler": {
       "version": "2.1.1",
       "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz",
@@ -2445,6 +2865,16 @@
       "dev": true,
       "license": "MIT"
     },
+    "node_modules/iterare": {
+      "version": "1.2.1",
+      "resolved": "https://registry.npmjs.org/iterare/-/iterare-1.2.1.tgz",
+      "integrity": "sha512-RKYVTCjAnRthyJes037NX/IiqeidgN1xc3j1RjFfECFp28A1GVwK9nA+i0rJPaHqSZwygLzRnFlzUuHFoWWy+Q==",
+      "dev": true,
+      "license": "ISC",
+      "engines": {
+        "node": ">=6"
+      }
+    },
     "node_modules/json-schema-ref-resolver": {
       "version": "3.0.0",
       "resolved": "https://registry.npmjs.org/json-schema-ref-resolver/-/json-schema-ref-resolver-3.0.0.tgz",
@@ -2525,6 +2955,26 @@
       ],
       "license": "MIT"
     },
+    "node_modules/load-esm": {
+      "version": "1.0.3",
+      "resolved": "https://registry.npmjs.org/load-esm/-/load-esm-1.0.3.tgz",
+      "integrity": "sha512-v5xlu8eHD1+6r8EHTg6hfmO97LN8ugKtiXcy5e6oN72iD2r6u0RPfLl6fxM+7Wnh2ZRq15o0russMst44WauPA==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/Borewit"
+        },
+        {
+          "type": "buymeacoffee",
+          "url": "https://buymeacoffee.com/borewit"
+        }
+      ],
+      "license": "MIT",
+      "engines": {
+        "node": ">=13.2.0"
+      }
+    },
     "node_modules/lodash.chunk": {
       "version": "4.2.0",
       "resolved": "https://registry.npmjs.org/lodash.chunk/-/lodash.chunk-4.2.0.tgz",
@@ -2647,6 +3097,73 @@
       "dev": true,
       "license": "MIT"
     },
+    "node_modules/multer": {
+      "version": "2.1.1",
+      "resolved": "https://registry.npmjs.org/multer/-/multer-2.1.1.tgz",
+      "integrity": "sha512-mo+QTzKlx8R7E5ylSXxWzGoXoZbOsRMpyitcht8By2KHvMbf3tjwosZ/Mu/XYU6UuJ3VZnODIrak5ZrPiPyB6A==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "append-field": "^1.0.0",
+        "busboy": "^1.6.0",
+        "concat-stream": "^2.0.0",
+        "type-is": "^1.6.18"
+      },
+      "engines": {
+        "node": ">= 10.16.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/multer/node_modules/media-typer": {
+      "version": "0.3.0",
+      "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
+      "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/multer/node_modules/mime-db": {
+      "version": "1.52.0",
+      "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
+      "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/multer/node_modules/mime-types": {
+      "version": "2.1.35",
+      "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
+      "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "mime-db": "1.52.0"
+      },
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/multer/node_modules/type-is": {
+      "version": "1.6.18",
+      "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
+      "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "media-typer": "0.3.0",
+        "mime-types": "~2.1.24"
+      },
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
     "node_modules/nanoid": {
       "version": "3.3.15",
       "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.15.tgz",
@@ -2676,6 +3193,16 @@
         "node": ">= 0.6"
       }
     },
+    "node_modules/object-assign": {
+      "version": "4.1.1",
+      "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
+      "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=0.10.0"
+      }
+    },
     "node_modules/object-inspect": {
       "version": "1.13.4",
       "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
@@ -2971,6 +3498,21 @@
         "node": ">= 0.10"
       }
     },
+    "node_modules/readable-stream": {
+      "version": "3.6.2",
+      "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
+      "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "inherits": "^2.0.3",
+        "string_decoder": "^1.1.1",
+        "util-deprecate": "^1.0.1"
+      },
+      "engines": {
+        "node": ">= 6"
+      }
+    },
     "node_modules/real-require": {
       "version": "0.2.0",
       "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz",
@@ -3101,6 +3643,37 @@
         "node": ">= 18"
       }
     },
+    "node_modules/rxjs": {
+      "version": "7.8.2",
+      "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz",
+      "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==",
+      "dev": true,
+      "license": "Apache-2.0",
+      "dependencies": {
+        "tslib": "^2.1.0"
+      }
+    },
+    "node_modules/safe-buffer": {
+      "version": "5.2.1",
+      "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
+      "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/feross"
+        },
+        {
+          "type": "patreon",
+          "url": "https://www.patreon.com/feross"
+        },
+        {
+          "type": "consulting",
+          "url": "https://feross.org/support"
+        }
+      ],
+      "license": "MIT"
+    },
     "node_modules/safe-regex2": {
       "version": "5.1.1",
       "resolved": "https://registry.npmjs.org/safe-regex2/-/safe-regex2-5.1.1.tgz",
@@ -3369,6 +3942,25 @@
       "dev": true,
       "license": "MIT"
     },
+    "node_modules/streamsearch": {
+      "version": "1.1.0",
+      "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz",
+      "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==",
+      "dev": true,
+      "engines": {
+        "node": ">=10.0.0"
+      }
+    },
+    "node_modules/string_decoder": {
+      "version": "1.3.0",
+      "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
+      "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "safe-buffer": "~5.2.0"
+      }
+    },
     "node_modules/string-width": {
       "version": "4.2.3",
       "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
@@ -3397,6 +3989,23 @@
         "node": ">=8"
       }
     },
+    "node_modules/strtok3": {
+      "version": "10.3.5",
+      "resolved": "https://registry.npmjs.org/strtok3/-/strtok3-10.3.5.tgz",
+      "integrity": "sha512-ki4hZQfh5rX0QDLLkOCj+h+CVNkqmp/CMf8v8kZpkNVK6jGQooMytqzLZYUVYIZcFZ6yDB70EfD8POcFXiF5oA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@tokenizer/token": "^0.3.0"
+      },
+      "engines": {
+        "node": ">=18"
+      },
+      "funding": {
+        "type": "github",
+        "url": "https://github.com/sponsors/Borewit"
+      }
+    },
     "node_modules/supports-color": {
       "version": "7.2.0",
       "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
@@ -3504,6 +4113,32 @@
         "node": ">=0.6"
       }
     },
+    "node_modules/token-types": {
+      "version": "6.1.2",
+      "resolved": "https://registry.npmjs.org/token-types/-/token-types-6.1.2.tgz",
+      "integrity": "sha512-dRXchy+C0IgK8WPC6xvCHFRIWYUbqqdEIKPaKo/AcTUNzwLTK6AH7RjdLWsEZcAN/TBdtfUw3PYEgPr5VPr6ww==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@borewit/text-codec": "^0.2.1",
+        "@tokenizer/token": "^0.3.0",
+        "ieee754": "^1.2.1"
+      },
+      "engines": {
+        "node": ">=14.16"
+      },
+      "funding": {
+        "type": "github",
+        "url": "https://github.com/sponsors/Borewit"
+      }
+    },
+    "node_modules/tslib": {
+      "version": "2.8.1",
+      "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
+      "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
+      "dev": true,
+      "license": "0BSD"
+    },
     "node_modules/tsx": {
       "version": "4.23.0",
       "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.0.tgz",
@@ -3989,6 +4624,13 @@
         "url": "https://opencollective.com/express"
       }
     },
+    "node_modules/typedarray": {
+      "version": "0.0.6",
+      "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",
+      "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/typescript": {
       "version": "5.9.3",
       "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
@@ -4003,6 +4645,32 @@
         "node": ">=14.17"
       }
     },
+    "node_modules/uid": {
+      "version": "2.0.2",
+      "resolved": "https://registry.npmjs.org/uid/-/uid-2.0.2.tgz",
+      "integrity": "sha512-u3xV3X7uzvi5b1MncmZo3i2Aw222Zk1keqLA1YkHldREkAhAqi65wuPfe7lHx8H/Wzy+8CE7S7uS3jekIM5s8g==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@lukeed/csprng": "^1.0.0"
+      },
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/uint8array-extras": {
+      "version": "1.5.0",
+      "resolved": "https://registry.npmjs.org/uint8array-extras/-/uint8array-extras-1.5.0.tgz",
+      "integrity": "sha512-rvKSBiC5zqCCiDZ9kAOszZcDvdAHwwIKJG33Ykj43OKcWsnmcBRL09YTU4nOeHZ8Y2a7l1MgTd08SBe9A8Qj6A==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=18"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
     "node_modules/undici-types": {
       "version": "5.26.5",
       "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz",
@@ -4020,6 +4688,13 @@
         "node": ">= 0.8"
       }
     },
+    "node_modules/util-deprecate": {
+      "version": "1.0.2",
+      "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
+      "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/uuid": {
       "version": "8.3.2",
       "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
diff --git a/package.json b/package.json
index ba216c5..faa53aa 100644
--- a/package.json
+++ b/package.json
@@ -26,6 +26,10 @@
     }
   },
   "devDependencies": {
+    "@nestjs/common": "^11.1.27",
+    "@nestjs/core": "^11.1.27",
+    "@nestjs/platform-express": "^11.1.27",
+    "@nestjs/platform-fastify": "^11.1.27",
     "@types/autocannon": "^7.12.7",
     "@types/express": "^5.0.6",
     "@types/node": "^18.19.0",
@@ -34,6 +38,7 @@
     "express": "^5.2.1",
     "fastify": "^5.10.0",
     "graphql": "^16.9.0",
+    "rxjs": "^7.8.2",
     "tsx": "^4.23.0",
     "typescript": "^5.5.0",
     "vitest": "^2.0.0",

From 90359e3907ab22eb62ab924f5dce72c0c3adccf8 Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Mon, 6 Jul 2026 23:48:19 -0500
Subject: [PATCH 070/139] docs(bench): regenerate BENCHMARKS.md with NestJS
 (express + fastify) rows

Signed-off-by: Diego Resendez 
---
 BENCHMARKS.md      |  60 ++++++----
 bench/results.json | 284 +++++++++++++++++++++++++++++++--------------
 2 files changed, 231 insertions(+), 113 deletions(-)

diff --git a/BENCHMARKS.md b/BENCHMARKS.md
index 3133702..d5d02e4 100644
--- a/BENCHMARKS.md
+++ b/BENCHMARKS.md
@@ -5,7 +5,7 @@
 ## Environment
 
 - **Date**: 2026-07-07
-- **Commit**: daa13f6
+- **Commit**: fe1831a
 - **Node**: v22.22.2
 - **OS**: darwin
 - **CPU**: Apple M4 Max (16 cores)
@@ -29,56 +29,64 @@
 
 | Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
 | --- | --- | --- | --- | --- | --- | --- |
-| raw-http | 116,166 | 0.00 | 1.00 | 1.00 | 0.6% | 115,590–117,242 |
-| green-tea | 97,760 | 0.00 | 1.00 | 2.00 | 0.3% | 97,094–97,837 |
-| fastify | 86,470 | 1.00 | 2.00 | 2.00 | 0.3% | 86,202–86,829 |
-| express | 24,005 | 3.00 | 6.00 | 9.00 | 0.3% | 23,989–24,136 |
+| raw-http | 115,398 | 0.00 | 1.00 | 1.00 | 0.3% | 114,822–115,539 |
+| green-tea | 98,093 | 0.00 | 1.00 | 2.00 | 0.3% | 98,054–98,669 |
+| nestjs-fastify | 95,034 | 1.00 | 1.00 | 2.00 | 0.5% | 94,240–95,264 |
+| fastify | 86,765 | 1.00 | 2.00 | 2.00 | 0.3% | 86,496–87,123 |
+| express | 24,366 | 3.00 | 5.00 | 8.00 | 0.2% | 24,283–24,418 |
+| nestjs-express | 21,762 | 4.00 | 6.00 | 10.00 | 0.4% | 21,698–21,896 |
 
 ### Route param
 
 | Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
 | --- | --- | --- | --- | --- | --- | --- |
-| raw-http | 117,024 | 0.00 | 1.00 | 1.00 | 0.3% | 116,538–117,242 |
-| green-tea | 92,384 | 1.00 | 2.00 | 2.00 | 0.5% | 91,795–92,998 |
-| fastify | 85,754 | 1.00 | 2.00 | 2.00 | 0.3% | 85,651–86,317 |
-| express | 23,666 | 4.00 | 5.00 | 8.00 | 0.1% | 23,666–23,720 |
+| raw-http | 116,333 | 0.00 | 1.00 | 1.00 | 0.2% | 115,974–116,410 |
+| green-tea | 93,434 | 1.00 | 2.00 | 2.00 | 0.2% | 93,152–93,613 |
+| nestjs-fastify | 89,312 | 1.00 | 2.00 | 2.00 | 0.1% | 89,235–89,530 |
+| fastify | 86,278 | 1.00 | 2.00 | 2.00 | 0.3% | 86,138–86,765 |
+| express | 23,835 | 3.00 | 5.00 | 8.00 | 0.5% | 23,803–24,046 |
+| nestjs-express | 20,955 | 4.00 | 6.00 | 11.00 | 0.6% | 20,949–21,202 |
 
 ### Pipeline (3 steps) (approximation)
 
 | Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
 | --- | --- | --- | --- | --- | --- | --- |
-| raw-http | 114,157 | 0.00 | 1.00 | 1.00 | 0.2% | 113,862–114,554 |
-| fastify | 84,320 | 1.00 | 2.00 | 2.00 | 0.1% | 84,269–84,422 |
-| green-tea | 83,962 | 1.00 | 2.00 | 2.00 | 0.4% | 83,590–84,358 |
-| express | 23,829 | 4.00 | 5.00 | 8.00 | 0.1% | 23,768–23,851 |
+| raw-http | 113,491 | 0.00 | 1.00 | 1.00 | 0.8% | 112,531–114,810 |
+| nestjs-fastify | 87,328 | 1.00 | 2.00 | 2.00 | 0.4% | 86,867–87,661 |
+| fastify | 85,024 | 1.00 | 2.00 | 2.00 | 0.3% | 84,512–85,178 |
+| green-tea | 84,896 | 1.00 | 2.00 | 2.00 | 0.5% | 84,243–85,267 |
+| express | 23,950 | 3.00 | 5.00 | 8.00 | 0.2% | 23,902–24,011 |
+| nestjs-express | 20,824 | 4.00 | 6.00 | 11.00 | 0.1% | 20,805–20,878 |
 
 ### POST JSON + validation
 
 | Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
 | --- | --- | --- | --- | --- | --- | --- |
-| raw-http | 100,230 | 0.00 | 1.00 | 2.00 | 0.1% | 100,064–100,294 |
-| green-tea | 76,243 | 1.00 | 2.00 | 2.00 | 0.2% | 76,192–76,550 |
-| fastify | 63,222 | 1.00 | 2.00 | 3.00 | 0.7% | 62,307–63,229 |
-| express | 19,870 | 4.00 | 7.00 | 23.00 | 0.3% | 19,758–19,883 |
+| raw-http | 100,141 | 0.00 | 1.00 | 2.00 | 0.2% | 99,846–100,294 |
+| green-tea | 77,178 | 1.00 | 2.00 | 2.00 | 0.1% | 77,126–77,254 |
+| fastify | 63,722 | 1.00 | 2.00 | 3.00 | 0.1% | 63,574–63,760 |
+| nestjs-fastify | 59,146 | 1.00 | 3.00 | 3.00 | 0.3% | 59,005–59,376 |
+| express | 20,098 | 4.00 | 6.00 | 12.00 | 0.2% | 20,056–20,174 |
+| nestjs-express | 18,856 | 5.00 | 7.00 | 30.00 | 0.5% | 18,853–19,067 |
 
 ## Step-scaling (green-tea)
 
 | Path | Steps | req/s |
 | --- | --- | --- |
-| /steps/0 | 0 | 91,386 |
+| /steps/0 | 0 | 92,282 |
 | /steps/3 | 3 | 81,530 |
-| /steps/5 | 5 | 72,237 |
+| /steps/5 | 5 | 71,994 |
 
-Each additional pipeline step costs roughly 3,830 req/s (-21.0% over 5 steps), on this box.
+Each additional pipeline step costs roughly 4,058 req/s (-22.0% over 5 steps), on this box.
 
 ## Cost of secure-by-default (green-tea)
 
 | Label | req/s |
 | --- | --- |
-| security:false (parity) | 97,760 |
-| security:true (default) | 93,306 |
+| security:false (parity) | 98,093 |
+| security:true (default) | 92,998 |
 
-The real cost of running secure-by-default (rather than the parity-mode `security:false` used above) is ~4.6% req/s on this box.
+The real cost of running secure-by-default (rather than the parity-mode `security:false` used above) is ~5.2% req/s on this box.
 
 > Scope: this micro-bench currently measures the security-**headers** cost only (`security:false` vs
 > `security:true` on `/hello`). The incremental cost of `@body` validation and CORS is not separately
@@ -102,3 +110,9 @@ The real cost of running secure-by-default (rather than the parity-mode `securit
 - **Content-type charset asymmetry (disclosed, not controlled)**: green-tea and raw-http send
   `Content-Type: application/json` while Express and Fastify send `application/json; charset=utf-8`.
   This is a minor header-byte asymmetry that is disclosed here rather than normalized away.
+- **NestJS runs on an underlying adapter** (Express or Fastify): the `nestjs-express` / `nestjs-fastify`
+  rows measure Nest's DI / decorator / routing overhead **on top of** that adapter, so compare each
+  against its own base (`express` / `fastify`) rather than against the field. Nest's idiomatic
+  `ValidationPipe` / class-validator is **not** used — `/validate` performs the same manual field check
+  as every other server (parity). The same parity controls apply: `etag` and `x-powered-by` are disabled
+  on the underlying Express instance, and `keepAliveTimeout` is 5000 on both adapters.
diff --git a/bench/results.json b/bench/results.json
index df932d3..73d408c 100644
--- a/bench/results.json
+++ b/bench/results.json
@@ -1,7 +1,7 @@
 {
   "env": {
     "date": "2026-07-07",
-    "commit": "daa13f6",
+    "commit": "fe1831a",
     "node": "v22.22.2",
     "os": "darwin",
     "cpu": "Apple M4 Max (16 cores)",
@@ -23,11 +23,11 @@
         {
           "framework": "raw-http",
           "reqSec": {
-            "median": 116166.4,
-            "min": 115590.4,
-            "max": 117241.6,
-            "stddev": 684.2913999167365,
-            "cv": 0.005882187997853885
+            "median": 115398.4,
+            "min": 114822.4,
+            "max": 115539.2,
+            "stddev": 310.09010876768724,
+            "cv": 0.0026905088104554075
           },
           "p50": 0,
           "p99": 1,
@@ -36,11 +36,11 @@
         {
           "framework": "fastify",
           "reqSec": {
-            "median": 86470.4,
-            "min": 86201.6,
-            "max": 86828.8,
-            "stddev": 256.92278130900564,
-            "cv": 0.0029701964075911015
+            "median": 86764.8,
+            "min": 86496,
+            "max": 87123.2,
+            "stddev": 256.9227813090051,
+            "cv": 0.002960121758353106
           },
           "p50": 1,
           "p99": 2,
@@ -49,28 +49,54 @@
         {
           "framework": "express",
           "reqSec": {
-            "median": 24004.8,
-            "min": 23988.8,
-            "max": 24136,
-            "stddev": 65.9438144685816,
-            "cv": 0.002742722036525155
+            "median": 24366.4,
+            "min": 24283.2,
+            "max": 24417.6,
+            "stddev": 55.38455460585383,
+            "cv": 0.002273984274990166
           },
           "p50": 3,
-          "p99": 6,
-          "p999": 9
+          "p99": 5,
+          "p999": 8
         },
         {
           "framework": "green-tea",
           "reqSec": {
-            "median": 97760,
-            "min": 97094.4,
-            "max": 97836.8,
-            "stddev": 333.34655973759686,
-            "cv": 0.003416705658430423
+            "median": 98092.8,
+            "min": 98054.4,
+            "max": 98668.8,
+            "stddev": 281.0175795212842,
+            "cv": 0.002859589501804015
           },
           "p50": 0,
           "p99": 1,
           "p999": 2
+        },
+        {
+          "framework": "nestjs-express",
+          "reqSec": {
+            "median": 21761.6,
+            "min": 21697.6,
+            "max": 21896,
+            "stddev": 82.67870880032535,
+            "cv": 0.0037952010918943873
+          },
+          "p50": 4,
+          "p99": 6,
+          "p999": 10
+        },
+        {
+          "framework": "nestjs-fastify",
+          "reqSec": {
+            "median": 95033.6,
+            "min": 94240,
+            "max": 95264,
+            "stddev": 438.6166536839312,
+            "cv": 0.00462452048886261
+          },
+          "p50": 1,
+          "p99": 1,
+          "p999": 2
         }
       ]
     },
@@ -81,11 +107,11 @@
         {
           "framework": "raw-http",
           "reqSec": {
-            "median": 117024,
-            "min": 116537.6,
-            "max": 117241.6,
-            "stddev": 294.3072317607338,
-            "cv": 0.0025168575864821115
+            "median": 116332.8,
+            "min": 115974.4,
+            "max": 116409.6,
+            "stddev": 189.66281191162406,
+            "cv": 0.001631663389130871
           },
           "p50": 0,
           "p99": 1,
@@ -94,11 +120,11 @@
         {
           "framework": "fastify",
           "reqSec": {
-            "median": 85753.6,
-            "min": 85651.2,
-            "max": 86316.8,
-            "stddev": 292.6323746044982,
-            "cv": 0.0034063777495308683
+            "median": 86278.4,
+            "min": 86137.6,
+            "max": 86764.8,
+            "stddev": 268.69839349476365,
+            "cv": 0.003110165492522174
           },
           "p50": 1,
           "p99": 2,
@@ -107,24 +133,50 @@
         {
           "framework": "express",
           "reqSec": {
-            "median": 23665.6,
-            "min": 23665.6,
-            "max": 23720,
-            "stddev": 25.64440593103281,
-            "cv": 0.0010827856221020677
+            "median": 23835.2,
+            "min": 23803.2,
+            "max": 24046.4,
+            "stddev": 107.89690552662897,
+            "cv": 0.004515472130491916
           },
-          "p50": 4,
+          "p50": 3,
           "p99": 5,
           "p999": 8
         },
         {
           "framework": "green-tea",
           "reqSec": {
-            "median": 92384,
-            "min": 91795.2,
-            "max": 92998.4,
-            "stddev": 491.24140252584004,
-            "cv": 0.005316895043385614
+            "median": 93433.6,
+            "min": 93152,
+            "max": 93612.8,
+            "stddev": 189.6628119116206,
+            "cv": 0.002030662686635119
+          },
+          "p50": 1,
+          "p99": 2,
+          "p999": 2
+        },
+        {
+          "framework": "nestjs-express",
+          "reqSec": {
+            "median": 20955.2,
+            "min": 20948.8,
+            "max": 21201.6,
+            "stddev": 117.69157432317111,
+            "cv": 0.005594982425799189
+          },
+          "p50": 4,
+          "p99": 6,
+          "p999": 11
+        },
+        {
+          "framework": "nestjs-fastify",
+          "reqSec": {
+            "median": 89312,
+            "min": 89235.2,
+            "max": 89529.6,
+            "stddev": 124.68598780759793,
+            "cv": 0.001395338811201841
           },
           "p50": 1,
           "p99": 2,
@@ -140,11 +192,11 @@
         {
           "framework": "raw-http",
           "reqSec": {
-            "median": 114156.8,
-            "min": 113862.4,
-            "max": 114553.6,
-            "stddev": 283.21155029804993,
-            "cv": 0.0024801579427618002
+            "median": 113491.2,
+            "min": 112531.2,
+            "max": 114809.6,
+            "stddev": 933.9810324031724,
+            "cv": 0.008220892102882115
           },
           "p50": 0,
           "p99": 1,
@@ -153,11 +205,11 @@
         {
           "framework": "fastify",
           "reqSec": {
-            "median": 84320,
-            "min": 84268.8,
-            "max": 84422.4,
-            "stddev": 63.857619400938304,
-            "cv": 0.0007571714540811431
+            "median": 85024,
+            "min": 84512,
+            "max": 85177.6,
+            "stddev": 284.55819947576623,
+            "cv": 0.003351507726431956
           },
           "p50": 1,
           "p99": 2,
@@ -166,24 +218,50 @@
         {
           "framework": "express",
           "reqSec": {
-            "median": 23828.8,
-            "min": 23768,
-            "max": 23851.2,
-            "stddev": 35.151481713672865,
-            "cv": 0.001475960770644645
+            "median": 23950.4,
+            "min": 23902.4,
+            "max": 24011.2,
+            "stddev": 44.519758410046,
+            "cv": 0.0018585004345727763
           },
-          "p50": 4,
+          "p50": 3,
           "p99": 5,
           "p999": 8
         },
         {
           "framework": "green-tea",
           "reqSec": {
-            "median": 83961.6,
-            "min": 83590.4,
-            "max": 84358.4,
-            "stddev": 313.5927436802211,
-            "cv": 0.0037345747973909107
+            "median": 84896,
+            "min": 84243.2,
+            "max": 85267.2,
+            "stddev": 423.2825796347192,
+            "cv": 0.004991414284012342
+          },
+          "p50": 1,
+          "p99": 2,
+          "p999": 2
+        },
+        {
+          "framework": "nestjs-express",
+          "reqSec": {
+            "median": 20824,
+            "min": 20804.8,
+            "max": 20878.41,
+            "stddev": 31.17605954717337,
+            "cv": 0.001496278247605678
+          },
+          "p50": 4,
+          "p99": 6,
+          "p999": 11
+        },
+        {
+          "framework": "nestjs-fastify",
+          "reqSec": {
+            "median": 87328,
+            "min": 86867.2,
+            "max": 87660.8,
+            "stddev": 325.38753646827104,
+            "cv": 0.0037278603866430907
           },
           "p50": 1,
           "p99": 2,
@@ -198,11 +276,11 @@
         {
           "framework": "raw-http",
           "reqSec": {
-            "median": 100230.4,
-            "min": 100064,
+            "median": 100140.8,
+            "min": 99846.4,
             "max": 100294.4,
-            "stddev": 97.10768364152092,
-            "cv": 0.0009691746695970135
+            "stddev": 185.88177843875883,
+            "cv": 0.0018570746103533369
           },
           "p50": 0,
           "p99": 1,
@@ -211,11 +289,11 @@
         {
           "framework": "fastify",
           "reqSec": {
-            "median": 63222.4,
-            "min": 62307.2,
-            "max": 63228.8,
-            "stddev": 432.9457959401203,
-            "cv": 0.006880951458691962
+            "median": 63721.6,
+            "min": 63574.4,
+            "max": 63760,
+            "stddev": 79.99288857281053,
+            "cv": 0.0012560645345785087
           },
           "p50": 1,
           "p99": 2,
@@ -224,28 +302,54 @@
         {
           "framework": "express",
           "reqSec": {
-            "median": 19870.41,
-            "min": 19758.41,
-            "max": 19883.2,
-            "stddev": 56.05565508195131,
-            "cv": 0.0028257646983895677
+            "median": 20097.6,
+            "min": 20056,
+            "max": 20174.41,
+            "stddev": 49.04789518646266,
+            "cv": 0.0024390608203285337
           },
           "p50": 4,
-          "p99": 7,
-          "p999": 23
+          "p99": 6,
+          "p999": 12
         },
         {
           "framework": "green-tea",
           "reqSec": {
-            "median": 76243.2,
-            "min": 76192,
-            "max": 76550.4,
-            "stddev": 158.26975565645782,
-            "cv": 0.0020735333006502306
+            "median": 77177.61,
+            "min": 77126.4,
+            "max": 77254.4,
+            "stddev": 52.602458962379814,
+            "cv": 0.0006815013839797027
           },
           "p50": 1,
           "p99": 2,
           "p999": 2
+        },
+        {
+          "framework": "nestjs-express",
+          "reqSec": {
+            "median": 18856,
+            "min": 18852.8,
+            "max": 19067.2,
+            "stddev": 100.32338821143516,
+            "cv": 0.005301010367660728
+          },
+          "p50": 5,
+          "p99": 7,
+          "p999": 30
+        },
+        {
+          "framework": "nestjs-fastify",
+          "reqSec": {
+            "median": 59145.6,
+            "min": 59004.8,
+            "max": 59376,
+            "stddev": 153.00625985741647,
+            "cv": 0.002585636725423652
+          },
+          "p50": 1,
+          "p99": 3,
+          "p999": 3
         }
       ]
     }
@@ -254,7 +358,7 @@
     {
       "path": "/steps/0",
       "steps": 0,
-      "reqSec": 91385.6
+      "reqSec": 92281.6
     },
     {
       "path": "/steps/3",
@@ -264,17 +368,17 @@
     {
       "path": "/steps/5",
       "steps": 5,
-      "reqSec": 72236.8
+      "reqSec": 71993.61
     }
   ],
   "secureCost": [
     {
       "label": "security:false (parity)",
-      "reqSec": 97760
+      "reqSec": 98092.8
     },
     {
       "label": "security:true (default)",
-      "reqSec": 93305.6
+      "reqSec": 92998.4
     }
   ]
 }
\ No newline at end of file

From c0c6e7fa57a28e8af5babc1a3eacadf6f17daaec Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Tue, 7 Jul 2026 00:12:58 -0500
Subject: [PATCH 071/139] =?UTF-8?q?docs:=20sell=20the=20idea=20=E2=80=94?=
 =?UTF-8?q?=20README=20refresh=20(zen=20philosophy,=20shipped=20features,?=
 =?UTF-8?q?=20honest=20benchmark=20result)=20+=20CHANGELOG?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Reframe README around the graph-as-clarity philosophy; add 'what's different
and why', a batteries-included section for the beta features (TLS/CORS/security,
Standard Schema validation, uploads, graceful shutdown), and the honest
benchmark headline (fastest high-level framework in 3/4 scenarios). Bump status
alpha->beta, add CalVer versioning note, seed CHANGELOG.

Signed-off-by: Diego Resendez 
---
 CHANGELOG.md |  40 +++++++++++++++
 README.md    | 134 +++++++++++++++++++++++++++------------------------
 2 files changed, 111 insertions(+), 63 deletions(-)
 create mode 100644 CHANGELOG.md

diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..e4b63b3
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,40 @@
+# Changelog
+
+All notable changes to `@green-tea/core` are documented here.
+
+The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
+green-tea uses calendar versioning: `YY.MM.PATCH`.
+
+## [Unreleased]
+
+Beta on the road to a release candidate. No published release yet; the
+version below is a placeholder until the API freeze.
+
+### Added
+- **Transport security** — native TLS termination (https/wss), CORS with a
+  guarded preflight and credentials-safe origins, secure-by-default response
+  headers (nosniff, X-Frame-Options, Referrer-Policy, HSTS-when-secure), and
+  proxy-aware `trustProxy` exposing `ctx.protocol` / `ctx.ip`.
+- **Input validation** — `@body/@query/@param/@headers` accept any
+  [Standard Schema](https://standardschema.dev) (zod / valibot / arktype); the
+  parsed value is passed to the handler, invalid input returns `422` with
+  per-field issues. Core stays dependency-free.
+- **Body parsing** — JSON, `application/x-www-form-urlencoded`, and
+  `multipart/form-data` file uploads (`@body()` → `{ fields, files }`), with a
+  configurable repeated-field policy (`bodyDuplicates`, per-route overridable)
+  and a `maxParts` DoS bound.
+- **Streams** — SSE / ndjson / WebSocket duplex over a multicast
+  `AsyncIterable` channel, with backpressure and cleanup; `rooms` broadcast hubs.
+- **Graph introspection** — `app.explain(route)`, `app.graph()`,
+  `app.toMermaid()` / `toDOT()`, and an opt-in `GET /__graph__` dev endpoint.
+- **Operational hardening** — request body/size limits (`413`), request and
+  keep-alive timeouts, and `app.close()` graceful shutdown (drains in-flight
+  requests, closes live streams and mesh links).
+- **Testing ergonomics** — `createApp({ overrides })` swaps any provider/step
+  by token in one line.
+- **Mesh (walking skeleton)** — `teapot`/`teacup` distributed dependency
+  injection over a secret-gated WebSocket control channel. Experimental.
+- **Benchmarks** — reproducible `npm run bench` harness vs Express 5, Fastify 5,
+  NestJS, and raw `http`; results in [BENCHMARKS.md](./BENCHMARKS.md).
+
+[Unreleased]: https://git.svc.zoit.services/Green-Tea/core/commits/develop
diff --git a/README.md b/README.md
index 751a2d3..55cd59c 100644
--- a/README.md
+++ b/README.md
@@ -1,28 +1,55 @@
 # 🍵 green-tea
 
-> A declarative, type-safe HTTP framework for Node. The request pipeline is an explicit **dependency graph**, not a mutable middleware chain.
+> A calm, type-safe HTTP framework for Node. Your API is an explicit **dependency graph** you can see, slice, and trust — not a mutable bag threaded through positional middleware.
 
-`@green-tea/core` — **alpha**. Zero runtime dependencies beyond `reflect-metadata` (`ws` is an optional peer dep, only for WebSocket/mesh on Node).
+`@green-tea/core` — **beta**, RC-track. One runtime dependency: `reflect-metadata` (`ws` is an optional peer, only for WebSocket/mesh).
 
-## Documentation
+```bash
+npm install @green-tea/core reflect-metadata
+```
 
-- **[Quickstart](./docs/quickstart.md)** — install + concrete examples (routes/DI, `flow`, SSE, WebSocket, mesh, plugins).
-- **[Architecture](./docs/architecture.md)** — the mental map (layers, request lifecycle, mesh) as diagrams.
+---
 
-## Why
+## The idea
 
-Express/Fastify middleware is positional, untyped, and globally mutable: order depends on the line you wrote `app.use()` on, `req.user` may or may not exist, and a plugin can quietly delete your body parser. green-tea replaces that model:
+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.
 
-- **Declarative, not positional.** You declare what each step *needs* and *produces*. The graph order is computed at boot via topological sort — there is no "put this before that".
-- **The type is the contract.** What a handler reads from the context *is* its dependency declaration. The typed `flow` core makes a handler that reads `ctx.user` **fail to compile** if no step produces `user`.
-- **Structural plugin isolation.** Plugins get only `bus.on(...)` (observe) and `scope.add(...)` (extend their own scope). There is no API to reorder or delete another scope's steps.
-- **Response = return value.** No `Response.json()`. Return data; a `@Transformer` serializes it in a leave phase. Cut a request by `throw`ing a typed signal.
-- **Fail-fast boot.** A required provider that can't initialize (e.g. the DB) stops the server from serving — no 500s because a resource wasn't ready.
+green-tea puts the request on the page instead. You declare what each step **needs** and **produces**; the framework computes the order, type-checks the wiring, and can print the whole thing. A route runs only the steps its handler actually depends on. Boot fails loudly when a dependency is missing, so you never serve `undefined`.
+
+Less to hold in your head. That's the tea.
+
+## What's different — and why it matters
+
+- **The pipeline is a graph, not a chain.** You never write "put this before that." You declare `needs`/`provides` and green-tea topologically sorts it. *Why it matters:* no ordering bugs, no positional guesswork, and each route runs only its slice of the graph (an auth step doesn't run on public routes).
+- **The type is the contract.** What a handler reads from the context *is* its dependency list. In the typed `flow` core, a handler that reads `ctx.user` **fails to compile** if no step produces `user`. *Why it matters:* whole classes of "it was undefined in prod" disappear at compile time.
+- **You can see the request before it runs.** `app.explain('/users/:id')` prints the ordered chain with origins; `app.graph()` / `GET /__graph__` render it as a live diagram. *Why it matters:* onboarding, debugging, and audits are reading, not archaeology. (NestJS puts this behind a paid Devtools plan.)
+- **One primitive for real-time.** Return an `AsyncIterable` and the transport streams it — SSE, ndjson, or a WebSocket duplex — with backpressure and cleanup handled. *Why it matters:* no separate gateway, adapter, or library to bolt on.
+- **A remote dependency looks like a local one.** `@needs('billing')` resolves the same whether `billing` lives in this process or on another node (mesh, experimental). *Why it matters:* no gRPC layer or message-pattern DSL to learn — there's the graph, and some nodes happen to live elsewhere.
+- **Plugins can't sabotage you.** A plugin gets `bus.on(...)` (observe) and `scope.add(...)` (extend its own scope). There is no API to reorder or delete another scope's steps. *Why it matters:* installing a plugin can't break your body parser.
+
+## Batteries included — still one dependency
+
+Beta shipped the parts a real API needs, without growing the runtime dependency tree past `reflect-metadata`:
+
+- **TLS → https/wss** natively, plus proxy-aware `trustProxy` (`X-Forwarded-*` → `ctx.protocol`/`ctx.ip`).
+- **Secure by default.** `nosniff`, `X-Frame-Options`, `Referrer-Policy`, HSTS-when-secure — on every response, opt-out with one flag.
+- **CORS** with a guarded preflight and the credentials-never-`*` rule enforced for you.
+- **Validation via [Standard Schema](https://standardschema.dev).** `@body(schema)` accepts zod, valibot, or arktype — you bring the validator, the core stays zero-dep. Invalid input → `422` with per-field issues; the parsed value reaches your handler typed.
+- **Real body parsing.** JSON, urlencoded, and `multipart/form-data` file uploads (`@body()` → `{ fields, files }`), size-capped (`413`) against DoS.
+- **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.
+
+## Benchmarks
+
+We built a reproducible [autocannon harness](./BENCHMARKS.md) comparing green-tea to Express 5, Fastify 5, NestJS (on both Express and Fastify), and raw Node `http` — and we wrote it to be **hard on ourselves**, not flattering.
+
+On that harness, **green-tea handled more requests per second than every other framework in 3 of 4 scenarios** (JSON response, routing, and body-parsing-plus-validation), behind only raw `http` with no framework at all. In the fourth (a multi-step pipeline) it lands even with Fastify.
+
+Read the honest caveats in [BENCHMARKS.md](./BENCHMARKS.md): the numbers are single-box + loopback (absolute throughput is overstated and differences compressed — trust the *ratios*), the cross-framework table runs green-tea with `security:false` for header parity, and the real cost of secure-by-default is measured separately. Regenerate any time with `npm run bench`.
 
 ## How it compares
 
-Every framework here can serve `/users/:id`. The difference is what happens when the app
-grows: more dependencies, real-time, and more than one machine.
+Every framework here can serve `/users/:id`. The difference shows up as the app grows: more dependencies, real-time, and more than one machine.
 
 | | Express | Fastify | NestJS | expressive-tea | **green-tea** |
 |---|---|---|---|---|---|
@@ -30,7 +57,7 @@ grows: more dependencies, real-time, and more than one machine.
 | **Order is decided by** | the line you wrote it on | hook phase + registration order | module/provider wiring | boot-stage order | **what each step *needs/produces*** |
 | **`req.user` exists?** | hope so | hope so | if the guard ran | if the middleware ran | **boot fails if nothing provides it** |
 | **Type safety** | none | schemas (runtime) | decorator types (runtime DI) | runtime | **compile-time in `flow`** + boot-validated decorators |
-| **Response** | `res.send()` (mutate) | `reply.send()` | return value | return value | **return value → `@Transformer`** |
+| **See the pipeline** | read the code | read the code | paid Devtools | `inspect` | **`explain` / `graph` / `/__graph__` — free** |
 | **Real-time** | bolt on `ws`/`sse` libs | plugins | separate Gateway + adapter | separate engine | **return an `AsyncIterable`** — same primitive |
 | **Cross-service calls** | HTTP client / gRPC by hand | HTTP client / gRPC | Microservices transport + message patterns | — | **`@needs('x')` resolves on another node** |
 | **Plugin can break your pipeline?** | yes (deletes your body parser) | encapsulated, but hooks are global | interceptor order matters | yes | **no** — plugins only `bus.on` + `scope.add` |
@@ -38,31 +65,10 @@ grows: more dependencies, real-time, and more than one machine.
 
 ### Read it as a story
 
-- **Express / Fastify** — fast and battle-tested, but the request is a *mutable bag* threaded
-  through positional middleware. Order is implicit, `req.x` is a leap of faith, and a careless
-  plugin can delete another's work. You wire types and DI yourself.
-- **NestJS** — brings DI, decorators, and structure, but the DI is *runtime token resolution*,
-  it's a large opinionated dependency tree, and every new capability (WebSockets, gRPC,
-  microservices) is a **separate subsystem** with its own abstraction (Gateways, transports,
-  message patterns) to learn and glue.
-- **expressive-tea** — the sibling this project grew from: decorators + InversifyJS DI + boot
-  stages on top of Express. green-tea keeps the ideas, drops Express and Inversify, and makes
-  the graph — not the middleware chain — the core.
-- **green-tea** — one model answers three questions other stacks answer with three subsystems:
-  - *"what does this handler depend on?"* → the graph (boot-validated, `flow` checks it at compile time)
-  - *"how do I push data over time?"* → return an `AsyncIterable` (SSE / WebSocket, one primitive)
-  - *"how do I call another service?"* → `@needs` a token that lives on another node (mesh)
-
-  A remote dependency looks **identical** to a local one. There is no gRPC layer, no
-  message-pattern DSL, no separate WebSocket gateway — there is the graph, and some of its
-  nodes happen to live on another machine.
-
-### Honest scope
-
-green-tea is **alpha**. Express/Fastify have a decade of ecosystem; NestJS has enterprise
-tooling and a huge plugin catalog. Mesh discovery, load-balancing, and failover are not built
-yet (the [walking skeleton](./docs/quickstart.md#5-mesh--distributed-dependency-injection) is).
-Pick green-tea for the model, not the ecosystem — *yet*.
+- **Express / Fastify** — fast and battle-tested, but the request is a *mutable bag* threaded through positional middleware. Order is implicit, `req.x` is a leap of faith, and a careless plugin can delete another's work. You wire types and DI yourself.
+- **NestJS** — brings DI, decorators, and structure, but the DI is *runtime token resolution*, it ships a large opinionated dependency tree, and every new capability (WebSockets, gRPC, microservices) is a **separate subsystem** with its own abstraction to learn and glue.
+- **expressive-tea** — the sibling this project grew from: decorators + InversifyJS + boot stages on top of Express. green-tea keeps the ideas, drops Express and Inversify, and makes the graph — not the middleware chain — the core.
+- **green-tea** — one model answers three questions other stacks answer with three subsystems: *what does this handler depend on?* → the graph; *how do I push data over time?* → an `AsyncIterable`; *how do I call another service?* → `@needs` a token that lives on another node.
 
 ## Quick look
 
@@ -102,7 +108,7 @@ class UserController {
 class ApiModule {}
 
 const app = createApp({ modules: [ApiModule] });
-console.log(app.inspect('/api/users/:id'));  // auditable: ordered chain with origins
+console.log(app.explain('/api/users/:id'));  // auditable: the ordered chain, with origins
 app.listen(3000);
 ```
 
@@ -119,45 +125,47 @@ The handler signature declares exactly what it wants — in any order, nothing m
 |---|---|---|
 | `@needs('user')` | a graph-produced value (boot-validated) | `('key')` |
 | `@ctx()` | the whole accumulated context | `()` |
-| `@param(...)` | route params | `()` · `('id')` · `(['a','b'])` |
-| `@query(...)` | parsed query string | `()` · `('q')` · `(['a','b'])` |
-| `@body(...)` | parsed JSON body | `()` · `('field')` · `(['a','b'])` |
-| `@headers(...)` | request headers | `()` · `('authorization')` · `(['a','b'])` |
+| `@param(...)` | route params | `()` · `('id')` · `('id', schema)` |
+| `@query(...)` | parsed query string | `()` · `('q')` · `(['a','b'])` · `(schema)` |
+| `@body(...)` | parsed body (JSON / urlencoded / multipart) | `()` · `('field')` · `(schema)` |
+| `@headers(...)` | request headers | `()` · `('authorization')` · `(schema)` |
 
-`@needs` keys are validated at boot: if nothing provides the key, `createApp` throws with a clear error instead of serving `undefined`.
+`@needs` keys are validated at boot: nothing provides the key → `createApp` throws with a clear error instead of serving `undefined`. Pass a Standard Schema (`@body(User)`) and the value is validated, coerced, and typed before your handler sees it.
 
 ## Two layers
 
 1. **Typed functional core (`flow`)** — `flow().step(...).step(...).handle(...)`; step outputs accumulate into the context type (`Acc & Out`). This is where the compile-time guarantee lives.
 2. **Declarative decorator layer** — `@Provider/@Step/@Module/@Route/@Get/@Transformer` + argument decorators. Emits runtime metadata, builds and topologically sorts the graph, validates at boot.
 
-## Benchmarks
+## Honest scope
 
-Reproducible autocannon comparison vs Express 5, Fastify 5, and raw Node `http`
-lives in [BENCHMARKS.md](./BENCHMARKS.md) (regenerate with `npm run bench`).
+green-tea is **beta**, on the road to a release candidate. Express and Fastify have a decade of ecosystem; NestJS has enterprise tooling and a huge plugin catalog. green-tea's mesh is a walking skeleton — distributed DI works, but discovery, load-balancing, and failover are not built yet. Pick green-tea for the model and the ergonomics, not the ecosystem — *yet*.
 
-Numbers are single-box + loopback — absolute req/s is overstated and
-inter-framework differences are compressed; treat cross-framework *ratios* as
-the honest signal, not the raw throughput. The cross-framework table runs
-green-tea with `security:false` for header parity; the real cost of green-tea's
-secure-by-default headers/validation is measured separately in that file.
+## Docs & development
 
-## Development
+- **[Quickstart](./docs/quickstart.md)** — install + concrete examples (routes/DI, `flow`, validation, uploads, SSE, WebSocket, mesh, plugins).
+- **[Architecture](./docs/architecture.md)** — the mental map (layers, request lifecycle, mesh) as diagrams.
 
 ```bash
 npm install
-npm test          # vitest
-npm run typecheck # tsc --noEmit (includes the compile-time-guarantee type test)
-npm run build     # emit dist/
+npm test           # vitest
+npm run typecheck  # tsc --noEmit (includes the compile-time-guarantee type test)
+npm run build      # emit dist/
+npm run bench      # regenerate BENCHMARKS.md
 ```
 
 ## Roadmap
 
-- ✅ **streams** — SSE / ndjson / WebSocket duplex over a multicast `AsyncIterable` channel. Return an `AsyncIterable` and the transport streams it (backpressure + cleanup). See the [quickstart](./docs/quickstart.md#3-streaming--sse).
-- ✅ **mesh (walking skeleton)** — `teapot`/`teacup`: a consumer resolves a scope/step or proxies a route living on another node, over a secret-gated WS control channel, via one id-correlated RPC. Remote tokens become synthetic graph nodes. Model: a BEAM/OTP-style cluster, *not* microservices. See the [quickstart](./docs/quickstart.md#5-mesh--distributed-dependency-injection).
-- **mesh sub-specs (next)** — discovery/auto-registration, 2-way load-balancing, failover/health.
-- **runtime adapters** — factor the transport behind an adapter so the core stays runtime-agnostic; Node / Deno / Bun / edge become thin adapters over web-standard `Request`/`Response`. Only `src/http.ts` is runtime-specific today.
-- official plugins (cors, body parsers, auth) — structurally unable to sabotage the global pipeline.
+- ✅ **transport security** — native TLS/wss, CORS, secure-by-default headers, `trustProxy`.
+- ✅ **request I/O** — JSON / urlencoded / multipart uploads, size limits, graceful shutdown, Standard Schema validation.
+- ✅ **streams** — SSE / ndjson / WebSocket duplex over a multicast `AsyncIterable` channel, with backpressure and cleanup.
+- ✅ **graph introspection** — `explain` / `graph` / `toMermaid` / `GET /__graph__`.
+- ✅ **mesh (walking skeleton)** — `teapot`/`teacup` distributed DI over a secret-gated WS control channel. A BEAM/OTP-style cluster, *not* microservices.
+- **next** — API freeze + first published release, mesh sub-specs (discovery, load-balancing, failover), runtime adapters (Deno / Bun / edge over web-standard `Request`/`Response`), official plugins.
+
+## Versioning
+
+green-tea uses **calendar versioning**: `YY.MM.PATCH` (e.g. `26.07.0` = the first release cut in July 2026, patch 0). A version tells you *when* it shipped; breaking changes are called out in the [CHANGELOG](./CHANGELOG.md).
 
 ## License
 

From 0df82479ee33e71d34f5e23fba365f40db7144cf Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Tue, 7 Jul 2026 00:28:51 -0500
Subject: [PATCH 072/139] =?UTF-8?q?docs:=20push=20the=20real-time=20story?=
 =?UTF-8?q?=20=E2=80=94=20one=20AsyncIterable=20primitive,=20explained?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Add a dedicated section explaining that real-time is native (not a bolt-on
Gateway/adapter/plugin like other frameworks), and that the primitive is always
an AsyncIterable — you declare the mode (@Sse/@Ws/@Stream) and what changes is
direction and framing. Explains the difference between each iterable exposed
(outbound return vs @inbound, channel/rooms fan-out).

Signed-off-by: Diego Resendez 
---
 README.md | 44 +++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 43 insertions(+), 1 deletion(-)

diff --git a/README.md b/README.md
index 55cd59c..d7079d1 100644
--- a/README.md
+++ b/README.md
@@ -27,6 +27,48 @@ Less to hold in your head. That's the tea.
 - **A remote dependency looks like a local one.** `@needs('billing')` resolves the same whether `billing` lives in this process or on another node (mesh, experimental). *Why it matters:* no gRPC layer or message-pattern DSL to learn — there's the graph, and some nodes happen to live elsewhere.
 - **Plugins can't sabotage you.** A plugin gets `bus.on(...)` (observe) and `scope.add(...)` (extend its own scope). There is no API to reorder or delete another scope's steps. *Why it matters:* installing a plugin can't break your body parser.
 
+## Real-time is a primitive, not a second framework
+
+Most stacks treat "push data over time" as a bolt-on: Express reaches for a `ws` or SSE library, Fastify for a plugin, NestJS for a separate **WebSocket Gateway** with its own adapter and decorators. That's a second mental model, a second error surface, glued to your HTTP app.
+
+green-tea has one model: an **`AsyncIterable`**. A handler that returns a sequence of values over time *is* a stream — the same shape you'd return from any function. You **declare the mode** with a decorator; the framework handles framing, backpressure, cleanup, and disconnects.
+
+| Declare | Direction | Transport | Reach for it when |
+|---|---|---|---|
+| `@Sse` | server → client | `text/event-stream` | live updates to a browser (`EventSource`) |
+| `@Ws` | duplex | WebSocket | chat, collaboration — anything two-way |
+| `@Stream` | negotiated | SSE / ndjson / WS, picked from the client's `Accept` / `Upgrade` | one handler, the client chooses |
+| *(plain return)* | server → client | SSE or ndjson by `Accept` | programmatic streaming over `fetch` |
+
+The primitive never changes — it's always an `AsyncIterable`. What changes is **direction and framing**, and you declare which. That's the difference between each iterable green-tea hands you:
+
+- **`@Sse` / plain return** — you return **one** iterable: the *outbound* stream. Each `yield` becomes an SSE event, or an ndjson line.
+- **`@Ws` (duplex)** — **two** iterables. `@inbound()` gives you the client's *incoming* messages to consume; the one you **return** is the *outbound* stream to the client. `@abort()` hands you an `AbortSignal` for teardown.
+- **`@Stream`** — you write the handler once; the client's request decides whether it arrives as SSE, ndjson, or a WebSocket. No branching in your code.
+
+Fan-out is a primitive too: `channel()` is a **multicast** `AsyncIterable` (bounded, drop-oldest) so one source feeds many subscribers, and `rooms` are named broadcast hubs — publish once, every connection in the room receives it.
+
+```typescript
+@Route('/live')
+class Live {
+  @Sse('/prices')                                   // one iterable out — each yield is an event
+  prices() {
+    return (async function* () {
+      while (true) { yield { btc: await getPrice() }; await sleep(1000); }
+    })();
+  }
+
+  @Ws('/echo')                                      // duplex — consume @inbound, return the outbound stream
+  echo(@inbound() incoming: AsyncIterable) {
+    const out = channel();
+    (async () => { for await (const m of incoming) out.push(`echo: ${m}`); out.close(); })();
+    return out;
+  }
+}
+```
+
+Same `@Route`, same handler shape, same `AsyncIterable` — real-time is not a separate framework you also have to learn.
+
 ## Batteries included — still one dependency
 
 Beta shipped the parts a real API needs, without growing the runtime dependency tree past `reflect-metadata`:
@@ -58,7 +100,7 @@ Every framework here can serve `/users/:id`. The difference shows up as the app
 | **`req.user` exists?** | hope so | hope so | if the guard ran | if the middleware ran | **boot fails if nothing provides it** |
 | **Type safety** | none | schemas (runtime) | decorator types (runtime DI) | runtime | **compile-time in `flow`** + boot-validated decorators |
 | **See the pipeline** | read the code | read the code | paid Devtools | `inspect` | **`explain` / `graph` / `/__graph__` — free** |
-| **Real-time** | bolt on `ws`/`sse` libs | plugins | separate Gateway + adapter | separate engine | **return an `AsyncIterable`** — same 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** |
 | **Plugin can break your pipeline?** | yes (deletes your body parser) | encapsulated, but hooks are global | interceptor order matters | yes | **no** — plugins only `bus.on` + `scope.add` |
 | **Runtime deps** | minimal | minimal | heavy (rxjs, reflect-metadata, …) | Express + InversifyJS | **`reflect-metadata` only** (`ws` optional) |

From 3ca4c8680ebb9c784462fe7000211f17bdb1d9e5 Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Tue, 7 Jul 2026 11:59:42 -0500
Subject: [PATCH 073/139] chore(qa): add ESLint, Prettier, and a
 cognitive-complexity gate
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

The project shipped no linting or formatting; add both ahead of the first
npm publish. ESLint (flat config, typescript-eslint) + Prettier enforce a
consistent style, and a cognitive-complexity gate (ccts, threshold 25)
keeps any function from regressing into the unreadable.

Both run in CI and in a pre-commit hook (.githooks, enabled via
core.hooksPath + the `prepare` script). Cyclomatic complexity stays
advisory-only — its ??-chain false positives make it a poor gate.

Signed-off-by: Diego Resendez 
---
 .gitea/workflows/ci.yml      |  3 +++
 .githooks/pre-commit         | 17 +++++++++++++++
 .gitignore                   |  4 ++++
 .prettierrc.json             |  8 +++++++
 eslint.config.mjs            | 26 ++++++++++++++++++++++
 scripts/check-complexity.mjs | 42 ++++++++++++++++++++++++++++++++++++
 6 files changed, 100 insertions(+)
 create mode 100755 .githooks/pre-commit
 create mode 100644 .prettierrc.json
 create mode 100644 eslint.config.mjs
 create mode 100755 scripts/check-complexity.mjs

diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml
index ba0e6fd..6ce8237 100644
--- a/.gitea/workflows/ci.yml
+++ b/.gitea/workflows/ci.yml
@@ -13,6 +13,9 @@ jobs:
         with:
           node-version: '18'
       - run: npm ci
+      - run: npm run lint
+      - run: npm run format:check
+      - run: npm run complexity:check
       - run: npm run typecheck
       - run: npm test
       - run: npm run build
diff --git a/.githooks/pre-commit b/.githooks/pre-commit
new file mode 100755
index 0000000..cbeda7b
--- /dev/null
+++ b/.githooks/pre-commit
@@ -0,0 +1,17 @@
+#!/bin/sh
+# Pre-commit gate. Auto-fixes formatting/lint on staged source, then enforces
+# lint + cognitive-complexity. Enabled via `git config core.hooksPath .githooks`
+# (run automatically by the `prepare` npm script on install).
+set -e
+
+# Auto-fix format + lint on staged TypeScript sources, then re-stage them.
+staged=$(git diff --cached --name-only --diff-filter=ACM -- 'src/*.ts' 'src/**/*.ts')
+if [ -n "$staged" ]; then
+  echo "$staged" | xargs npx prettier --write
+  echo "$staged" | xargs npx eslint --fix
+  echo "$staged" | xargs git add
+fi
+
+# Enforce (no auto-fix): lint must be clean, and no function over the complexity gate.
+npm run lint
+npm run complexity:check
diff --git a/.gitignore b/.gitignore
index a64bd69..32206f8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -10,3 +10,7 @@ coverage/
 # Env
 .env
 .env.*
+
+# Astro (docs site)
+.astro/
+website/dist/
diff --git a/.prettierrc.json b/.prettierrc.json
new file mode 100644
index 0000000..f730360
--- /dev/null
+++ b/.prettierrc.json
@@ -0,0 +1,8 @@
+{
+  "printWidth": 120,
+  "tabWidth": 2,
+  "singleQuote": true,
+  "semi": true,
+  "trailingComma": "all",
+  "arrowParens": "always"
+}
diff --git a/eslint.config.mjs b/eslint.config.mjs
new file mode 100644
index 0000000..565e909
--- /dev/null
+++ b/eslint.config.mjs
@@ -0,0 +1,26 @@
+import js from '@eslint/js';
+import tseslint from 'typescript-eslint';
+import stylistic from '@stylistic/eslint-plugin';
+
+export default tseslint.config(
+  { ignores: ['dist', 'node_modules', 'bench', 'coverage'] },
+  js.configs.recommended,
+  ...tseslint.configs.recommended,
+  {
+    plugins: { '@stylistic': stylistic },
+    rules: {
+      // The request pipeline accumulates a dynamic context object by design;
+      // `any` there is load-bearing, not laziness. Flag it as a warning so new
+      // uses are visible without failing the build.
+      '@typescript-eslint/no-explicit-any': 'warn',
+      '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }],
+      // Breathing room around multi-line blocks (for/while/if/function/class) so
+      // consecutive blocks don't read as one wall of code. Auto-fixable.
+      '@stylistic/padding-line-between-statements': [
+        'error',
+        { blankLine: 'always', prev: 'multiline-block-like', next: '*' },
+        { blankLine: 'always', prev: '*', next: 'multiline-block-like' },
+      ],
+    },
+  },
+);
diff --git a/scripts/check-complexity.mjs b/scripts/check-complexity.mjs
new file mode 100755
index 0000000..e66958b
--- /dev/null
+++ b/scripts/check-complexity.mjs
@@ -0,0 +1,42 @@
+#!/usr/bin/env node
+// Cognitive-complexity gate. Fails (exit 1) if any named function in src/ exceeds
+// the threshold, per cognitive-complexity-ts. Cyclomatic complexity is intentionally
+// NOT gated here — its `??`-chain false positives make it advisory only (npm run complexity:cyclomatic).
+import { execSync } from 'node:child_process';
+
+const THRESHOLD = Number(process.env.COMPLEXITY_MAX ?? 25);
+
+let raw = '';
+try {
+  raw = execSync('npx ccts-json src', { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
+} catch (error) {
+  raw = error.stdout?.toString() ?? '';
+}
+
+if (!raw.trim()) {
+  console.error('check-complexity: no output from ccts-json');
+  process.exit(2);
+}
+
+const offenders = [];
+function walk(node) {
+  if (!node || typeof node !== 'object') return;
+  if (node.kind === 'function' && node.name && node.score > THRESHOLD) {
+    offenders.push({ score: node.score, name: node.name });
+  }
+  for (const [key, value] of Object.entries(node)) {
+    if (key === 'inner' && Array.isArray(value)) value.forEach(walk);
+    else if (value && typeof value === 'object') walk(value);
+  }
+}
+walk(JSON.parse(raw));
+
+if (offenders.length) {
+  offenders.sort((a, b) => b.score - a.score);
+  console.error(`\n✖ cognitive complexity: ${offenders.length} function(s) over ${THRESHOLD}\n`);
+  for (const o of offenders) console.error(`  ${String(o.score).padStart(4)}  ${o.name}`);
+  console.error('\nExtract helpers to bring them under the threshold (or raise COMPLEXITY_MAX).\n');
+  process.exit(1);
+}
+
+console.log(`✓ cognitive complexity: every function ≤ ${THRESHOLD}`);

From 9d79972f6254b833cd50a84ff768c87181df743f Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Tue, 7 Jul 2026 11:59:57 -0500
Subject: [PATCH 074/139] chore(release): dual ESM/CJS build via tsup; fix
 packaging; 26.07.0-beta.0

Packaging was broken for consumers: `main` resolved to a nonexistent
dist/index.js (tsc emitted dist/src/index.js), and the tarball shipped
tests, benches and sources. Build with tsup to emit CJS + ESM (+ types)
behind an `exports` map so `require` and `import` both resolve; a
createRequire banner keeps the lazy require('ws')/require('busboy') working
under ESM. Add the `files` allowlist and a `prepublishOnly` gate.

Bump to the first CalVer beta, published under the npm `beta` dist-tag.

Signed-off-by: Diego Resendez 
---
 package-lock.json  | 3045 ++++++++++++++++++++++++++++++++++++++++++++
 package.json       |   53 +-
 test/smoke.test.ts |    4 +-
 tsup.config.ts     |   22 +
 4 files changed, 3117 insertions(+), 7 deletions(-)
 create mode 100644 tsup.config.ts

diff --git a/package-lock.json b/package-lock.json
index 579edfa..a78fbe7 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -12,28 +12,41 @@
         "reflect-metadata": "0.2.2"
       },
       "devDependencies": {
+        "@eslint/js": "^9.39.4",
         "@nestjs/common": "^11.1.27",
         "@nestjs/core": "^11.1.27",
         "@nestjs/platform-express": "^11.1.27",
         "@nestjs/platform-fastify": "^11.1.27",
+        "@stylistic/eslint-plugin": "^5.10.0",
         "@types/autocannon": "^7.12.7",
+        "@types/busboy": "^1.5.4",
         "@types/express": "^5.0.6",
         "@types/node": "^18.19.0",
         "@types/ws": "^8.18.1",
         "autocannon": "^8.0.0",
+        "busboy": "^1.6.0",
+        "cognitive-complexity-ts": "^0.8.2",
+        "eslint": "^9.39.4",
         "express": "^5.2.1",
         "fastify": "^5.10.0",
         "graphql": "^16.9.0",
+        "prettier": "^3.9.4",
         "rxjs": "^7.8.2",
+        "tsup": "^8.5.1",
         "tsx": "^4.23.0",
         "typescript": "^5.5.0",
+        "typescript-eslint": "^8.63.0",
         "vitest": "^2.0.0",
         "ws": "^8.21.0"
       },
       "peerDependencies": {
+        "busboy": "^1.6.0",
         "ws": "^8.18.0"
       },
       "peerDependenciesMeta": {
+        "busboy": {
+          "optional": true
+        },
         "ws": {
           "optional": true
         }
@@ -510,6 +523,174 @@
         "node": ">=12"
       }
     },
+    "node_modules/@eslint-community/eslint-utils": {
+      "version": "4.9.1",
+      "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz",
+      "integrity": "sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "eslint-visitor-keys": "^3.4.3"
+      },
+      "engines": {
+        "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
+      },
+      "funding": {
+        "url": "https://opencollective.com/eslint"
+      },
+      "peerDependencies": {
+        "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0"
+      }
+    },
+    "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": {
+      "version": "3.4.3",
+      "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz",
+      "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==",
+      "dev": true,
+      "license": "Apache-2.0",
+      "engines": {
+        "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
+      },
+      "funding": {
+        "url": "https://opencollective.com/eslint"
+      }
+    },
+    "node_modules/@eslint-community/regexpp": {
+      "version": "4.12.2",
+      "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz",
+      "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": "^12.0.0 || ^14.0.0 || >=16.0.0"
+      }
+    },
+    "node_modules/@eslint/config-array": {
+      "version": "0.21.2",
+      "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.21.2.tgz",
+      "integrity": "sha512-nJl2KGTlrf9GjLimgIru+V/mzgSK0ABCDQRvxw5BjURL7WfH5uoWmizbH7QB6MmnMBd8cIC9uceWnezL1VZWWw==",
+      "dev": true,
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@eslint/object-schema": "^2.1.7",
+        "debug": "^4.3.1",
+        "minimatch": "^3.1.5"
+      },
+      "engines": {
+        "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+      }
+    },
+    "node_modules/@eslint/config-helpers": {
+      "version": "0.4.2",
+      "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.4.2.tgz",
+      "integrity": "sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==",
+      "dev": true,
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@eslint/core": "^0.17.0"
+      },
+      "engines": {
+        "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+      }
+    },
+    "node_modules/@eslint/core": {
+      "version": "0.17.0",
+      "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.17.0.tgz",
+      "integrity": "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==",
+      "dev": true,
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@types/json-schema": "^7.0.15"
+      },
+      "engines": {
+        "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+      }
+    },
+    "node_modules/@eslint/eslintrc": {
+      "version": "3.3.5",
+      "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.5.tgz",
+      "integrity": "sha512-4IlJx0X0qftVsN5E+/vGujTRIFtwuLbNsVUe7TO6zYPDR1O6nFwvwhIKEKSrl6dZchmYBITazxKoUYOjdtjlRg==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "ajv": "^6.14.0",
+        "debug": "^4.3.2",
+        "espree": "^10.0.1",
+        "globals": "^14.0.0",
+        "ignore": "^5.2.0",
+        "import-fresh": "^3.2.1",
+        "js-yaml": "^4.1.1",
+        "minimatch": "^3.1.5",
+        "strip-json-comments": "^3.1.1"
+      },
+      "engines": {
+        "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+      },
+      "funding": {
+        "url": "https://opencollective.com/eslint"
+      }
+    },
+    "node_modules/@eslint/eslintrc/node_modules/ajv": {
+      "version": "6.15.0",
+      "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz",
+      "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "fast-deep-equal": "^3.1.1",
+        "fast-json-stable-stringify": "^2.0.0",
+        "json-schema-traverse": "^0.4.1",
+        "uri-js": "^4.2.2"
+      },
+      "funding": {
+        "type": "github",
+        "url": "https://github.com/sponsors/epoberezkin"
+      }
+    },
+    "node_modules/@eslint/eslintrc/node_modules/json-schema-traverse": {
+      "version": "0.4.1",
+      "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
+      "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/@eslint/js": {
+      "version": "9.39.4",
+      "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.39.4.tgz",
+      "integrity": "sha512-nE7DEIchvtiFTwBw4Lfbu59PG+kCofhjsKaCWzxTpt4lfRjRMqG6uMBzKXuEcyXhOHoUp9riAm7/aWYGhXZ9cw==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+      },
+      "funding": {
+        "url": "https://eslint.org/donate"
+      }
+    },
+    "node_modules/@eslint/object-schema": {
+      "version": "2.1.7",
+      "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.7.tgz",
+      "integrity": "sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==",
+      "dev": true,
+      "license": "Apache-2.0",
+      "engines": {
+        "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+      }
+    },
+    "node_modules/@eslint/plugin-kit": {
+      "version": "0.4.1",
+      "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.4.1.tgz",
+      "integrity": "sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==",
+      "dev": true,
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@eslint/core": "^0.17.0",
+        "levn": "^0.4.1"
+      },
+      "engines": {
+        "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+      }
+    },
     "node_modules/@fastify/ajv-compiler": {
       "version": "4.0.5",
       "resolved": "https://registry.npmjs.org/@fastify/ajv-compiler/-/ajv-compiler-4.0.5.tgz",
@@ -703,6 +884,165 @@
         "ipaddr.js": "^2.1.0"
       }
     },
+    "node_modules/@humanfs/core": {
+      "version": "0.19.2",
+      "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz",
+      "integrity": "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==",
+      "dev": true,
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@humanfs/types": "^0.15.0"
+      },
+      "engines": {
+        "node": ">=18.18.0"
+      }
+    },
+    "node_modules/@humanfs/node": {
+      "version": "0.16.8",
+      "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.8.tgz",
+      "integrity": "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==",
+      "dev": true,
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@humanfs/core": "^0.19.2",
+        "@humanfs/types": "^0.15.0",
+        "@humanwhocodes/retry": "^0.4.0"
+      },
+      "engines": {
+        "node": ">=18.18.0"
+      }
+    },
+    "node_modules/@humanfs/types": {
+      "version": "0.15.0",
+      "resolved": "https://registry.npmjs.org/@humanfs/types/-/types-0.15.0.tgz",
+      "integrity": "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==",
+      "dev": true,
+      "license": "Apache-2.0",
+      "engines": {
+        "node": ">=18.18.0"
+      }
+    },
+    "node_modules/@humanwhocodes/module-importer": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz",
+      "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==",
+      "dev": true,
+      "license": "Apache-2.0",
+      "engines": {
+        "node": ">=12.22"
+      },
+      "funding": {
+        "type": "github",
+        "url": "https://github.com/sponsors/nzakas"
+      }
+    },
+    "node_modules/@humanwhocodes/retry": {
+      "version": "0.4.3",
+      "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz",
+      "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==",
+      "dev": true,
+      "license": "Apache-2.0",
+      "engines": {
+        "node": ">=18.18"
+      },
+      "funding": {
+        "type": "github",
+        "url": "https://github.com/sponsors/nzakas"
+      }
+    },
+    "node_modules/@isaacs/cliui": {
+      "version": "8.0.2",
+      "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz",
+      "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==",
+      "dev": true,
+      "license": "ISC",
+      "dependencies": {
+        "string-width": "^5.1.2",
+        "string-width-cjs": "npm:string-width@^4.2.0",
+        "strip-ansi": "^7.0.1",
+        "strip-ansi-cjs": "npm:strip-ansi@^6.0.1",
+        "wrap-ansi": "^8.1.0",
+        "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0"
+      },
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@isaacs/cliui/node_modules/ansi-regex": {
+      "version": "6.2.2",
+      "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz",
+      "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=12"
+      },
+      "funding": {
+        "url": "https://github.com/chalk/ansi-regex?sponsor=1"
+      }
+    },
+    "node_modules/@isaacs/cliui/node_modules/emoji-regex": {
+      "version": "9.2.2",
+      "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
+      "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/@isaacs/cliui/node_modules/string-width": {
+      "version": "5.1.2",
+      "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz",
+      "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "eastasianwidth": "^0.2.0",
+        "emoji-regex": "^9.2.2",
+        "strip-ansi": "^7.0.1"
+      },
+      "engines": {
+        "node": ">=12"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
+    "node_modules/@isaacs/cliui/node_modules/strip-ansi": {
+      "version": "7.2.0",
+      "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz",
+      "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "ansi-regex": "^6.2.2"
+      },
+      "engines": {
+        "node": ">=12"
+      },
+      "funding": {
+        "url": "https://github.com/chalk/strip-ansi?sponsor=1"
+      }
+    },
+    "node_modules/@jridgewell/gen-mapping": {
+      "version": "0.3.13",
+      "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
+      "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@jridgewell/sourcemap-codec": "^1.5.0",
+        "@jridgewell/trace-mapping": "^0.3.24"
+      }
+    },
+    "node_modules/@jridgewell/resolve-uri": {
+      "version": "3.1.2",
+      "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
+      "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=6.0.0"
+      }
+    },
     "node_modules/@jridgewell/sourcemap-codec": {
       "version": "1.5.5",
       "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
@@ -710,6 +1050,17 @@
       "dev": true,
       "license": "MIT"
     },
+    "node_modules/@jridgewell/trace-mapping": {
+      "version": "0.3.31",
+      "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
+      "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@jridgewell/resolve-uri": "^3.1.0",
+        "@jridgewell/sourcemap-codec": "^1.4.14"
+      }
+    },
     "node_modules/@lukeed/csprng": {
       "version": "1.1.0",
       "resolved": "https://registry.npmjs.org/@lukeed/csprng/-/csprng-1.1.0.tgz",
@@ -920,6 +1271,13 @@
         "toad-cache": "^3.7.0"
       }
     },
+    "node_modules/@one-ini/wasm": {
+      "version": "0.1.1",
+      "resolved": "https://registry.npmjs.org/@one-ini/wasm/-/wasm-0.1.1.tgz",
+      "integrity": "sha512-XuySG1E38YScSJoMlqovLru4KTUNSjgVTIjyh7qMX6aNN5HY5Ct5LhRJdxO79JtTzKfzV/bnWpz+zquYrISsvw==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/@pinojs/redact": {
       "version": "0.4.0",
       "resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz",
@@ -927,6 +1285,17 @@
       "dev": true,
       "license": "MIT"
     },
+    "node_modules/@pkgjs/parseargs": {
+      "version": "0.11.0",
+      "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz",
+      "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==",
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "engines": {
+        "node": ">=14"
+      }
+    },
     "node_modules/@rollup/rollup-android-arm-eabi": {
       "version": "4.62.2",
       "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.62.2.tgz",
@@ -1277,6 +1646,27 @@
         "win32"
       ]
     },
+    "node_modules/@stylistic/eslint-plugin": {
+      "version": "5.10.0",
+      "resolved": "https://registry.npmjs.org/@stylistic/eslint-plugin/-/eslint-plugin-5.10.0.tgz",
+      "integrity": "sha512-nPK52ZHvot8Ju/0A4ucSX1dcPV2/1clx0kLcH5wDmrE4naKso7TUC/voUyU1O9OTKTrR6MYip6LP0ogEMQ9jPQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@eslint-community/eslint-utils": "^4.9.1",
+        "@typescript-eslint/types": "^8.56.0",
+        "eslint-visitor-keys": "^4.2.1",
+        "espree": "^10.4.0",
+        "estraverse": "^5.3.0",
+        "picomatch": "^4.0.3"
+      },
+      "engines": {
+        "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+      },
+      "peerDependencies": {
+        "eslint": "^9.0.0 || ^10.0.0"
+      }
+    },
     "node_modules/@tokenizer/inflate": {
       "version": "0.4.1",
       "resolved": "https://registry.npmjs.org/@tokenizer/inflate/-/inflate-0.4.1.tgz",
@@ -1323,6 +1713,16 @@
         "@types/node": "*"
       }
     },
+    "node_modules/@types/busboy": {
+      "version": "1.5.4",
+      "resolved": "https://registry.npmjs.org/@types/busboy/-/busboy-1.5.4.tgz",
+      "integrity": "sha512-kG7WrUuAKK0NoyxfQHsVE6j1m01s6kMma64E+OZenQABMQyTJop1DumUWcLwAQ2JzpefU7PDYoRDKl8uZosFjw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@types/node": "*"
+      }
+    },
     "node_modules/@types/connect": {
       "version": "3.4.38",
       "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz",
@@ -1372,6 +1772,13 @@
       "dev": true,
       "license": "MIT"
     },
+    "node_modules/@types/json-schema": {
+      "version": "7.0.15",
+      "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
+      "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/@types/node": {
       "version": "18.19.130",
       "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.130.tgz",
@@ -1427,6 +1834,288 @@
         "@types/node": "*"
       }
     },
+    "node_modules/@typescript-eslint/eslint-plugin": {
+      "version": "8.63.0",
+      "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.63.0.tgz",
+      "integrity": "sha512-rvwSgqT+DHpWdzfSzPatRLm02a0GlESt++9iy3hLCDY4BgkaLcl8LBi9Yh7XGFBpwcBE/K3024QuXWTpbz4FfQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@eslint-community/regexpp": "^4.12.2",
+        "@typescript-eslint/scope-manager": "8.63.0",
+        "@typescript-eslint/type-utils": "8.63.0",
+        "@typescript-eslint/utils": "8.63.0",
+        "@typescript-eslint/visitor-keys": "8.63.0",
+        "ignore": "^7.0.5",
+        "natural-compare": "^1.4.0",
+        "ts-api-utils": "^2.5.0"
+      },
+      "engines": {
+        "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/typescript-eslint"
+      },
+      "peerDependencies": {
+        "@typescript-eslint/parser": "^8.63.0",
+        "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",
+        "typescript": ">=4.8.4 <6.1.0"
+      }
+    },
+    "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": {
+      "version": "7.0.5",
+      "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz",
+      "integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 4"
+      }
+    },
+    "node_modules/@typescript-eslint/parser": {
+      "version": "8.63.0",
+      "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.63.0.tgz",
+      "integrity": "sha512-gwh4gvvlaVDKKxyfxMG+Gnu1u9X0OQBwyGLkbwB65dIzBKnxeRiJlNFqlI3zwVhNXJIs6qV7mlFCn/BIajlVig==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@typescript-eslint/scope-manager": "8.63.0",
+        "@typescript-eslint/types": "8.63.0",
+        "@typescript-eslint/typescript-estree": "8.63.0",
+        "@typescript-eslint/visitor-keys": "8.63.0",
+        "debug": "^4.4.3"
+      },
+      "engines": {
+        "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/typescript-eslint"
+      },
+      "peerDependencies": {
+        "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",
+        "typescript": ">=4.8.4 <6.1.0"
+      }
+    },
+    "node_modules/@typescript-eslint/project-service": {
+      "version": "8.63.0",
+      "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.63.0.tgz",
+      "integrity": "sha512-e5dh0/UI0ok53AlZ5wRkXCB32z/f2jUZqPR/ygAw5WYaSw8j9EoJWlS7wQjr/dmOaqWjnPIn2m+HhVPCMWGZVQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@typescript-eslint/tsconfig-utils": "^8.63.0",
+        "@typescript-eslint/types": "^8.63.0",
+        "debug": "^4.4.3"
+      },
+      "engines": {
+        "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/typescript-eslint"
+      },
+      "peerDependencies": {
+        "typescript": ">=4.8.4 <6.1.0"
+      }
+    },
+    "node_modules/@typescript-eslint/scope-manager": {
+      "version": "8.63.0",
+      "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.63.0.tgz",
+      "integrity": "sha512-uUyfMWCnDSN8bCpcrY8nGP2BLkQ9Xn0GsipcONcpIDWhwhO4ZSyHvyS14U3X75mzxWxL3I2UZIrenTzdzcJO8A==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@typescript-eslint/types": "8.63.0",
+        "@typescript-eslint/visitor-keys": "8.63.0"
+      },
+      "engines": {
+        "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/typescript-eslint"
+      }
+    },
+    "node_modules/@typescript-eslint/tsconfig-utils": {
+      "version": "8.63.0",
+      "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.63.0.tgz",
+      "integrity": "sha512-sUAbkulqBAsncKnbRP3+7CtQFRKicexnj7ZwNC6ddCR7EmrXvjvdCYMJbUIqMd6lwoEriZjwLo08aS5tSjVMHg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/typescript-eslint"
+      },
+      "peerDependencies": {
+        "typescript": ">=4.8.4 <6.1.0"
+      }
+    },
+    "node_modules/@typescript-eslint/type-utils": {
+      "version": "8.63.0",
+      "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.63.0.tgz",
+      "integrity": "sha512-Nzzh/OGxVCOjObjaj1CQF2RUasyYy2Jfuh+zZ3PjLzG2fYRriAiZLib9UKtO+CpQAS3YHiAS+ckZDclwqI1TPA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@typescript-eslint/types": "8.63.0",
+        "@typescript-eslint/typescript-estree": "8.63.0",
+        "@typescript-eslint/utils": "8.63.0",
+        "debug": "^4.4.3",
+        "ts-api-utils": "^2.5.0"
+      },
+      "engines": {
+        "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/typescript-eslint"
+      },
+      "peerDependencies": {
+        "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",
+        "typescript": ">=4.8.4 <6.1.0"
+      }
+    },
+    "node_modules/@typescript-eslint/types": {
+      "version": "8.63.0",
+      "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.63.0.tgz",
+      "integrity": "sha512-xyLtl9DUBBFrcJS4x2pIqGLH68/tC2uOa4Z7pUteW09D3bXnnXUom4dyPikzWgB7llmIc1zoeI3aoUdC4rPK/Q==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/typescript-eslint"
+      }
+    },
+    "node_modules/@typescript-eslint/typescript-estree": {
+      "version": "8.63.0",
+      "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.63.0.tgz",
+      "integrity": "sha512-ygBkU+B7ex5UI/gKhaqexWev79uISfIv7XQCRNYO/jmD8rGLPyWLAb3KMRT6nd8Gt9bmUBi9+iX6tBdYfOY81Q==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@typescript-eslint/project-service": "8.63.0",
+        "@typescript-eslint/tsconfig-utils": "8.63.0",
+        "@typescript-eslint/types": "8.63.0",
+        "@typescript-eslint/visitor-keys": "8.63.0",
+        "debug": "^4.4.3",
+        "minimatch": "^10.2.2",
+        "semver": "^7.7.3",
+        "tinyglobby": "^0.2.15",
+        "ts-api-utils": "^2.5.0"
+      },
+      "engines": {
+        "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/typescript-eslint"
+      },
+      "peerDependencies": {
+        "typescript": ">=4.8.4 <6.1.0"
+      }
+    },
+    "node_modules/@typescript-eslint/typescript-estree/node_modules/balanced-match": {
+      "version": "4.0.4",
+      "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
+      "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": "18 || 20 || >=22"
+      }
+    },
+    "node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": {
+      "version": "5.0.7",
+      "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.7.tgz",
+      "integrity": "sha512-7oFy703dxfY3/NLxC1fh2SUCQ0H9rmAY+5EpDVfXjUTTs+HEwR2nYaqLv+GWcTsumwxPfiz6CzCNkwXwBUwqCA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "balanced-match": "^4.0.2"
+      },
+      "engines": {
+        "node": "18 || 20 || >=22"
+      }
+    },
+    "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": {
+      "version": "10.2.5",
+      "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz",
+      "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==",
+      "dev": true,
+      "license": "BlueOak-1.0.0",
+      "dependencies": {
+        "brace-expansion": "^5.0.5"
+      },
+      "engines": {
+        "node": "18 || 20 || >=22"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/isaacs"
+      }
+    },
+    "node_modules/@typescript-eslint/utils": {
+      "version": "8.63.0",
+      "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.63.0.tgz",
+      "integrity": "sha512-fUKaeAvrTuQg/Tgt3nliAUSZHJM6DlCcfyEmxCvlX8kieWSStBX+5O5Fnidtc3i2JrH+9c/GL4RY2iasd/GPTA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@eslint-community/eslint-utils": "^4.9.1",
+        "@typescript-eslint/scope-manager": "8.63.0",
+        "@typescript-eslint/types": "8.63.0",
+        "@typescript-eslint/typescript-estree": "8.63.0"
+      },
+      "engines": {
+        "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/typescript-eslint"
+      },
+      "peerDependencies": {
+        "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",
+        "typescript": ">=4.8.4 <6.1.0"
+      }
+    },
+    "node_modules/@typescript-eslint/visitor-keys": {
+      "version": "8.63.0",
+      "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.63.0.tgz",
+      "integrity": "sha512-UexrHGnGTpbuQHct2ExOc2ZcFbGUS9FOesCxxqdBGcpI1BxYu/LZ6U8Aq6/72XtF/qRBk9nhuGHFJIXXMhPMdw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@typescript-eslint/types": "8.63.0",
+        "eslint-visitor-keys": "^5.0.0"
+      },
+      "engines": {
+        "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/typescript-eslint"
+      }
+    },
+    "node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": {
+      "version": "5.0.1",
+      "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz",
+      "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==",
+      "dev": true,
+      "license": "Apache-2.0",
+      "engines": {
+        "node": "^20.19.0 || ^22.13.0 || >=24"
+      },
+      "funding": {
+        "url": "https://opencollective.com/eslint"
+      }
+    },
     "node_modules/@vitest/expect": {
       "version": "2.1.9",
       "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-2.1.9.tgz",
@@ -1540,6 +2229,16 @@
         "url": "https://opencollective.com/vitest"
       }
     },
+    "node_modules/abbrev": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-2.0.0.tgz",
+      "integrity": "sha512-6/mh1E2u2YgEsCHdY0Yx5oW+61gZU+1vXaoiHHrpKeuRNNgFvS+/jrwHiQhB5apAf5oB7UB7E19ol2R2LKH8hQ==",
+      "dev": true,
+      "license": "ISC",
+      "engines": {
+        "node": "^14.17.0 || ^16.13.0 || >=18.0.0"
+      }
+    },
     "node_modules/abstract-logging": {
       "version": "2.0.1",
       "resolved": "https://registry.npmjs.org/abstract-logging/-/abstract-logging-2.0.1.tgz",
@@ -1561,6 +2260,29 @@
         "node": ">= 0.6"
       }
     },
+    "node_modules/acorn": {
+      "version": "8.17.0",
+      "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.17.0.tgz",
+      "integrity": "sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg==",
+      "dev": true,
+      "license": "MIT",
+      "bin": {
+        "acorn": "bin/acorn"
+      },
+      "engines": {
+        "node": ">=0.4.0"
+      }
+    },
+    "node_modules/acorn-jsx": {
+      "version": "5.3.2",
+      "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz",
+      "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==",
+      "dev": true,
+      "license": "MIT",
+      "peerDependencies": {
+        "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
+      }
+    },
     "node_modules/ajv": {
       "version": "8.20.0",
       "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
@@ -1622,6 +2344,13 @@
         "url": "https://github.com/chalk/ansi-styles?sponsor=1"
       }
     },
+    "node_modules/any-promise": {
+      "version": "1.3.0",
+      "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz",
+      "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/append-field": {
       "version": "1.0.0",
       "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz",
@@ -1629,6 +2358,13 @@
       "dev": true,
       "license": "MIT"
     },
+    "node_modules/argparse": {
+      "version": "2.0.1",
+      "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
+      "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",
+      "dev": true,
+      "license": "Python-2.0"
+    },
     "node_modules/assertion-error": {
       "version": "2.0.1",
       "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
@@ -1712,6 +2448,13 @@
         "fastq": "^1.17.1"
       }
     },
+    "node_modules/balanced-match": {
+      "version": "1.0.2",
+      "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
+      "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/base64-js": {
       "version": "1.5.1",
       "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
@@ -1772,6 +2515,17 @@
         "url": "https://opencollective.com/express"
       }
     },
+    "node_modules/brace-expansion": {
+      "version": "1.1.15",
+      "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.15.tgz",
+      "integrity": "sha512-EwOCDEex4quD37XhqM3omwtMoJjr//isUZz1JopUNWms+4Z2ViyM/k1YIRePpoVNnQhENnxtFjLaxNHrT7xIUg==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "balanced-match": "^1.0.0",
+        "concat-map": "0.0.1"
+      }
+    },
     "node_modules/buffer": {
       "version": "5.7.1",
       "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",
@@ -1804,6 +2558,38 @@
       "dev": true,
       "license": "MIT"
     },
+    "node_modules/bundle-name": {
+      "version": "4.1.0",
+      "resolved": "https://registry.npmjs.org/bundle-name/-/bundle-name-4.1.0.tgz",
+      "integrity": "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "run-applescript": "^7.0.0"
+      },
+      "engines": {
+        "node": ">=18"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
+    "node_modules/bundle-require": {
+      "version": "5.1.0",
+      "resolved": "https://registry.npmjs.org/bundle-require/-/bundle-require-5.1.0.tgz",
+      "integrity": "sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "load-tsconfig": "^0.2.3"
+      },
+      "engines": {
+        "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
+      },
+      "peerDependencies": {
+        "esbuild": ">=0.18"
+      }
+    },
     "node_modules/busboy": {
       "version": "1.6.0",
       "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
@@ -1867,6 +2653,16 @@
         "url": "https://github.com/sponsors/ljharb"
       }
     },
+    "node_modules/callsites": {
+      "version": "3.1.0",
+      "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",
+      "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=6"
+      }
+    },
     "node_modules/chai": {
       "version": "5.3.3",
       "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz",
@@ -1918,6 +2714,22 @@
         "node": ">= 16"
       }
     },
+    "node_modules/chokidar": {
+      "version": "4.0.3",
+      "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz",
+      "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "readdirp": "^4.0.1"
+      },
+      "engines": {
+        "node": ">= 14.16.0"
+      },
+      "funding": {
+        "url": "https://paulmillr.com/funding/"
+      }
+    },
     "node_modules/cli-table3": {
       "version": "0.6.5",
       "resolved": "https://registry.npmjs.org/cli-table3/-/cli-table3-0.6.5.tgz",
@@ -1934,6 +2746,28 @@
         "@colors/colors": "1.5.0"
       }
     },
+    "node_modules/cognitive-complexity-ts": {
+      "version": "0.8.2",
+      "resolved": "https://registry.npmjs.org/cognitive-complexity-ts/-/cognitive-complexity-ts-0.8.2.tgz",
+      "integrity": "sha512-2ituXHQsA4PjFI3ySEgrzc50Mz48If1QHrr4HxHqD3kNg2nM9klBtfcj5NFvc3x5ciObFcoIJ8OANB2Rt73Gkw==",
+      "dev": true,
+      "license": "GPL-3.0",
+      "dependencies": {
+        "js-beautify": "^1.15.4",
+        "minimist": "^1.2.8",
+        "open": "^11.0.0",
+        "source-map-support": "^0.5.21",
+        "typescript": "^5.9.3"
+      },
+      "bin": {
+        "ccts": "bin/cognitive-complexity-ts",
+        "ccts-json": "bin/cognitive-complexity-ts-json",
+        "ccts-ui": "bin/cognitive-complexity-ts-ui",
+        "cognitive-complexity-ts": "bin/cognitive-complexity-ts",
+        "cognitive-complexity-ts-json": "bin/cognitive-complexity-ts-json",
+        "cognitive-complexity-ts-ui": "bin/cognitive-complexity-ts-ui"
+      }
+    },
     "node_modules/color-convert": {
       "version": "2.0.1",
       "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
@@ -1977,6 +2811,23 @@
         "node": ">= 0.8"
       }
     },
+    "node_modules/commander": {
+      "version": "10.0.1",
+      "resolved": "https://registry.npmjs.org/commander/-/commander-10.0.1.tgz",
+      "integrity": "sha512-y4Mg2tXshplEbSGzx7amzPwKKOCGuoSRP/CjEdwwk0FOGlUbq6lKuoyDZTNZkmxHdJtp54hdfY/JUrdL7Xfdug==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=14"
+      }
+    },
+    "node_modules/concat-map": {
+      "version": "0.0.1",
+      "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
+      "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/concat-stream": {
       "version": "2.0.0",
       "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz",
@@ -1993,6 +2844,34 @@
         "typedarray": "^0.0.6"
       }
     },
+    "node_modules/confbox": {
+      "version": "0.1.8",
+      "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.1.8.tgz",
+      "integrity": "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/config-chain": {
+      "version": "1.1.13",
+      "resolved": "https://registry.npmjs.org/config-chain/-/config-chain-1.1.13.tgz",
+      "integrity": "sha512-qj+f8APARXHrM0hraqXYb2/bOVSV4PvJQlNZ/DVj0QrmNM2q2euizkeuVckQ57J+W0mRH6Hvi+k50M4Jul2VRQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "ini": "^1.3.4",
+        "proto-list": "~1.2.1"
+      }
+    },
+    "node_modules/consola": {
+      "version": "3.4.2",
+      "resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz",
+      "integrity": "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": "^14.18.0 || >=16.10.0"
+      }
+    },
     "node_modules/content-disposition": {
       "version": "1.1.0",
       "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz",
@@ -2062,6 +2941,21 @@
       "dev": true,
       "license": "MIT"
     },
+    "node_modules/cross-spawn": {
+      "version": "7.0.6",
+      "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
+      "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "path-key": "^3.1.0",
+        "shebang-command": "^2.0.0",
+        "which": "^2.0.1"
+      },
+      "engines": {
+        "node": ">= 8"
+      }
+    },
     "node_modules/debug": {
       "version": "4.4.3",
       "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
@@ -2090,6 +2984,56 @@
         "node": ">=6"
       }
     },
+    "node_modules/deep-is": {
+      "version": "0.1.4",
+      "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",
+      "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/default-browser": {
+      "version": "5.5.0",
+      "resolved": "https://registry.npmjs.org/default-browser/-/default-browser-5.5.0.tgz",
+      "integrity": "sha512-H9LMLr5zwIbSxrmvikGuI/5KGhZ8E2zH3stkMgM5LpOWDutGM2JZaj460Udnf1a+946zc7YBgrqEWwbk7zHvGw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "bundle-name": "^4.1.0",
+        "default-browser-id": "^5.0.0"
+      },
+      "engines": {
+        "node": ">=18"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
+    "node_modules/default-browser-id": {
+      "version": "5.0.1",
+      "resolved": "https://registry.npmjs.org/default-browser-id/-/default-browser-id-5.0.1.tgz",
+      "integrity": "sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=18"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
+    "node_modules/define-lazy-prop": {
+      "version": "3.0.0",
+      "resolved": "https://registry.npmjs.org/define-lazy-prop/-/define-lazy-prop-3.0.0.tgz",
+      "integrity": "sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=12"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
     "node_modules/delayed-stream": {
       "version": "1.0.0",
       "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
@@ -2135,6 +3079,58 @@
         "node": ">= 0.4"
       }
     },
+    "node_modules/eastasianwidth": {
+      "version": "0.2.0",
+      "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz",
+      "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/editorconfig": {
+      "version": "1.0.7",
+      "resolved": "https://registry.npmjs.org/editorconfig/-/editorconfig-1.0.7.tgz",
+      "integrity": "sha512-e0GOtq/aTQhVdNyDU9e02+wz9oDDM+SIOQxWME2QRjzRX5yyLAuHDE+0aE8vHb9XRC8XD37eO2u57+F09JqFhw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@one-ini/wasm": "0.1.1",
+        "commander": "^10.0.0",
+        "minimatch": "^9.0.1",
+        "semver": "^7.5.3"
+      },
+      "bin": {
+        "editorconfig": "bin/editorconfig"
+      },
+      "engines": {
+        "node": ">=14"
+      }
+    },
+    "node_modules/editorconfig/node_modules/brace-expansion": {
+      "version": "2.1.1",
+      "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.1.tgz",
+      "integrity": "sha512-WR1cURNjuvBLMZBMbqM0UoE+WAfdUcEV1ccD8PVBVOI+Z3ND4+SZbN8RsfT2bMuG1qwz5RFvPukSZm5fF2D5eA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "balanced-match": "^1.0.0"
+      }
+    },
+    "node_modules/editorconfig/node_modules/minimatch": {
+      "version": "9.0.9",
+      "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz",
+      "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==",
+      "dev": true,
+      "license": "ISC",
+      "dependencies": {
+        "brace-expansion": "^2.0.2"
+      },
+      "engines": {
+        "node": ">=16 || 14 >=14.17"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/isaacs"
+      }
+    },
     "node_modules/ee-first": {
       "version": "1.1.1",
       "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
@@ -2261,6 +3257,187 @@
       "dev": true,
       "license": "MIT"
     },
+    "node_modules/escape-string-regexp": {
+      "version": "4.0.0",
+      "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",
+      "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=10"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
+    "node_modules/eslint": {
+      "version": "9.39.4",
+      "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.39.4.tgz",
+      "integrity": "sha512-XoMjdBOwe/esVgEvLmNsD3IRHkm7fbKIUGvrleloJXUZgDHig2IPWNniv+GwjyJXzuNqVjlr5+4yVUZjycJwfQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@eslint-community/eslint-utils": "^4.8.0",
+        "@eslint-community/regexpp": "^4.12.1",
+        "@eslint/config-array": "^0.21.2",
+        "@eslint/config-helpers": "^0.4.2",
+        "@eslint/core": "^0.17.0",
+        "@eslint/eslintrc": "^3.3.5",
+        "@eslint/js": "9.39.4",
+        "@eslint/plugin-kit": "^0.4.1",
+        "@humanfs/node": "^0.16.6",
+        "@humanwhocodes/module-importer": "^1.0.1",
+        "@humanwhocodes/retry": "^0.4.2",
+        "@types/estree": "^1.0.6",
+        "ajv": "^6.14.0",
+        "chalk": "^4.0.0",
+        "cross-spawn": "^7.0.6",
+        "debug": "^4.3.2",
+        "escape-string-regexp": "^4.0.0",
+        "eslint-scope": "^8.4.0",
+        "eslint-visitor-keys": "^4.2.1",
+        "espree": "^10.4.0",
+        "esquery": "^1.5.0",
+        "esutils": "^2.0.2",
+        "fast-deep-equal": "^3.1.3",
+        "file-entry-cache": "^8.0.0",
+        "find-up": "^5.0.0",
+        "glob-parent": "^6.0.2",
+        "ignore": "^5.2.0",
+        "imurmurhash": "^0.1.4",
+        "is-glob": "^4.0.0",
+        "json-stable-stringify-without-jsonify": "^1.0.1",
+        "lodash.merge": "^4.6.2",
+        "minimatch": "^3.1.5",
+        "natural-compare": "^1.4.0",
+        "optionator": "^0.9.3"
+      },
+      "bin": {
+        "eslint": "bin/eslint.js"
+      },
+      "engines": {
+        "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+      },
+      "funding": {
+        "url": "https://eslint.org/donate"
+      },
+      "peerDependencies": {
+        "jiti": "*"
+      },
+      "peerDependenciesMeta": {
+        "jiti": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/eslint-scope": {
+      "version": "8.4.0",
+      "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.4.0.tgz",
+      "integrity": "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==",
+      "dev": true,
+      "license": "BSD-2-Clause",
+      "dependencies": {
+        "esrecurse": "^4.3.0",
+        "estraverse": "^5.2.0"
+      },
+      "engines": {
+        "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+      },
+      "funding": {
+        "url": "https://opencollective.com/eslint"
+      }
+    },
+    "node_modules/eslint-visitor-keys": {
+      "version": "4.2.1",
+      "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz",
+      "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==",
+      "dev": true,
+      "license": "Apache-2.0",
+      "engines": {
+        "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+      },
+      "funding": {
+        "url": "https://opencollective.com/eslint"
+      }
+    },
+    "node_modules/eslint/node_modules/ajv": {
+      "version": "6.15.0",
+      "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz",
+      "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "fast-deep-equal": "^3.1.1",
+        "fast-json-stable-stringify": "^2.0.0",
+        "json-schema-traverse": "^0.4.1",
+        "uri-js": "^4.2.2"
+      },
+      "funding": {
+        "type": "github",
+        "url": "https://github.com/sponsors/epoberezkin"
+      }
+    },
+    "node_modules/eslint/node_modules/json-schema-traverse": {
+      "version": "0.4.1",
+      "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
+      "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/espree": {
+      "version": "10.4.0",
+      "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz",
+      "integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==",
+      "dev": true,
+      "license": "BSD-2-Clause",
+      "dependencies": {
+        "acorn": "^8.15.0",
+        "acorn-jsx": "^5.3.2",
+        "eslint-visitor-keys": "^4.2.1"
+      },
+      "engines": {
+        "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+      },
+      "funding": {
+        "url": "https://opencollective.com/eslint"
+      }
+    },
+    "node_modules/esquery": {
+      "version": "1.7.0",
+      "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz",
+      "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==",
+      "dev": true,
+      "license": "BSD-3-Clause",
+      "dependencies": {
+        "estraverse": "^5.1.0"
+      },
+      "engines": {
+        "node": ">=0.10"
+      }
+    },
+    "node_modules/esrecurse": {
+      "version": "4.3.0",
+      "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz",
+      "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==",
+      "dev": true,
+      "license": "BSD-2-Clause",
+      "dependencies": {
+        "estraverse": "^5.2.0"
+      },
+      "engines": {
+        "node": ">=4.0"
+      }
+    },
+    "node_modules/estraverse": {
+      "version": "5.3.0",
+      "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz",
+      "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==",
+      "dev": true,
+      "license": "BSD-2-Clause",
+      "engines": {
+        "node": ">=4.0"
+      }
+    },
     "node_modules/estree-walker": {
       "version": "3.0.3",
       "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
@@ -2271,6 +3448,16 @@
         "@types/estree": "^1.0.0"
       }
     },
+    "node_modules/esutils": {
+      "version": "2.0.3",
+      "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz",
+      "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==",
+      "dev": true,
+      "license": "BSD-2-Clause",
+      "engines": {
+        "node": ">=0.10.0"
+      }
+    },
     "node_modules/etag": {
       "version": "1.8.1",
       "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
@@ -2349,6 +3536,13 @@
       "dev": true,
       "license": "MIT"
     },
+    "node_modules/fast-json-stable-stringify": {
+      "version": "2.1.0",
+      "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",
+      "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/fast-json-stringify": {
       "version": "7.0.0",
       "resolved": "https://registry.npmjs.org/fast-json-stringify/-/fast-json-stringify-7.0.0.tgz",
@@ -2374,6 +3568,13 @@
         "rfdc": "^1.2.0"
       }
     },
+    "node_modules/fast-levenshtein": {
+      "version": "2.0.6",
+      "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz",
+      "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/fast-querystring": {
       "version": "1.1.2",
       "resolved": "https://registry.npmjs.org/fast-querystring/-/fast-querystring-1.1.2.tgz",
@@ -2469,6 +3670,37 @@
         "reusify": "^1.0.4"
       }
     },
+    "node_modules/fdir": {
+      "version": "6.5.0",
+      "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
+      "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=12.0.0"
+      },
+      "peerDependencies": {
+        "picomatch": "^3 || ^4"
+      },
+      "peerDependenciesMeta": {
+        "picomatch": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/file-entry-cache": {
+      "version": "8.0.0",
+      "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz",
+      "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "flat-cache": "^4.0.0"
+      },
+      "engines": {
+        "node": ">=16.0.0"
+      }
+    },
     "node_modules/file-type": {
       "version": "21.3.4",
       "resolved": "https://registry.npmjs.org/file-type/-/file-type-21.3.4.tgz",
@@ -2525,6 +3757,73 @@
         "node": ">=20"
       }
     },
+    "node_modules/find-up": {
+      "version": "5.0.0",
+      "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz",
+      "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "locate-path": "^6.0.0",
+        "path-exists": "^4.0.0"
+      },
+      "engines": {
+        "node": ">=10"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
+    "node_modules/fix-dts-default-cjs-exports": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/fix-dts-default-cjs-exports/-/fix-dts-default-cjs-exports-1.0.1.tgz",
+      "integrity": "sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "magic-string": "^0.30.17",
+        "mlly": "^1.7.4",
+        "rollup": "^4.34.8"
+      }
+    },
+    "node_modules/flat-cache": {
+      "version": "4.0.1",
+      "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz",
+      "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "flatted": "^3.2.9",
+        "keyv": "^4.5.4"
+      },
+      "engines": {
+        "node": ">=16"
+      }
+    },
+    "node_modules/flatted": {
+      "version": "3.4.2",
+      "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.2.tgz",
+      "integrity": "sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==",
+      "dev": true,
+      "license": "ISC"
+    },
+    "node_modules/foreground-child": {
+      "version": "3.3.1",
+      "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz",
+      "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==",
+      "dev": true,
+      "license": "ISC",
+      "dependencies": {
+        "cross-spawn": "^7.0.6",
+        "signal-exit": "^4.0.1"
+      },
+      "engines": {
+        "node": ">=14"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/isaacs"
+      }
+    },
     "node_modules/form-data": {
       "version": "4.0.6",
       "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz",
@@ -2649,6 +3948,80 @@
         "node": ">= 0.4"
       }
     },
+    "node_modules/glob": {
+      "version": "10.5.0",
+      "resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz",
+      "integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==",
+      "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me",
+      "dev": true,
+      "license": "ISC",
+      "dependencies": {
+        "foreground-child": "^3.1.0",
+        "jackspeak": "^3.1.2",
+        "minimatch": "^9.0.4",
+        "minipass": "^7.1.2",
+        "package-json-from-dist": "^1.0.0",
+        "path-scurry": "^1.11.1"
+      },
+      "bin": {
+        "glob": "dist/esm/bin.mjs"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/isaacs"
+      }
+    },
+    "node_modules/glob-parent": {
+      "version": "6.0.2",
+      "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz",
+      "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==",
+      "dev": true,
+      "license": "ISC",
+      "dependencies": {
+        "is-glob": "^4.0.3"
+      },
+      "engines": {
+        "node": ">=10.13.0"
+      }
+    },
+    "node_modules/glob/node_modules/brace-expansion": {
+      "version": "2.1.1",
+      "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.1.tgz",
+      "integrity": "sha512-WR1cURNjuvBLMZBMbqM0UoE+WAfdUcEV1ccD8PVBVOI+Z3ND4+SZbN8RsfT2bMuG1qwz5RFvPukSZm5fF2D5eA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "balanced-match": "^1.0.0"
+      }
+    },
+    "node_modules/glob/node_modules/minimatch": {
+      "version": "9.0.9",
+      "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz",
+      "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==",
+      "dev": true,
+      "license": "ISC",
+      "dependencies": {
+        "brace-expansion": "^2.0.2"
+      },
+      "engines": {
+        "node": ">=16 || 14 >=14.17"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/isaacs"
+      }
+    },
+    "node_modules/globals": {
+      "version": "14.0.0",
+      "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz",
+      "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=18"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
     "node_modules/gopd": {
       "version": "1.2.0",
       "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
@@ -2831,6 +4204,43 @@
       ],
       "license": "BSD-3-Clause"
     },
+    "node_modules/ignore": {
+      "version": "5.3.2",
+      "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
+      "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 4"
+      }
+    },
+    "node_modules/import-fresh": {
+      "version": "3.3.1",
+      "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz",
+      "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "parent-module": "^1.0.0",
+        "resolve-from": "^4.0.0"
+      },
+      "engines": {
+        "node": ">=6"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
+    "node_modules/imurmurhash": {
+      "version": "0.1.4",
+      "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz",
+      "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=0.8.19"
+      }
+    },
     "node_modules/inherits": {
       "version": "2.0.4",
       "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
@@ -2838,6 +4248,13 @@
       "dev": true,
       "license": "ISC"
     },
+    "node_modules/ini": {
+      "version": "1.3.8",
+      "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz",
+      "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==",
+      "dev": true,
+      "license": "ISC"
+    },
     "node_modules/ipaddr.js": {
       "version": "2.4.0",
       "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-2.4.0.tgz",
@@ -2848,6 +4265,32 @@
         "node": ">= 10"
       }
     },
+    "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==",
+      "dev": true,
+      "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-extglob": {
+      "version": "2.1.1",
+      "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
+      "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=0.10.0"
+      }
+    },
     "node_modules/is-fullwidth-code-point": {
       "version": "3.0.0",
       "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
@@ -2858,6 +4301,51 @@
         "node": ">=8"
       }
     },
+    "node_modules/is-glob": {
+      "version": "4.0.3",
+      "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
+      "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "is-extglob": "^2.1.1"
+      },
+      "engines": {
+        "node": ">=0.10.0"
+      }
+    },
+    "node_modules/is-in-ssh": {
+      "version": "1.0.0",
+      "resolved": "https://registry.npmjs.org/is-in-ssh/-/is-in-ssh-1.0.0.tgz",
+      "integrity": "sha512-jYa6Q9rH90kR1vKB6NM7qqd1mge3Fx4Dhw5TVlK1MUBqhEOuCagrEHMevNuCcbECmXZ0ThXkRm+Ymr51HwEPAw==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=20"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
+    "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==",
+      "dev": true,
+      "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-promise": {
       "version": "4.0.0",
       "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",
@@ -2865,6 +4353,29 @@
       "dev": true,
       "license": "MIT"
     },
+    "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==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "is-inside-container": "^1.0.0"
+      },
+      "engines": {
+        "node": ">=16"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
+    "node_modules/isexe": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
+      "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
+      "dev": true,
+      "license": "ISC"
+    },
     "node_modules/iterare": {
       "version": "1.2.1",
       "resolved": "https://registry.npmjs.org/iterare/-/iterare-1.2.1.tgz",
@@ -2875,6 +4386,91 @@
         "node": ">=6"
       }
     },
+    "node_modules/jackspeak": {
+      "version": "3.4.3",
+      "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz",
+      "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==",
+      "dev": true,
+      "license": "BlueOak-1.0.0",
+      "dependencies": {
+        "@isaacs/cliui": "^8.0.2"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/isaacs"
+      },
+      "optionalDependencies": {
+        "@pkgjs/parseargs": "^0.11.0"
+      }
+    },
+    "node_modules/joycon": {
+      "version": "3.1.1",
+      "resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz",
+      "integrity": "sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=10"
+      }
+    },
+    "node_modules/js-beautify": {
+      "version": "1.15.4",
+      "resolved": "https://registry.npmjs.org/js-beautify/-/js-beautify-1.15.4.tgz",
+      "integrity": "sha512-9/KXeZUKKJwqCXUdBxFJ3vPh467OCckSBmYDwSK/EtV090K+iMJ7zx2S3HLVDIWFQdqMIsZWbnaGiba18aWhaA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "config-chain": "^1.1.13",
+        "editorconfig": "^1.0.4",
+        "glob": "^10.4.2",
+        "js-cookie": "^3.0.5",
+        "nopt": "^7.2.1"
+      },
+      "bin": {
+        "css-beautify": "js/bin/css-beautify.js",
+        "html-beautify": "js/bin/html-beautify.js",
+        "js-beautify": "js/bin/js-beautify.js"
+      },
+      "engines": {
+        "node": ">=14"
+      }
+    },
+    "node_modules/js-cookie": {
+      "version": "3.0.8",
+      "resolved": "https://registry.npmjs.org/js-cookie/-/js-cookie-3.0.8.tgz",
+      "integrity": "sha512-yeJd4aNAdYZQjaon2bpD/Gb0B/omw7HQOsynXXcOiWVCacbBcPlgn8S/d1X6blFSaHao7ozqtW7NZW19xpCtIw==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/js-yaml": {
+      "version": "4.3.0",
+      "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz",
+      "integrity": "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/puzrin"
+        },
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/nodeca"
+        }
+      ],
+      "license": "MIT",
+      "dependencies": {
+        "argparse": "^2.0.1"
+      },
+      "bin": {
+        "js-yaml": "bin/js-yaml.js"
+      }
+    },
+    "node_modules/json-buffer": {
+      "version": "3.0.1",
+      "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz",
+      "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/json-schema-ref-resolver": {
       "version": "3.0.0",
       "resolved": "https://registry.npmjs.org/json-schema-ref-resolver/-/json-schema-ref-resolver-3.0.0.tgz",
@@ -2902,6 +4498,37 @@
       "dev": true,
       "license": "MIT"
     },
+    "node_modules/json-stable-stringify-without-jsonify": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz",
+      "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/keyv": {
+      "version": "4.5.4",
+      "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
+      "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "json-buffer": "3.0.1"
+      }
+    },
+    "node_modules/levn": {
+      "version": "0.4.1",
+      "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz",
+      "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "prelude-ls": "^1.2.1",
+        "type-check": "~0.4.0"
+      },
+      "engines": {
+        "node": ">= 0.8.0"
+      }
+    },
     "node_modules/light-my-request": {
       "version": "6.6.0",
       "resolved": "https://registry.npmjs.org/light-my-request/-/light-my-request-6.6.0.tgz",
@@ -2955,6 +4582,26 @@
       ],
       "license": "MIT"
     },
+    "node_modules/lilconfig": {
+      "version": "3.1.3",
+      "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz",
+      "integrity": "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=14"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/antonk52"
+      }
+    },
+    "node_modules/lines-and-columns": {
+      "version": "1.2.4",
+      "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz",
+      "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/load-esm": {
       "version": "1.0.3",
       "resolved": "https://registry.npmjs.org/load-esm/-/load-esm-1.0.3.tgz",
@@ -2975,6 +4622,32 @@
         "node": ">=13.2.0"
       }
     },
+    "node_modules/load-tsconfig": {
+      "version": "0.2.5",
+      "resolved": "https://registry.npmjs.org/load-tsconfig/-/load-tsconfig-0.2.5.tgz",
+      "integrity": "sha512-IXO6OCs9yg8tMKzfPZ1YmheJbZCiEsnBdcB03l0OcfK9prKnJb96siuHCr5Fl37/yo9DnKU+TLpxzTUspw9shg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
+      }
+    },
+    "node_modules/locate-path": {
+      "version": "6.0.0",
+      "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz",
+      "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "p-locate": "^5.0.0"
+      },
+      "engines": {
+        "node": ">=10"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
     "node_modules/lodash.chunk": {
       "version": "4.2.0",
       "resolved": "https://registry.npmjs.org/lodash.chunk/-/lodash.chunk-4.2.0.tgz",
@@ -2996,6 +4669,13 @@
       "dev": true,
       "license": "MIT"
     },
+    "node_modules/lodash.merge": {
+      "version": "4.6.2",
+      "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz",
+      "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/loupe": {
       "version": "3.2.1",
       "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",
@@ -3003,6 +4683,13 @@
       "dev": true,
       "license": "MIT"
     },
+    "node_modules/lru-cache": {
+      "version": "10.4.3",
+      "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",
+      "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
+      "dev": true,
+      "license": "ISC"
+    },
     "node_modules/magic-string": {
       "version": "0.30.21",
       "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
@@ -3080,6 +4767,19 @@
         "url": "https://opencollective.com/express"
       }
     },
+    "node_modules/minimatch": {
+      "version": "3.1.5",
+      "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
+      "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
+      "dev": true,
+      "license": "ISC",
+      "dependencies": {
+        "brace-expansion": "^1.1.7"
+      },
+      "engines": {
+        "node": "*"
+      }
+    },
     "node_modules/minimist": {
       "version": "1.2.8",
       "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
@@ -3090,6 +4790,36 @@
         "url": "https://github.com/sponsors/ljharb"
       }
     },
+    "node_modules/minipass": {
+      "version": "7.1.3",
+      "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz",
+      "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==",
+      "dev": true,
+      "license": "BlueOak-1.0.0",
+      "engines": {
+        "node": ">=16 || 14 >=14.17"
+      }
+    },
+    "node_modules/mlly": {
+      "version": "1.8.2",
+      "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.8.2.tgz",
+      "integrity": "sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "acorn": "^8.16.0",
+        "pathe": "^2.0.3",
+        "pkg-types": "^1.3.1",
+        "ufo": "^1.6.3"
+      }
+    },
+    "node_modules/mlly/node_modules/pathe": {
+      "version": "2.0.3",
+      "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
+      "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/ms": {
       "version": "2.1.3",
       "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
@@ -3164,6 +4894,18 @@
         "node": ">= 0.6"
       }
     },
+    "node_modules/mz": {
+      "version": "2.7.0",
+      "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz",
+      "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "any-promise": "^1.0.0",
+        "object-assign": "^4.0.1",
+        "thenify-all": "^1.0.0"
+      }
+    },
     "node_modules/nanoid": {
       "version": "3.3.15",
       "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.15.tgz",
@@ -3183,6 +4925,13 @@
         "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
       }
     },
+    "node_modules/natural-compare": {
+      "version": "1.4.0",
+      "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz",
+      "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/negotiator": {
       "version": "1.0.0",
       "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",
@@ -3193,6 +4942,22 @@
         "node": ">= 0.6"
       }
     },
+    "node_modules/nopt": {
+      "version": "7.2.1",
+      "resolved": "https://registry.npmjs.org/nopt/-/nopt-7.2.1.tgz",
+      "integrity": "sha512-taM24ViiimT/XntxbPyJQzCG+p4EKOpgD3mxFwW38mGjVUrfERQOeY4EDHjdnptttfHuHQXFx+lTP08Q+mLa/w==",
+      "dev": true,
+      "license": "ISC",
+      "dependencies": {
+        "abbrev": "^2.0.0"
+      },
+      "bin": {
+        "nopt": "bin/nopt.js"
+      },
+      "engines": {
+        "node": "^14.17.0 || ^16.13.0 || >=18.0.0"
+      }
+    },
     "node_modules/object-assign": {
       "version": "4.1.1",
       "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
@@ -3259,6 +5024,84 @@
         "wrappy": "1"
       }
     },
+    "node_modules/open": {
+      "version": "11.0.0",
+      "resolved": "https://registry.npmjs.org/open/-/open-11.0.0.tgz",
+      "integrity": "sha512-smsWv2LzFjP03xmvFoJ331ss6h+jixfA4UUV/Bsiyuu4YJPfN+FIQGOIiv4w9/+MoHkfkJ22UIaQWRVFRfH6Vw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "default-browser": "^5.4.0",
+        "define-lazy-prop": "^3.0.0",
+        "is-in-ssh": "^1.0.0",
+        "is-inside-container": "^1.0.0",
+        "powershell-utils": "^0.1.0",
+        "wsl-utils": "^0.3.0"
+      },
+      "engines": {
+        "node": ">=20"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
+    "node_modules/optionator": {
+      "version": "0.9.4",
+      "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",
+      "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "deep-is": "^0.1.3",
+        "fast-levenshtein": "^2.0.6",
+        "levn": "^0.4.1",
+        "prelude-ls": "^1.2.1",
+        "type-check": "^0.4.0",
+        "word-wrap": "^1.2.5"
+      },
+      "engines": {
+        "node": ">= 0.8.0"
+      }
+    },
+    "node_modules/p-limit": {
+      "version": "3.1.0",
+      "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",
+      "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "yocto-queue": "^0.1.0"
+      },
+      "engines": {
+        "node": ">=10"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
+    "node_modules/p-locate": {
+      "version": "5.0.0",
+      "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz",
+      "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "p-limit": "^3.0.2"
+      },
+      "engines": {
+        "node": ">=10"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
+    "node_modules/package-json-from-dist": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz",
+      "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==",
+      "dev": true,
+      "license": "BlueOak-1.0.0"
+    },
     "node_modules/pako": {
       "version": "1.0.11",
       "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz",
@@ -3266,6 +5109,19 @@
       "dev": true,
       "license": "(MIT AND Zlib)"
     },
+    "node_modules/parent-module": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz",
+      "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "callsites": "^3.0.0"
+      },
+      "engines": {
+        "node": ">=6"
+      }
+    },
     "node_modules/parseurl": {
       "version": "1.3.3",
       "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
@@ -3276,6 +5132,43 @@
         "node": ">= 0.8"
       }
     },
+    "node_modules/path-exists": {
+      "version": "4.0.0",
+      "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
+      "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/path-key": {
+      "version": "3.1.1",
+      "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
+      "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/path-scurry": {
+      "version": "1.11.1",
+      "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz",
+      "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==",
+      "dev": true,
+      "license": "BlueOak-1.0.0",
+      "dependencies": {
+        "lru-cache": "^10.2.0",
+        "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0"
+      },
+      "engines": {
+        "node": ">=16 || 14 >=14.18"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/isaacs"
+      }
+    },
     "node_modules/path-to-regexp": {
       "version": "8.4.2",
       "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz",
@@ -3311,6 +5204,19 @@
       "dev": true,
       "license": "ISC"
     },
+    "node_modules/picomatch": {
+      "version": "4.0.5",
+      "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz",
+      "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=12"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/jonschlinkert"
+      }
+    },
     "node_modules/pino": {
       "version": "10.3.1",
       "resolved": "https://registry.npmjs.org/pino/-/pino-10.3.1.tgz",
@@ -3351,6 +5257,35 @@
       "dev": true,
       "license": "MIT"
     },
+    "node_modules/pirates": {
+      "version": "4.0.7",
+      "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz",
+      "integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 6"
+      }
+    },
+    "node_modules/pkg-types": {
+      "version": "1.3.1",
+      "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz",
+      "integrity": "sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "confbox": "^0.1.8",
+        "mlly": "^1.7.4",
+        "pathe": "^2.0.1"
+      }
+    },
+    "node_modules/pkg-types/node_modules/pathe": {
+      "version": "2.0.3",
+      "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
+      "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/postcss": {
       "version": "8.5.15",
       "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.15.tgz",
@@ -3380,6 +5315,88 @@
         "node": "^10 || ^12 || >=14"
       }
     },
+    "node_modules/postcss-load-config": {
+      "version": "6.0.1",
+      "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-6.0.1.tgz",
+      "integrity": "sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/postcss/"
+        },
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/ai"
+        }
+      ],
+      "license": "MIT",
+      "dependencies": {
+        "lilconfig": "^3.1.1"
+      },
+      "engines": {
+        "node": ">= 18"
+      },
+      "peerDependencies": {
+        "jiti": ">=1.21.0",
+        "postcss": ">=8.0.9",
+        "tsx": "^4.8.1",
+        "yaml": "^2.4.2"
+      },
+      "peerDependenciesMeta": {
+        "jiti": {
+          "optional": true
+        },
+        "postcss": {
+          "optional": true
+        },
+        "tsx": {
+          "optional": true
+        },
+        "yaml": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/powershell-utils": {
+      "version": "0.1.0",
+      "resolved": "https://registry.npmjs.org/powershell-utils/-/powershell-utils-0.1.0.tgz",
+      "integrity": "sha512-dM0jVuXJPsDN6DvRpea484tCUaMiXWjuCn++HGTqUWzGDjv5tZkEZldAJ/UMlqRYGFrD/etByo4/xOuC/snX2A==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=20"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
+    "node_modules/prelude-ls": {
+      "version": "1.2.1",
+      "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",
+      "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8.0"
+      }
+    },
+    "node_modules/prettier": {
+      "version": "3.9.4",
+      "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.4.tgz",
+      "integrity": "sha512-yWG/o/4oJfo036EKAfK6ACAoDOfHeRHx4tuxkfBZiauURiaSmYwlpOr5LQqKtIkRD2z1PLteme2WoxEnj4tHTg==",
+      "dev": true,
+      "license": "MIT",
+      "bin": {
+        "prettier": "bin/prettier.cjs"
+      },
+      "engines": {
+        "node": ">=14"
+      },
+      "funding": {
+        "url": "https://github.com/prettier/prettier?sponsor=1"
+      }
+    },
     "node_modules/pretty-bytes": {
       "version": "5.6.0",
       "resolved": "https://registry.npmjs.org/pretty-bytes/-/pretty-bytes-5.6.0.tgz",
@@ -3420,6 +5437,13 @@
         "node": ">=0.4.0"
       }
     },
+    "node_modules/proto-list": {
+      "version": "1.2.4",
+      "resolved": "https://registry.npmjs.org/proto-list/-/proto-list-1.2.4.tgz",
+      "integrity": "sha512-vtK/94akxsTMhe0/cbfpR+syPuszcuwhqVjJq26CuNDgFGj682oRBXOP5MJpv2r7JtE8MsiepGIqvvOTBwn2vA==",
+      "dev": true,
+      "license": "ISC"
+    },
     "node_modules/proxy-addr": {
       "version": "2.0.7",
       "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
@@ -3444,6 +5468,16 @@
         "node": ">= 0.10"
       }
     },
+    "node_modules/punycode": {
+      "version": "2.3.1",
+      "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
+      "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=6"
+      }
+    },
     "node_modules/qs": {
       "version": "6.15.3",
       "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz",
@@ -3513,6 +5547,20 @@
         "node": ">= 6"
       }
     },
+    "node_modules/readdirp": {
+      "version": "4.1.2",
+      "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz",
+      "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 14.18.0"
+      },
+      "funding": {
+        "type": "individual",
+        "url": "https://paulmillr.com/funding/"
+      }
+    },
     "node_modules/real-require": {
       "version": "0.2.0",
       "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz",
@@ -3546,6 +5594,16 @@
         "node": ">=0.10.0"
       }
     },
+    "node_modules/resolve-from": {
+      "version": "4.0.0",
+      "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz",
+      "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=4"
+      }
+    },
     "node_modules/ret": {
       "version": "0.5.0",
       "resolved": "https://registry.npmjs.org/ret/-/ret-0.5.0.tgz",
@@ -3643,6 +5701,19 @@
         "node": ">= 18"
       }
     },
+    "node_modules/run-applescript": {
+      "version": "7.1.0",
+      "resolved": "https://registry.npmjs.org/run-applescript/-/run-applescript-7.1.0.tgz",
+      "integrity": "sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=18"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
     "node_modules/rxjs": {
       "version": "7.8.2",
       "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz",
@@ -3805,6 +5876,29 @@
       "dev": true,
       "license": "ISC"
     },
+    "node_modules/shebang-command": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
+      "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "shebang-regex": "^3.0.0"
+      },
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/shebang-regex": {
+      "version": "3.0.0",
+      "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
+      "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=8"
+      }
+    },
     "node_modules/side-channel": {
       "version": "1.1.1",
       "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz",
@@ -3888,6 +5982,19 @@
       "dev": true,
       "license": "ISC"
     },
+    "node_modules/signal-exit": {
+      "version": "4.1.0",
+      "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz",
+      "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==",
+      "dev": true,
+      "license": "ISC",
+      "engines": {
+        "node": ">=14"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/isaacs"
+      }
+    },
     "node_modules/sonic-boom": {
       "version": "4.2.1",
       "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz",
@@ -3898,6 +6005,16 @@
         "atomic-sleep": "^1.0.0"
       }
     },
+    "node_modules/source-map": {
+      "version": "0.6.1",
+      "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
+      "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
+      "dev": true,
+      "license": "BSD-3-Clause",
+      "engines": {
+        "node": ">=0.10.0"
+      }
+    },
     "node_modules/source-map-js": {
       "version": "1.2.1",
       "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
@@ -3908,6 +6025,17 @@
         "node": ">=0.10.0"
       }
     },
+    "node_modules/source-map-support": {
+      "version": "0.5.21",
+      "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz",
+      "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "buffer-from": "^1.0.0",
+        "source-map": "^0.6.0"
+      }
+    },
     "node_modules/split2": {
       "version": "4.2.0",
       "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
@@ -3976,6 +6104,22 @@
         "node": ">=8"
       }
     },
+    "node_modules/string-width-cjs": {
+      "name": "string-width",
+      "version": "4.2.3",
+      "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
+      "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "emoji-regex": "^8.0.0",
+        "is-fullwidth-code-point": "^3.0.0",
+        "strip-ansi": "^6.0.1"
+      },
+      "engines": {
+        "node": ">=8"
+      }
+    },
     "node_modules/strip-ansi": {
       "version": "6.0.1",
       "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
@@ -3989,6 +6133,33 @@
         "node": ">=8"
       }
     },
+    "node_modules/strip-ansi-cjs": {
+      "name": "strip-ansi",
+      "version": "6.0.1",
+      "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
+      "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "ansi-regex": "^5.0.1"
+      },
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/strip-json-comments": {
+      "version": "3.1.1",
+      "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz",
+      "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=8"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
     "node_modules/strtok3": {
       "version": "10.3.5",
       "resolved": "https://registry.npmjs.org/strtok3/-/strtok3-10.3.5.tgz",
@@ -4006,6 +6177,39 @@
         "url": "https://github.com/sponsors/Borewit"
       }
     },
+    "node_modules/sucrase": {
+      "version": "3.35.1",
+      "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.1.tgz",
+      "integrity": "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@jridgewell/gen-mapping": "^0.3.2",
+        "commander": "^4.0.0",
+        "lines-and-columns": "^1.1.6",
+        "mz": "^2.7.0",
+        "pirates": "^4.0.1",
+        "tinyglobby": "^0.2.11",
+        "ts-interface-checker": "^0.1.9"
+      },
+      "bin": {
+        "sucrase": "bin/sucrase",
+        "sucrase-node": "bin/sucrase-node"
+      },
+      "engines": {
+        "node": ">=16 || 14 >=14.17"
+      }
+    },
+    "node_modules/sucrase/node_modules/commander": {
+      "version": "4.1.1",
+      "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz",
+      "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 6"
+      }
+    },
     "node_modules/supports-color": {
       "version": "7.2.0",
       "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
@@ -4019,6 +6223,29 @@
         "node": ">=8"
       }
     },
+    "node_modules/thenify": {
+      "version": "3.3.1",
+      "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz",
+      "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "any-promise": "^1.0.0"
+      }
+    },
+    "node_modules/thenify-all": {
+      "version": "1.6.0",
+      "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz",
+      "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "thenify": ">= 3.1.0 < 4"
+      },
+      "engines": {
+        "node": ">=0.8"
+      }
+    },
     "node_modules/thread-stream": {
       "version": "4.2.0",
       "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-4.2.0.tgz",
@@ -4063,6 +6290,23 @@
       "dev": true,
       "license": "MIT"
     },
+    "node_modules/tinyglobby": {
+      "version": "0.2.17",
+      "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
+      "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "fdir": "^6.5.0",
+        "picomatch": "^4.0.4"
+      },
+      "engines": {
+        "node": ">=12.0.0"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/SuperchupuDev"
+      }
+    },
     "node_modules/tinypool": {
       "version": "1.1.1",
       "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz",
@@ -4132,6 +6376,36 @@
         "url": "https://github.com/sponsors/Borewit"
       }
     },
+    "node_modules/tree-kill": {
+      "version": "1.2.2",
+      "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz",
+      "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==",
+      "dev": true,
+      "license": "MIT",
+      "bin": {
+        "tree-kill": "cli.js"
+      }
+    },
+    "node_modules/ts-api-utils": {
+      "version": "2.5.0",
+      "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz",
+      "integrity": "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=18.12"
+      },
+      "peerDependencies": {
+        "typescript": ">=4.8.4"
+      }
+    },
+    "node_modules/ts-interface-checker": {
+      "version": "0.1.13",
+      "resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz",
+      "integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==",
+      "dev": true,
+      "license": "Apache-2.0"
+    },
     "node_modules/tslib": {
       "version": "2.8.1",
       "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
@@ -4139,6 +6413,563 @@
       "dev": true,
       "license": "0BSD"
     },
+    "node_modules/tsup": {
+      "version": "8.5.1",
+      "resolved": "https://registry.npmjs.org/tsup/-/tsup-8.5.1.tgz",
+      "integrity": "sha512-xtgkqwdhpKWr3tKPmCkvYmS9xnQK3m3XgxZHwSUjvfTjp7YfXe5tT3GgWi0F2N+ZSMsOeWeZFh7ZZFg5iPhing==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "bundle-require": "^5.1.0",
+        "cac": "^6.7.14",
+        "chokidar": "^4.0.3",
+        "consola": "^3.4.0",
+        "debug": "^4.4.0",
+        "esbuild": "^0.27.0",
+        "fix-dts-default-cjs-exports": "^1.0.0",
+        "joycon": "^3.1.1",
+        "picocolors": "^1.1.1",
+        "postcss-load-config": "^6.0.1",
+        "resolve-from": "^5.0.0",
+        "rollup": "^4.34.8",
+        "source-map": "^0.7.6",
+        "sucrase": "^3.35.0",
+        "tinyexec": "^0.3.2",
+        "tinyglobby": "^0.2.11",
+        "tree-kill": "^1.2.2"
+      },
+      "bin": {
+        "tsup": "dist/cli-default.js",
+        "tsup-node": "dist/cli-node.js"
+      },
+      "engines": {
+        "node": ">=18"
+      },
+      "peerDependencies": {
+        "@microsoft/api-extractor": "^7.36.0",
+        "@swc/core": "^1",
+        "postcss": "^8.4.12",
+        "typescript": ">=4.5.0"
+      },
+      "peerDependenciesMeta": {
+        "@microsoft/api-extractor": {
+          "optional": true
+        },
+        "@swc/core": {
+          "optional": true
+        },
+        "postcss": {
+          "optional": true
+        },
+        "typescript": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/tsup/node_modules/@esbuild/aix-ppc64": {
+      "version": "0.27.7",
+      "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.7.tgz",
+      "integrity": "sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg==",
+      "cpu": [
+        "ppc64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "aix"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsup/node_modules/@esbuild/android-arm": {
+      "version": "0.27.7",
+      "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.7.tgz",
+      "integrity": "sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ==",
+      "cpu": [
+        "arm"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "android"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsup/node_modules/@esbuild/android-arm64": {
+      "version": "0.27.7",
+      "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.7.tgz",
+      "integrity": "sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "android"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsup/node_modules/@esbuild/android-x64": {
+      "version": "0.27.7",
+      "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.7.tgz",
+      "integrity": "sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "android"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsup/node_modules/@esbuild/darwin-arm64": {
+      "version": "0.27.7",
+      "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.7.tgz",
+      "integrity": "sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsup/node_modules/@esbuild/darwin-x64": {
+      "version": "0.27.7",
+      "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.7.tgz",
+      "integrity": "sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsup/node_modules/@esbuild/freebsd-arm64": {
+      "version": "0.27.7",
+      "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.7.tgz",
+      "integrity": "sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "freebsd"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsup/node_modules/@esbuild/freebsd-x64": {
+      "version": "0.27.7",
+      "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.7.tgz",
+      "integrity": "sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "freebsd"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsup/node_modules/@esbuild/linux-arm": {
+      "version": "0.27.7",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.7.tgz",
+      "integrity": "sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA==",
+      "cpu": [
+        "arm"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsup/node_modules/@esbuild/linux-arm64": {
+      "version": "0.27.7",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.7.tgz",
+      "integrity": "sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsup/node_modules/@esbuild/linux-ia32": {
+      "version": "0.27.7",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.7.tgz",
+      "integrity": "sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg==",
+      "cpu": [
+        "ia32"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsup/node_modules/@esbuild/linux-loong64": {
+      "version": "0.27.7",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.7.tgz",
+      "integrity": "sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q==",
+      "cpu": [
+        "loong64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsup/node_modules/@esbuild/linux-mips64el": {
+      "version": "0.27.7",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.7.tgz",
+      "integrity": "sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw==",
+      "cpu": [
+        "mips64el"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsup/node_modules/@esbuild/linux-ppc64": {
+      "version": "0.27.7",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.7.tgz",
+      "integrity": "sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ==",
+      "cpu": [
+        "ppc64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsup/node_modules/@esbuild/linux-riscv64": {
+      "version": "0.27.7",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.7.tgz",
+      "integrity": "sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ==",
+      "cpu": [
+        "riscv64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsup/node_modules/@esbuild/linux-s390x": {
+      "version": "0.27.7",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.7.tgz",
+      "integrity": "sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw==",
+      "cpu": [
+        "s390x"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsup/node_modules/@esbuild/linux-x64": {
+      "version": "0.27.7",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.7.tgz",
+      "integrity": "sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsup/node_modules/@esbuild/netbsd-arm64": {
+      "version": "0.27.7",
+      "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.7.tgz",
+      "integrity": "sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "netbsd"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsup/node_modules/@esbuild/netbsd-x64": {
+      "version": "0.27.7",
+      "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.7.tgz",
+      "integrity": "sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "netbsd"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsup/node_modules/@esbuild/openbsd-arm64": {
+      "version": "0.27.7",
+      "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.7.tgz",
+      "integrity": "sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "openbsd"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsup/node_modules/@esbuild/openbsd-x64": {
+      "version": "0.27.7",
+      "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.7.tgz",
+      "integrity": "sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "openbsd"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsup/node_modules/@esbuild/openharmony-arm64": {
+      "version": "0.27.7",
+      "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.7.tgz",
+      "integrity": "sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "openharmony"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsup/node_modules/@esbuild/sunos-x64": {
+      "version": "0.27.7",
+      "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.7.tgz",
+      "integrity": "sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "sunos"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsup/node_modules/@esbuild/win32-arm64": {
+      "version": "0.27.7",
+      "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.7.tgz",
+      "integrity": "sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsup/node_modules/@esbuild/win32-ia32": {
+      "version": "0.27.7",
+      "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.7.tgz",
+      "integrity": "sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw==",
+      "cpu": [
+        "ia32"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsup/node_modules/@esbuild/win32-x64": {
+      "version": "0.27.7",
+      "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.7.tgz",
+      "integrity": "sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsup/node_modules/esbuild": {
+      "version": "0.27.7",
+      "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.7.tgz",
+      "integrity": "sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==",
+      "dev": true,
+      "hasInstallScript": true,
+      "license": "MIT",
+      "bin": {
+        "esbuild": "bin/esbuild"
+      },
+      "engines": {
+        "node": ">=18"
+      },
+      "optionalDependencies": {
+        "@esbuild/aix-ppc64": "0.27.7",
+        "@esbuild/android-arm": "0.27.7",
+        "@esbuild/android-arm64": "0.27.7",
+        "@esbuild/android-x64": "0.27.7",
+        "@esbuild/darwin-arm64": "0.27.7",
+        "@esbuild/darwin-x64": "0.27.7",
+        "@esbuild/freebsd-arm64": "0.27.7",
+        "@esbuild/freebsd-x64": "0.27.7",
+        "@esbuild/linux-arm": "0.27.7",
+        "@esbuild/linux-arm64": "0.27.7",
+        "@esbuild/linux-ia32": "0.27.7",
+        "@esbuild/linux-loong64": "0.27.7",
+        "@esbuild/linux-mips64el": "0.27.7",
+        "@esbuild/linux-ppc64": "0.27.7",
+        "@esbuild/linux-riscv64": "0.27.7",
+        "@esbuild/linux-s390x": "0.27.7",
+        "@esbuild/linux-x64": "0.27.7",
+        "@esbuild/netbsd-arm64": "0.27.7",
+        "@esbuild/netbsd-x64": "0.27.7",
+        "@esbuild/openbsd-arm64": "0.27.7",
+        "@esbuild/openbsd-x64": "0.27.7",
+        "@esbuild/openharmony-arm64": "0.27.7",
+        "@esbuild/sunos-x64": "0.27.7",
+        "@esbuild/win32-arm64": "0.27.7",
+        "@esbuild/win32-ia32": "0.27.7",
+        "@esbuild/win32-x64": "0.27.7"
+      }
+    },
+    "node_modules/tsup/node_modules/resolve-from": {
+      "version": "5.0.0",
+      "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz",
+      "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/tsup/node_modules/source-map": {
+      "version": "0.7.6",
+      "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.6.tgz",
+      "integrity": "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==",
+      "dev": true,
+      "license": "BSD-3-Clause",
+      "engines": {
+        "node": ">= 12"
+      }
+    },
     "node_modules/tsx": {
       "version": "4.23.0",
       "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.0.tgz",
@@ -4591,6 +7422,19 @@
         "@esbuild/win32-x64": "0.28.1"
       }
     },
+    "node_modules/type-check": {
+      "version": "0.4.0",
+      "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
+      "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "prelude-ls": "^1.2.1"
+      },
+      "engines": {
+        "node": ">= 0.8.0"
+      }
+    },
     "node_modules/type-is": {
       "version": "2.1.0",
       "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz",
@@ -4645,6 +7489,37 @@
         "node": ">=14.17"
       }
     },
+    "node_modules/typescript-eslint": {
+      "version": "8.63.0",
+      "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.63.0.tgz",
+      "integrity": "sha512-xgwXyzG4sK9ALkBxbyGkTMMOS+imnW65iPhxCQMK83KhxyoDNW7l+IDqEf9vMdoUidHpOoS967RCq4eMiTexwQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@typescript-eslint/eslint-plugin": "8.63.0",
+        "@typescript-eslint/parser": "8.63.0",
+        "@typescript-eslint/typescript-estree": "8.63.0",
+        "@typescript-eslint/utils": "8.63.0"
+      },
+      "engines": {
+        "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/typescript-eslint"
+      },
+      "peerDependencies": {
+        "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",
+        "typescript": ">=4.8.4 <6.1.0"
+      }
+    },
+    "node_modules/ufo": {
+      "version": "1.6.4",
+      "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.4.tgz",
+      "integrity": "sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==",
+      "dev": true,
+      "license": "MIT"
+    },
     "node_modules/uid": {
       "version": "2.0.2",
       "resolved": "https://registry.npmjs.org/uid/-/uid-2.0.2.tgz",
@@ -4688,6 +7563,16 @@
         "node": ">= 0.8"
       }
     },
+    "node_modules/uri-js": {
+      "version": "4.4.1",
+      "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",
+      "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",
+      "dev": true,
+      "license": "BSD-2-Clause",
+      "dependencies": {
+        "punycode": "^2.1.0"
+      }
+    },
     "node_modules/util-deprecate": {
       "version": "1.0.2",
       "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
@@ -4872,6 +7757,22 @@
         }
       }
     },
+    "node_modules/which": {
+      "version": "2.0.2",
+      "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
+      "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
+      "dev": true,
+      "license": "ISC",
+      "dependencies": {
+        "isexe": "^2.0.0"
+      },
+      "bin": {
+        "node-which": "bin/node-which"
+      },
+      "engines": {
+        "node": ">= 8"
+      }
+    },
     "node_modules/why-is-node-running": {
       "version": "2.3.0",
       "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
@@ -4889,6 +7790,120 @@
         "node": ">=8"
       }
     },
+    "node_modules/word-wrap": {
+      "version": "1.2.5",
+      "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",
+      "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=0.10.0"
+      }
+    },
+    "node_modules/wrap-ansi": {
+      "version": "8.1.0",
+      "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz",
+      "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "ansi-styles": "^6.1.0",
+        "string-width": "^5.0.1",
+        "strip-ansi": "^7.0.1"
+      },
+      "engines": {
+        "node": ">=12"
+      },
+      "funding": {
+        "url": "https://github.com/chalk/wrap-ansi?sponsor=1"
+      }
+    },
+    "node_modules/wrap-ansi-cjs": {
+      "name": "wrap-ansi",
+      "version": "7.0.0",
+      "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
+      "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "ansi-styles": "^4.0.0",
+        "string-width": "^4.1.0",
+        "strip-ansi": "^6.0.0"
+      },
+      "engines": {
+        "node": ">=10"
+      },
+      "funding": {
+        "url": "https://github.com/chalk/wrap-ansi?sponsor=1"
+      }
+    },
+    "node_modules/wrap-ansi/node_modules/ansi-regex": {
+      "version": "6.2.2",
+      "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz",
+      "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=12"
+      },
+      "funding": {
+        "url": "https://github.com/chalk/ansi-regex?sponsor=1"
+      }
+    },
+    "node_modules/wrap-ansi/node_modules/ansi-styles": {
+      "version": "6.2.3",
+      "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",
+      "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=12"
+      },
+      "funding": {
+        "url": "https://github.com/chalk/ansi-styles?sponsor=1"
+      }
+    },
+    "node_modules/wrap-ansi/node_modules/emoji-regex": {
+      "version": "9.2.2",
+      "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
+      "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/wrap-ansi/node_modules/string-width": {
+      "version": "5.1.2",
+      "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz",
+      "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "eastasianwidth": "^0.2.0",
+        "emoji-regex": "^9.2.2",
+        "strip-ansi": "^7.0.1"
+      },
+      "engines": {
+        "node": ">=12"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
+    "node_modules/wrap-ansi/node_modules/strip-ansi": {
+      "version": "7.2.0",
+      "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz",
+      "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "ansi-regex": "^6.2.2"
+      },
+      "engines": {
+        "node": ">=12"
+      },
+      "funding": {
+        "url": "https://github.com/chalk/strip-ansi?sponsor=1"
+      }
+    },
     "node_modules/wrappy": {
       "version": "1.0.2",
       "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
@@ -4917,6 +7932,36 @@
           "optional": true
         }
       }
+    },
+    "node_modules/wsl-utils": {
+      "version": "0.3.1",
+      "resolved": "https://registry.npmjs.org/wsl-utils/-/wsl-utils-0.3.1.tgz",
+      "integrity": "sha512-g/eziiSUNBSsdDJtCLB8bdYEUMj4jR7AGeUo96p/3dTafgjHhpF4RiCFPiRILwjQoDXx5MqkBr4fwWtR3Ky4Wg==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "is-wsl": "^3.1.0",
+        "powershell-utils": "^0.1.0"
+      },
+      "engines": {
+        "node": ">=20"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
+    "node_modules/yocto-queue": {
+      "version": "0.1.0",
+      "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
+      "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=10"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
     }
   }
 }
diff --git a/package.json b/package.json
index faa53aa..21565dc 100644
--- a/package.json
+++ b/package.json
@@ -1,46 +1,89 @@
 {
   "name": "@green-tea/core",
-  "version": "0.0.0",
+  "version": "26.07.0-beta.0",
   "description": "Declarative, type-safe HTTP framework. The pipeline is a graph, not a middleware chain.",
   "license": "MIT",
   "type": "commonjs",
-  "main": "dist/index.js",
-  "types": "dist/index.d.ts",
+  "main": "./dist/index.js",
+  "module": "./dist/index.mjs",
+  "types": "./dist/index.d.ts",
+  "exports": {
+    ".": {
+      "import": {
+        "types": "./dist/index.d.mts",
+        "default": "./dist/index.mjs"
+      },
+      "require": {
+        "types": "./dist/index.d.ts",
+        "default": "./dist/index.js"
+      }
+    }
+  },
+  "files": [
+    "dist",
+    "README.md",
+    "CHANGELOG.md",
+    "LICENSE"
+  ],
   "scripts": {
-    "build": "tsc -p tsconfig.json",
+    "build": "tsup",
     "test": "vitest run",
     "test:dev": "vitest",
     "typecheck": "tsc --noEmit -p tsconfig.json",
     "typecheck:bench": "tsc --noEmit -p bench/tsconfig.json",
-    "bench": "tsx bench/run.ts"
+    "lint": "eslint src",
+    "lint:fix": "eslint src --fix",
+    "format": "prettier --write \"src/**/*.ts\"",
+    "format:check": "prettier --check \"src/**/*.ts\"",
+    "docs:dev": "npm --prefix website run dev",
+    "docs:build": "npm --prefix website run build",
+    "complexity": "ccts src",
+    "complexity:check": "node scripts/check-complexity.mjs",
+    "complexity:cyclomatic": "cyclomatic-complexity \"src/**/*.ts\" -tw 15 -te 25",
+    "bench": "tsx bench/run.ts",
+    "prepublishOnly": "npm run lint && npm run complexity:check && npm run typecheck && npm test && npm run build",
+    "prepare": "git config core.hooksPath .githooks || true"
   },
   "dependencies": {
     "reflect-metadata": "0.2.2"
   },
   "peerDependencies": {
+    "busboy": "^1.6.0",
     "ws": "^8.18.0"
   },
   "peerDependenciesMeta": {
+    "busboy": {
+      "optional": true
+    },
     "ws": {
       "optional": true
     }
   },
   "devDependencies": {
+    "@eslint/js": "^9.39.4",
     "@nestjs/common": "^11.1.27",
     "@nestjs/core": "^11.1.27",
     "@nestjs/platform-express": "^11.1.27",
     "@nestjs/platform-fastify": "^11.1.27",
+    "@stylistic/eslint-plugin": "^5.10.0",
     "@types/autocannon": "^7.12.7",
+    "@types/busboy": "^1.5.4",
     "@types/express": "^5.0.6",
     "@types/node": "^18.19.0",
     "@types/ws": "^8.18.1",
     "autocannon": "^8.0.0",
+    "busboy": "^1.6.0",
+    "cognitive-complexity-ts": "^0.8.2",
+    "eslint": "^9.39.4",
     "express": "^5.2.1",
     "fastify": "^5.10.0",
     "graphql": "^16.9.0",
+    "prettier": "^3.9.4",
     "rxjs": "^7.8.2",
+    "tsup": "^8.5.1",
     "tsx": "^4.23.0",
     "typescript": "^5.5.0",
+    "typescript-eslint": "^8.63.0",
     "vitest": "^2.0.0",
     "ws": "^8.21.0"
   }
diff --git a/test/smoke.test.ts b/test/smoke.test.ts
index 76a7aa3..4267eb2 100644
--- a/test/smoke.test.ts
+++ b/test/smoke.test.ts
@@ -1,6 +1,6 @@
 import { expect, test } from 'vitest';
 import { VERSION } from '../src/index';
 
-test('package loads and exposes VERSION', () => {
-  expect(VERSION).toBe('0.0.0');
+test('package loads and exposes a CalVer VERSION', () => {
+  expect(VERSION).toMatch(/^\d{2}\.\d{2}\.\d+(-beta\.\d+)?$/);
 });
diff --git a/tsup.config.ts b/tsup.config.ts
new file mode 100644
index 0000000..20e97ef
--- /dev/null
+++ b/tsup.config.ts
@@ -0,0 +1,22 @@
+import { defineConfig } from 'tsup';
+
+// Dual build: CJS (dist/index.js) + ESM (dist/index.mjs) + type declarations, from one entry.
+// tsup injects a createRequire shim into the ESM output so the lazy require('ws') / require('busboy')
+// (optional peer deps) keep working there. reflect-metadata and the peer deps stay external.
+export default defineConfig({
+  entry: ['src/index.ts'],
+  format: ['cjs', 'esm'],
+  dts: true,
+  clean: true,
+  sourcemap: true,
+  target: 'node18',
+  // Give the ESM output a real `require` (via createRequire) so the lazy require('ws') / require('busboy')
+  // (optional peer deps) resolve instead of hitting esbuild's "Dynamic require not supported" stub.
+  esbuildOptions(options, context) {
+    if (context.format === 'esm') {
+      options.banner = {
+        js: "import { createRequire as _createRequire } from 'node:module'; const require = _createRequire(import.meta.url);",
+      };
+    }
+  },
+});

From d6c5cee0ee31ca30673cb2e72655819c8b9ff0d8 Mon Sep 17 00:00:00 2001
From: Diego Resendez 
Date: Tue, 7 Jul 2026 12:00:15 -0500
Subject: [PATCH 075/139] =?UTF-8?q?feat:=20beta-hardening=20=E2=80=94=20ro?=
 =?UTF-8?q?uting,=20degradation,=20mesh=20gate,=20uploads,=20@header?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Restructure first: split the two oversized files by cohesion (http.ts 449
→ http/{router,request,stream,ws,server,types}; app.ts 556 → app/{types,
introspect,index}), rename cryptic locals, JSDoc the public API, and
extract helpers so no function exceeds the complexity gate (createApp
187 → <15, listen 113 → 6). Public import paths are unchanged (barrels).

On that structure, five features that close the biggest gaps vs
Express/Fastify/Nest for a comparable beta:

- routing: `:name*` catch-all, specificity precedence (static ▸ param ▸
  catch-all, not registration order), and 405 + Allow when a path exists
  under a different method (was 404)
- visible degradation: optional providers that fail boot are summarized on
  listen() and queryable via app.degraded(), instead of a silent warn
- mesh is alpha — gated behind `experimental: true`; createApp throws if
  `mesh` is configured without it
- multipart moves to the optional `busboy` peer dependency (clear 501 when
  absent), keeping the core at one runtime dependency
- `@header('name')` as a singular alias of `@headers`

Signed-off-by: Diego Resendez 
---
 example/server.ts               |   2 +-
 src/app.ts                      | 387 --------------------
 src/app/index.ts                | 625 ++++++++++++++++++++++++++++++++
 src/app/introspect.ts           |  77 ++++
 src/app/types.ts                |  66 ++++
 src/bus.ts                      |  41 ++-
 src/channel.ts                  |  70 +++-
 src/container.ts                |  28 +-
 src/encoders.ts                 |  12 +-
 src/flow.ts                     |  14 +-
 src/graph-viz.ts                |  76 +++-
 src/graph.ts                    |  79 ++--
 src/http.ts                     | 316 ----------------
 src/http/index.ts               |  14 +
 src/http/request.ts             |  42 +++
 src/http/router.ts              |  92 +++++
 src/http/server.ts              | 242 +++++++++++++
 src/http/stream.ts              |  74 ++++
 src/http/types.ts               |  71 ++++
 src/http/ws.ts                  | 180 +++++++++
 src/index.ts                    |  37 +-
 src/mesh/link.ts                | 137 ++++---
 src/mesh/protocol.ts            |  38 +-
 src/mesh/teacup.ts              |  38 +-
 src/mesh/teapot.ts              | 125 +++++--
 src/metadata.ts                 | 110 +++++-
 src/multipart.ts                | 186 +++++-----
 src/params.ts                   |  77 ++--
 src/pipeline.ts                 |  53 ++-
 src/plugin.ts                   |  14 +-
 src/rooms.ts                    |  14 +-
 src/security.ts                 | 118 +++---
 src/signals.ts                  |  38 +-
 src/standard-schema.ts          |  22 +-
 src/transformers.ts             |  18 +-
 test/app.test.ts                |   4 +
 test/mesh/integration.test.ts   |  14 +-
 test/mesh/teacup.test.ts        |   4 +-
 test/multipart.test.ts          |  73 ++--
 test/params.test.ts             | 100 ++++-
 test/router.test.ts             |  52 +++
 test/transport-security.test.ts |   9 +-
 42 files changed, 2619 insertions(+), 1170 deletions(-)
 delete mode 100644 src/app.ts
 create mode 100644 src/app/index.ts
 create mode 100644 src/app/introspect.ts
 create mode 100644 src/app/types.ts
 delete mode 100644 src/http.ts
 create mode 100644 src/http/index.ts
 create mode 100644 src/http/request.ts
 create mode 100644 src/http/router.ts
 create mode 100644 src/http/server.ts
 create mode 100644 src/http/stream.ts
 create mode 100644 src/http/types.ts
 create mode 100644 src/http/ws.ts
 create mode 100644 test/router.test.ts

diff --git a/example/server.ts b/example/server.ts
index c9c1367..ed43747 100644
--- a/example/server.ts
+++ b/example/server.ts
@@ -101,7 +101,7 @@ class PingController {
 @Module({ mountpoint: '/mesh', providers: [ConfigProvider], steps: [AuthStep], controllers: [PingController] })
 class TeapotModule {}
 
-export const teapotApp = createApp({ modules: [TeapotModule], mesh: { secret: 'demo-secret' } });
+export const teapotApp = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'demo-secret' } });
 
 @Route('/remote')
 class TeacupController {
diff --git a/src/app.ts b/src/app.ts
deleted file mode 100644
index 74ead24..0000000
--- a/src/app.ts
+++ /dev/null
@@ -1,387 +0,0 @@
-import http from 'http';
-import { Bus } from './bus';
-import { Container } from './container';
-import { topoSort, subgraphFor, GraphNode, nearest } from './graph';
-import { toMermaid, toDOT, graphHtml, type GraphView } from './graph-viz';
-import { runPipeline, PipelineStep } from './pipeline';
-import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from './http';
-import { isAsyncIterable } from './channel';
-import { JsonTransformer } from './transformers';
-import { mountPlugin, Plugin, ScopeApi, ScopeNode } from './plugin';
-import {
-  Ctor, HttpMethod, Transport, getModuleMeta, getProviderMeta, getStepMeta, getRoutes, getTransformer, joinPath,
-} from './metadata';
-import { getArgs, getHandlerNeeds, resolveArgs } from './params';
-import { connectLink, type Link } from './mesh/link';
-import { Rooms } from './rooms';
-import type { TlsOptions, SecurityOptions, CorsOptions } from './security';
-import { buildRemote } from './mesh/teacup';
-import { buildManifest, createMeshControl } from './mesh/teapot';
-import type { MeshControl } from './http';
-import type { RequestEnvelope, RouteEntry } from './mesh/protocol';
-
-export interface InspectLine { name: string; kind: 'provider' | 'step' | 'handler'; origin: string }
-export interface ExplainNode { name: string; kind: 'provider' | 'step' | 'handler'; origin: string; needs: string[]; provides: string[] }
-export interface Explain { pattern: string; method: HttpMethod; transport: Transport; chain: ExplainNode[] }
-export interface App {
-  listen(port: number): Promise;
-  close(): Promise;
-  inspect(routePath: string): InspectLine[];
-  graph(): GraphView;
-  toMermaid(): string;
-  toDOT(): string;
-  explain(routePath: string): Explain;
-  bus: Bus;
-}
-
-interface RoutePlan {
-  pattern: string;
-  method: HttpMethod;
-  transport: Transport;
-  origin: string;
-  providers: GraphNode[];
-  steps: GraphNode[];
-  handlerName: string;
-  needs: string[];
-  run: (ctx: any) => Promise;
-  transformer: typeof JsonTransformer;
-  duplicates?: 'array' | 'last';
-}
-
-export interface MeshConfig {
-  secret?: string;
-  teapots?: Array<{ url: string; secret: string }>;
-  timeoutMs?: number;
-}
-
-export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions; cors?: CorsOptions; bodyDuplicates?: 'array' | 'last' }): App {
-  const bus = new Bus();
-  const container = new Container();
-  let server: http.Server | undefined;
-  const streams = new Set<() => void>();
-  const extraSteps: ScopeNode[] = [];
-  const scope: ScopeApi = { add: (n) => extraSteps.push(n) };
-
-  // collect declarations from modules
-  const providerNodes: GraphNode[] = [];
-  const stepNodes: GraphNode[] = [];
-  const runners = new Map any>();      // node name -> runtime fn
-  const setRunner = (name: string, fn: (ctx: any) => any) => {
-    if (runners.has(name)) throw new Error(`duplicate provider/step name '${name}' — names must be unique across modules and plugins`);
-    runners.set(name, fn);
-  };
-  const providerMeta = new Map();
-  const routePlans: RoutePlan[] = [];
-  const exportedProviders: string[] = [];
-  const exportedSteps: string[] = [];
-  const exportedRoutes: RouteEntry[] = [];
-
-  for (const mod of opts.modules) {
-    const m = getModuleMeta(mod);
-    if (!m) throw new Error(`${mod.name} is not a @Module`);
-    const origin = `module:${mod.name}`;
-
-    for (const P of m.providers ?? []) {
-      const meta = getProviderMeta(P)!;
-      providerNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin });
-      providerMeta.set(meta.provides, { optional: meta.optional });
-      if (meta.export) exportedProviders.push(meta.provides);
-      const inst: any = new P();
-      setRunner(meta.provides, (ctx) => inst.provide(ctx));
-    }
-    for (const S of m.steps ?? []) {
-      const meta = getStepMeta(S)!;
-      stepNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin });
-      if (meta.export) exportedSteps.push(meta.provides);
-      const inst: any = new S();
-      setRunner(meta.provides, (ctx) => inst.run(ctx));
-    }
-    for (const C of m.controllers ?? []) {
-      for (const route of getRoutes(C)) {
-        const inst: any = new C();
-        const argSpecs = getArgs(C, route.handlerName);
-        const pattern = joinPath(m.mountpoint, route.path);
-        if (route.export) {
-          if (route.transport !== 'buffer') throw new Error(`cannot export streaming route ${pattern}`);
-          exportedRoutes.push({ method: route.method, pattern });
-        }
-        routePlans.push({
-          pattern,
-          method: route.method,
-          transport: route.transport,
-          origin,
-          providers: [],
-          steps: [],
-          handlerName: route.handlerName,
-          needs: getHandlerNeeds(argSpecs),
-          run: async (c: any) => inst[route.handlerName](...(await resolveArgs(argSpecs, c))),
-          transformer: getTransformer(C, route.handlerName) ?? JsonTransformer,
-          duplicates: route.duplicates,
-        });
-      }
-    }
-  }
-
-  // plugin-added steps join the graph as their own scope
-  for (const plugin of opts.plugins ?? []) mountPlugin(plugin, bus, scope);
-  for (const n of extraSteps) {
-    const node = { name: n.name, needs: n.needs, provides: n.provides, origin: 'plugin' };
-    if (n.kind === 'provider') providerNodes.push(node); else stepNodes.push(node);
-    setRunner(n.name, n.run);
-  }
-
-  // built-in: auto-provide a shared Rooms instance (unless the user declares one)
-  if (!runners.has('rooms')) {
-    const roomsInstance = new Rooms();
-    providerNodes.push({ name: 'rooms', needs: [], provides: ['rooms'], origin: 'builtin' });
-    providerMeta.set('rooms', { optional: false });
-    setRunner('rooms', () => ({ rooms: roomsInstance }));   // merge object -> ctx.rooms
-  }
-
-  // For each route, resolve which providers/steps feed it via topo order.
-  // MVP: every route depends on every declared step + provider in the app graph.
-  // For mesh apps, finalize is DEFERRED to listen() so remote scopes can join the graph first.
-  let orderedProviders: GraphNode[] = [];
-  let orderedSteps: GraphNode[] = [];
-  let booted = false;
-  const finalizeGraph = (): void => {
-    const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params']);
-    orderedProviders = ordered.filter((n) => providerNodes.includes(n));
-    orderedSteps = ordered.filter((n) => stepNodes.includes(n));
-    const alwaysSteps = stepNodes.filter((n) => n.provides.length === 0);   // side-effect/observer steps (plugins)
-    const alwaysNeeds = alwaysSteps.flatMap((n) => n.needs);                // pull observers' deps into every route
-    for (const plan of routePlans) {
-      const closure = subgraphFor([...plan.needs, ...alwaysNeeds], ordered);
-      plan.providers = closure.filter((n) => providerNodes.includes(n));
-      const sliced = new Set([...closure.filter((n) => stepNodes.includes(n)), ...alwaysSteps]);
-      plan.steps = ordered.filter((n) => stepNodes.includes(n) && sliced.has(n));   // topo order, deduped
-    }
-
-    const producedKeys = new Set([
-      ...providerNodes.flatMap((n) => n.provides),
-      ...stepNodes.flatMap((n) => n.provides),
-    ]);
-    const allowed = new Set([...producedKeys, 'req', 'params', 'query', 'body', 'headers', 'inbound', 'abort']);
-    for (const plan of routePlans) {
-      for (const need of plan.needs) {
-        if (!allowed.has(need)) {
-          const hint = nearest(need, allowed);
-          throw new Error(`handler '${plan.handlerName}' needs '${need}' but nothing (local or mesh) provides it${hint ? ` — did you mean '${hint}'?` : ''}`);
-        }
-      }
-    }
-    booted = true;
-  };
-  if (!opts.mesh) finalizeGraph();
-
-  const inspect = (routePath: string): InspectLine[] => {
-    if (!booted) throw new Error('inspect() unavailable before listen() for mesh apps');
-    const plan = routePlans.find((p) => p.pattern === routePath);
-    if (!plan) throw new Error(`no route: ${routePath}`);
-    return [
-      ...plan.providers.map((p) => ({ name: p.name, kind: 'provider' as const, origin: p.origin })),
-      ...plan.steps.map((s) => ({ name: s.name, kind: 'step' as const, origin: s.origin })),
-      { name: plan.handlerName, kind: 'handler' as const, origin: plan.origin },
-    ];
-  };
-
-  const graph = (): GraphView => {
-    if (!booted) throw new Error('graph() unavailable before listen() for mesh apps');
-    return {
-      nodes: [
-        ...providerNodes.map((n) => ({ name: n.name, kind: 'provider' as const, origin: n.origin, needs: n.needs, provides: n.provides })),
-        ...stepNodes.map((n) => ({ name: n.name, kind: 'step' as const, origin: n.origin, needs: n.needs, provides: n.provides })),
-      ],
-      routes: routePlans.map((p) => ({
-        pattern: p.pattern, method: p.method, transport: p.transport,
-        chain: [...p.providers.map((n) => n.name), ...p.steps.map((n) => n.name), p.handlerName],
-      })),
-    };
-  };
-
-  const explain = (routePath: string): Explain => {
-    if (!booted) throw new Error('explain() unavailable before listen() for mesh apps');
-    const plan = routePlans.find((p) => p.pattern === routePath);
-    if (!plan) throw new Error(`no route: ${routePath}`);
-    const nv = (n: GraphNode, kind: 'provider' | 'step'): ExplainNode => ({ name: n.name, kind, origin: n.origin, needs: n.needs, provides: n.provides });
-    return {
-      pattern: plan.pattern, method: plan.method, transport: plan.transport,
-      chain: [
-        ...plan.providers.map((n) => nv(n, 'provider')),
-        ...plan.steps.map((n) => nv(n, 'step')),
-        { name: plan.handlerName, kind: 'handler', origin: plan.origin, needs: plan.needs, provides: [] },
-      ],
-    };
-  };
-
-  const providedSeed = async (plan: RoutePlan): Promise> => {
-    const provided: Record = {};
-    for (const p of plan.providers) {
-      if (container.has(p.name)) Object.assign(provided, (await container.resolve(p.name)) as Record);
-    }
-    return provided;
-  };
-  const planSteps = (plan: RoutePlan): PipelineStep[] => plan.steps.map((s) => {
-    const fn = runners.get(s.name);
-    if (!fn) throw new Error(`no runner registered for step '${s.name}'`);
-    return { name: s.name, origin: s.origin, run: fn };
-  });
-
-  const listen = async (port: number): Promise => {
-    // mesh teacup: connect remote teapots, splice their scopes/routes into the graph, then finalize
-    const remoteRoutes: RouteDef[] = [];
-    const meshLinks: Link[] = [];
-    let meshControl: MeshControl | undefined;
-    if (opts.mesh && !booted) {
-      try {
-        for (const t of opts.mesh.teapots ?? []) {
-          const link = await connectLink({ url: t.url, secret: t.secret, timeoutMs: opts.mesh.timeoutMs, bus });
-          meshLinks.push(link);
-          const { providers, steps, routes } = buildRemote(link, t.url);
-          for (const p of providers) {
-            providerNodes.push({ name: p.name, needs: [], provides: [p.name], origin: `mesh:${t.url}` });
-            providerMeta.set(p.name, { optional: false });
-            setRunner(p.name, p.run);
-          }
-          for (const s of steps) {
-            stepNodes.push({ name: s.name, needs: [], provides: [s.name], origin: `mesh:${t.url}` });
-            setRunner(s.name, s.run);
-          }
-          for (const r of routes) {
-            remoteRoutes.push({
-              method: r.method, pattern: r.pattern, transport: 'buffer',
-              handler: async (req) => r.handler(req as RequestEnvelope),
-            });
-          }
-        }
-        finalizeGraph();
-      } catch (err) {
-        for (const l of meshLinks) { try { l.close(); } catch { /* */ } }
-        throw err;
-      }
-    }
-
-    // apply overrides: swap any provider/step runner by token in one line
-    if (opts.overrides) {
-      const produced = new Set([...providerNodes, ...stepNodes].flatMap((n) => n.provides));
-      for (const [token, val] of Object.entries(opts.overrides)) {
-        if (!produced.has(token)) throw new Error(`override for unknown token '${token}'`);
-        const fn = typeof val === 'function' ? (val as (ctx: any) => any) : () => ({ [token]: val });
-        runners.set(token, fn);   // direct set (setRunner throws on dup); replaces the real runner
-      }
-    }
-
-    // run app-scoped providers in order (fail-fast for required)
-    for (const node of orderedProviders) {
-      bus.emit('boot:provider:start', { name: node.name, scope: node.origin });
-      try {
-        const value = await runners.get(node.name)!(await snapshot(container, node.needs));
-        container.register(node.name, 'app', () => value);
-        await container.resolve(node.name);                // warm the cache
-        bus.emit('boot:provider:ok', { name: node.name });
-      } catch (error) {
-        bus.emit('boot:provider:fail', { name: node.name, error });
-        if (!providerMeta.get(node.name)?.optional) {
-          throw new Error(`provider '${node.name}' failed: ${(error as Error).message}`);
-        }
-        // optional: warn, leave it unregistered; routes needing it fail at request time
-        // ponytail: full partial-degradation is out of scope (spec §10); warn is enough here
-        console.warn(`[green-tea] optional provider '${node.name}' failed: ${(error as Error).message}`);
-      }
-    }
-
-    // mesh teapot: expose declared exports over the control channel (lazy resolvers read live state)
-    const hasExports = exportedProviders.length || exportedSteps.length || exportedRoutes.length;
-    if (hasExports && !opts.mesh?.secret) {
-      throw new Error('mesh: exports declared (export: true) but no mesh.secret configured to gate the control channel');
-    }
-    if (opts.mesh?.secret && hasExports) {
-      const manifest = buildManifest({ providers: exportedProviders, steps: exportedSteps, routes: exportedRoutes });
-      const resolveScope = async (name: string, env: RequestEnvelope): Promise => {
-        let ctx: any = { req: env, params: env.params, query: env.query, body: env.body, headers: env.headers };
-        for (const p of orderedProviders) if (container.has(p.name)) Object.assign(ctx, await container.resolve(p.name));
-        for (const s of orderedSteps) { const fn = runners.get(s.name)!; ctx = { ...ctx, ...(await fn(ctx)) }; }
-        return ctx[name];
-      };
-      const resolveRoute = async (name: string, env: RequestEnvelope) => {
-        const plan = routePlans.find((p) => p.pattern === name && p.method === env.method);
-        if (!plan) { const e: any = new Error(`no route ${name}`); e.status = 404; throw e; }
-        const provided = await providedSeed(plan);
-        const result = await runPipeline({
-          steps: planSteps(plan), handler: plan.run, transformer: plan.transformer, bus,
-          seed: { ...provided, req: env, params: env.params, query: env.query, body: env.body, headers: env.headers },
-        });
-        if ('stream' in result) { const e: any = new Error('cannot proxy a streaming route'); e.status = 500; throw e; }
-        return result;
-      };
-      meshControl = createMeshControl({ secret: opts.mesh.secret, manifest, resolveScope, resolveRoute, bus });
-    }
-
-    const httpRoutes: RouteDef[] = [
-      ...routePlans
-        .filter((plan) => plan.transport !== 'ws')   // buffer | sse | ndjson | negotiate
-        .map((plan): RouteDef => ({
-          method: plan.method, pattern: plan.pattern, transport: plan.transport, bodyDuplicates: plan.duplicates,
-          handler: async (req) => {
-            const provided = await providedSeed(plan);
-            return runPipeline({
-              steps: planSteps(plan), handler: plan.run, transformer: plan.transformer, bus,
-              seed: { ...provided, req, params: req.params, query: req.query, body: req.body, headers: req.headers,
-                      protocol: req.protocol, ip: req.ip },
-            });
-          },
-        })),
-      ...remoteRoutes,
-    ];
-
-    if (opts.devGraph) {
-      httpRoutes.push({
-        method: 'GET', pattern: '/__graph__', transport: 'buffer',
-        handler: async (req) => {
-          const mermaid = toMermaid(graph());
-          const accept = String(req.headers['accept'] ?? '');
-          return accept.includes('text/plain')
-            ? { status: 200, headers: { 'content-type': 'text/plain' }, body: mermaid }
-            : { status: 200, headers: { 'content-type': 'text/html' }, body: graphHtml(mermaid) };
-        },
-      });
-    }
-
-    const wsRoutes: WsRouteDef[] = routePlans
-      .filter((plan) => plan.transport === 'ws' || plan.transport === 'negotiate')
-      .map((plan) => ({
-        pattern: plan.pattern,
-        open: async ({ params, inbound, abort, req }) => {
-          const provided = await providedSeed(plan);
-          // ws upgrades come in on the raw Node req; trustProxy derivation for ws is out of scope here
-          let ctx: any = { ...provided, req, params, query: parseQuery(req.url ?? ''), body: undefined,
-                           headers: req.headers, inbound, abort,
-                           protocol: (req.socket as any).encrypted ? 'https' : 'http', ip: req.socket.remoteAddress ?? '' };
-          for (const s of planSteps(plan)) { ctx = { ...ctx, ...(await s.run(ctx)) }; }
-          const out = await plan.run(ctx);
-          if (!isAsyncIterable(out)) throw new Error(`@Ws handler '${plan.handlerName}' must return an AsyncIterable`);
-          return out as AsyncIterable;
-        },
-      }));
-
-    server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams, tls: opts.tls, trustProxy: opts.trustProxy, security: opts.security ?? true, cors: opts.cors, bodyDuplicates: opts.bodyDuplicates });
-    server.on('close', () => { for (const l of meshLinks) { try { l.close(); } catch { /* */ } } });
-    await new Promise((resolve) => server!.listen(port, resolve));
-    return server;
-  };
-
-  const close = (): Promise => new Promise((resolve) => {
-    if (!server) return resolve();
-    server.close(() => resolve());            // waits for in-flight buffered to drain
-    for (const closeStream of streams) closeStream();  // force-close long-lived SSE/WS so close() resolves
-    server.closeIdleConnections();            // Node >=18.2: drop idle keep-alive
-  });
-
-  return { listen, close, inspect, graph, toMermaid: () => toMermaid(graph()), toDOT: () => toDOT(graph()), explain, bus };
-}
-
-async function snapshot(c: Container, needs: string[]): Promise> {
-  const out: Record = {};
-  for (const key of needs) if (c.has(key)) Object.assign(out, (await c.resolve(key)) as Record);
-  return out;
-}
diff --git a/src/app/index.ts b/src/app/index.ts
new file mode 100644
index 0000000..4073e14
--- /dev/null
+++ b/src/app/index.ts
@@ -0,0 +1,625 @@
+import http from 'http';
+import { Bus } from '../bus';
+import { Container } from '../container';
+import { topoSort, subgraphFor, GraphNode, nearest } from '../graph';
+import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz';
+import { runPipeline, PipelineStep } from '../pipeline';
+import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
+import { isAsyncIterable } from '../channel';
+import { JsonTransformer } from '../transformers';
+import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin';
+import { Ctor, getModuleMeta, getProviderMeta, getStepMeta, getRoutes, getTransformer, joinPath } from '../metadata';
+import { getArgs, getHandlerNeeds, resolveArgs } from '../params';
+import { connectLink, type Link } from '../mesh/link';
+import { Rooms } from '../rooms';
+import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
+import { buildRemote } from '../mesh/teacup';
+import { buildManifest, createMeshControl } from '../mesh/teapot';
+import type { MeshControl } from '../http';
+import type { RequestEnvelope, RouteEntry } from '../mesh/protocol';
+import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types';
+import { inspectRoute, buildGraphView, explainRoute } from './introspect';
+
+export type { App, InspectLine, ExplainNode, Explain, MeshConfig } from './types';
+
+type Runner = (ctx: any) => any;
+
+/** Mutable graph state assembled from modules/plugins and later spliced with remote mesh scopes. */
+interface Registry {
+  providerNodes: GraphNode[];
+  stepNodes: GraphNode[];
+  runners: Map;
+  providerMeta: Map;
+  routePlans: RoutePlan[];
+  exportedProviders: string[];
+  exportedSteps: string[];
+  exportedRoutes: RouteEntry[];
+  setRunner(name: string, runner: Runner): void;
+}
+
+/** Request-time helpers shared by the HTTP, WS and mesh route builders. */
+interface PipelineDeps {
+  providedSeed(plan: RoutePlan): Promise>;
+  planSteps(plan: RoutePlan): PipelineStep[];
+  bus: Bus;
+}
+
+/**
+ * Build an {@link App} from the given modules and options.
+ * Wires providers, steps, controllers and plugins into a dependency graph; for non-mesh apps
+ * the graph is finalized eagerly, otherwise finalization is deferred to {@link App.listen}.
+ */
+export function createApp(opts: {
+  modules: Ctor[];
+  plugins?: Plugin[];
+  mesh?: MeshConfig;
+  limits?: RequestLimits;
+  devGraph?: boolean;
+  overrides?: Record;
+  tls?: TlsOptions;
+  trustProxy?: boolean;
+  security?: boolean | SecurityOptions;
+  cors?: CorsOptions;
+  bodyDuplicates?: 'array' | 'last';
+  /** Opt in to alpha features whose API may still change. Currently gates `mesh`. */
+  experimental?: boolean;
+}): App {
+  // mesh is alpha: its API and wire protocol may change. Require an explicit opt-in.
+  if (opts.mesh && !opts.experimental) {
+    throw new Error(
+      'mesh is an alpha feature — pass `experimental: true` to createApp to enable it (its API may change between releases)',
+    );
+  }
+
+  const bus = new Bus();
+  const container = new Container();
+  let server: http.Server | undefined;
+  const streams = new Set<() => void>();
+  const degradedProviders: string[] = []; // optional providers that failed to boot (running degraded)
+
+  // Collect declarations from modules, then splice in plugin- and built-in-provided nodes.
+  const registry = collectModules(opts.modules);
+  const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry;
+  mountPlugins(opts.plugins, bus, registry);
+  provideBuiltins(registry);
+
+  // For each route, resolve which providers/steps feed it via topo order.
+  // MVP: every route depends on every declared step + provider in the app graph.
+  // For mesh apps, finalize is DEFERRED to listen() so remote scopes can join the graph first.
+  let orderedProviders: GraphNode[] = [];
+  let orderedSteps: GraphNode[] = [];
+  let booted = false;
+
+  const finalize = (): void => {
+    ({ orderedProviders, orderedSteps } = finalizeGraph(registry));
+    booted = true;
+  };
+
+  if (!opts.mesh) finalize();
+
+  const inspect = (routePath: string): InspectLine[] => inspectRoute(routePlans, routePath, booted);
+  const graph = (): GraphView => buildGraphView(providerNodes, stepNodes, routePlans, booted);
+  const explain = (routePath: string): Explain => explainRoute(routePlans, routePath, booted);
+
+  const providedSeed = (plan: RoutePlan) => seedProviders(container, plan);
+  const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan);
+
+  const listen = async (port: number): Promise => {
+    const deps: PipelineDeps = { providedSeed, planSteps, bus };
+
+    // mesh teacup: connect remote teapots, splice their scopes/routes into the graph, then finalize
+    let remoteRoutes: RouteDef[] = [];
+    const meshLinks: Link[] = [];
+
+    if (opts.mesh && !booted) {
+      const spliced = await spliceRemoteScopes(opts.mesh, bus, registry);
+      remoteRoutes = spliced.remoteRoutes;
+      meshLinks.push(...spliced.meshLinks);
+      finalize();
+    }
+
+    applyOverrides(opts.overrides, registry);
+    degradedProviders.length = 0;
+    degradedProviders.push(...(await bootProviders(orderedProviders, { runners, container, providerMeta, bus })));
+
+    if (degradedProviders.length) {
+      console.warn(
+        `[green-tea] started with ${degradedProviders.length} degraded optional provider(s): ${degradedProviders.join(', ')} — routes that need them will fail at request time.`,
+      );
+    }
+
+    const meshControl = buildMeshControl(opts.mesh, registry, {
+      container,
+      orderedProviders,
+      orderedSteps,
+      deps,
+    });
+
+    const httpRoutes = buildHttpRoutes(routePlans, remoteRoutes, deps);
+    if (opts.devGraph) httpRoutes.push(devGraphRoute(graph));
+    const wsRoutes = buildWsRoutes(routePlans, deps);
+
+    server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, {
+      limits: opts.limits,
+      streams,
+      tls: opts.tls,
+      trustProxy: opts.trustProxy,
+      security: opts.security ?? true,
+      cors: opts.cors,
+      bodyDuplicates: opts.bodyDuplicates,
+    });
+    server.on('close', () => closeLinks(meshLinks));
+    await new Promise((resolve) => server!.listen(port, resolve));
+    return server;
+  };
+
+  const close = (): Promise =>
+    new Promise((resolve) => {
+      if (!server) return resolve();
+      server.close(() => resolve()); // waits for in-flight buffered to drain
+      for (const closeStream of streams) closeStream(); // force-close long-lived SSE/WS so close() resolves
+      server.closeIdleConnections(); // Node >=18.2: drop idle keep-alive
+    });
+
+  return {
+    listen,
+    close,
+    inspect,
+    graph,
+    toMermaid: () => toMermaid(graph()),
+    toDOT: () => toDOT(graph()),
+    explain,
+    degraded: () => [...degradedProviders],
+    bus,
+  };
+}
+
+/** Creates an empty {@link Registry} whose `setRunner` enforces globally-unique provider/step names. */
+function emptyRegistry(): Registry {
+  const runners = new Map(); // node name -> runtime fn
+
+  const setRunner = (name: string, runner: Runner) => {
+    if (runners.has(name))
+      throw new Error(`duplicate provider/step name '${name}' — names must be unique across modules and plugins`);
+    runners.set(name, runner);
+  };
+
+  return {
+    providerNodes: [],
+    stepNodes: [],
+    runners,
+    providerMeta: new Map(),
+    routePlans: [],
+    exportedProviders: [],
+    exportedSteps: [],
+    exportedRoutes: [],
+    setRunner,
+  };
+}
+
+/** Registers a module's `@Provider` classes as app-scope provider nodes. */
+function collectProviders(providers: Ctor[], origin: string, registry: Registry): void {
+  for (const ProviderClass of providers) {
+    const meta = getProviderMeta(ProviderClass)!;
+    registry.providerNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin });
+    registry.providerMeta.set(meta.provides, { optional: meta.optional });
+    if (meta.export) registry.exportedProviders.push(meta.provides);
+    const instance: any = new ProviderClass();
+    registry.setRunner(meta.provides, (ctx) => instance.provide(ctx));
+  }
+}
+
+/** Registers a module's `@Step` classes as request-scope step nodes. */
+function collectSteps(steps: Ctor[], origin: string, registry: Registry): void {
+  for (const StepClass of steps) {
+    const meta = getStepMeta(StepClass)!;
+    registry.stepNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin });
+    if (meta.export) registry.exportedSteps.push(meta.provides);
+    const instance: any = new StepClass();
+    registry.setRunner(meta.provides, (ctx) => instance.run(ctx));
+  }
+}
+
+/** Registers each `@Route` handler on a module's controllers as a {@link RoutePlan}. */
+function collectControllers(controllers: Ctor[], mountpoint: string, origin: string, registry: Registry): void {
+  for (const ControllerClass of controllers) {
+    for (const route of getRoutes(ControllerClass)) {
+      const instance: any = new ControllerClass();
+      const argSpecs = getArgs(ControllerClass, route.handlerName);
+      const pattern = joinPath(mountpoint, route.path);
+
+      if (route.export) {
+        if (route.transport !== 'buffer') throw new Error(`cannot export streaming route ${pattern}`);
+        registry.exportedRoutes.push({ method: route.method, pattern });
+      }
+
+      registry.routePlans.push({
+        pattern,
+        method: route.method,
+        transport: route.transport,
+        origin,
+        providers: [],
+        steps: [],
+        handlerName: route.handlerName,
+        needs: getHandlerNeeds(argSpecs),
+        run: async (context: any) => instance[route.handlerName](...(await resolveArgs(argSpecs, context))),
+        transformer: getTransformer(ControllerClass, route.handlerName) ?? JsonTransformer,
+        duplicates: route.duplicates,
+      });
+    }
+  }
+}
+
+/** Reads every module's metadata into a fresh {@link Registry} of graph nodes, runners and exports. */
+function collectModules(modules: Ctor[]): Registry {
+  const registry = emptyRegistry();
+
+  for (const mod of modules) {
+    const moduleMeta = getModuleMeta(mod);
+    if (!moduleMeta) throw new Error(`${mod.name} is not a @Module`);
+    const origin = `module:${mod.name}`;
+    collectProviders(moduleMeta.providers ?? [], origin, registry);
+    collectSteps(moduleMeta.steps ?? [], origin, registry);
+    collectControllers(moduleMeta.controllers ?? [], moduleMeta.mountpoint, origin, registry);
+  }
+
+  return registry;
+}
+
+/** Mounts plugins and splices any steps/providers they add into the registry as their own scope. */
+function mountPlugins(plugins: Plugin[] | undefined, bus: Bus, registry: Registry): void {
+  const extraSteps: ScopeNode[] = [];
+  const scope: ScopeApi = { add: (node) => extraSteps.push(node) };
+
+  for (const plugin of plugins ?? []) mountPlugin(plugin, bus, scope);
+
+  for (const scopeNode of extraSteps) {
+    const node = { name: scopeNode.name, needs: scopeNode.needs, provides: scopeNode.provides, origin: 'plugin' };
+    if (scopeNode.kind === 'provider') registry.providerNodes.push(node);
+    else registry.stepNodes.push(node);
+    registry.setRunner(scopeNode.name, scopeNode.run);
+  }
+}
+
+/** Auto-provides a shared {@link Rooms} instance unless the user already declared a `rooms` provider. */
+function provideBuiltins(registry: Registry): void {
+  if (registry.runners.has('rooms')) return;
+  const roomsInstance = new Rooms();
+  registry.providerNodes.push({ name: 'rooms', needs: [], provides: ['rooms'], origin: 'builtin' });
+  registry.providerMeta.set('rooms', { optional: false });
+  registry.setRunner('rooms', () => ({ rooms: roomsInstance })); // merge object -> ctx.rooms
+}
+
+/**
+ * Topo-sorts the graph, slices each route's provider/step closure into its plan, and validates every need.
+ * @returns The app-scope providers and request-scope steps in execution order.
+ */
+function finalizeGraph(registry: Registry): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } {
+  const { providerNodes, stepNodes, routePlans } = registry;
+  const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params']);
+  const orderedProviders = ordered.filter((node) => providerNodes.includes(node));
+  const orderedSteps = ordered.filter((node) => stepNodes.includes(node));
+  const alwaysSteps = stepNodes.filter((node) => node.provides.length === 0); // side-effect/observer steps (plugins)
+  const alwaysNeeds = alwaysSteps.flatMap((node) => node.needs); // pull observers' deps into every route
+
+  for (const plan of routePlans) {
+    const closure = subgraphFor([...plan.needs, ...alwaysNeeds], ordered);
+    plan.providers = closure.filter((node) => providerNodes.includes(node));
+    const sliced = new Set([...closure.filter((node) => stepNodes.includes(node)), ...alwaysSteps]);
+    plan.steps = ordered.filter((node) => stepNodes.includes(node) && sliced.has(node)); // topo order, deduped
+  }
+
+  assertNeedsSatisfiable(routePlans, providerNodes, stepNodes);
+  return { orderedProviders, orderedSteps };
+}
+
+/** Throws if any route needs a key that nothing (local or mesh) provides, suggesting the nearest match. */
+function assertNeedsSatisfiable(routePlans: RoutePlan[], providerNodes: GraphNode[], stepNodes: GraphNode[]): void {
+  const producedKeys = new Set([
+    ...providerNodes.flatMap((node) => node.provides),
+    ...stepNodes.flatMap((node) => node.provides),
+  ]);
+  const allowed = new Set([...producedKeys, 'req', 'params', 'query', 'body', 'headers', 'inbound', 'abort']);
+
+  for (const plan of routePlans) {
+    for (const need of plan.needs) {
+      if (allowed.has(need)) continue;
+      const hint = nearest(need, allowed);
+      throw new Error(
+        `handler '${plan.handlerName}' needs '${need}' but nothing (local or mesh) provides it${hint ? ` — did you mean '${hint}'?` : ''}`,
+      );
+    }
+  }
+}
+
+/** Connects the configured teapots, splices their remote providers/steps into the registry, and returns their routes. */
+async function spliceRemoteScopes(
+  mesh: MeshConfig,
+  bus: Bus,
+  registry: Registry,
+): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[] }> {
+  const remoteRoutes: RouteDef[] = [];
+  const meshLinks: Link[] = [];
+
+  try {
+    for (const teapot of mesh.teapots ?? []) {
+      const link = await connectLink({ url: teapot.url, secret: teapot.secret, timeoutMs: mesh.timeoutMs, bus });
+      meshLinks.push(link);
+      const { providers, steps, routes } = buildRemote(link);
+      const origin = `mesh:${teapot.url}`;
+
+      for (const provider of providers) {
+        registry.providerNodes.push({ name: provider.name, needs: [], provides: [provider.name], origin });
+        registry.providerMeta.set(provider.name, { optional: false });
+        registry.setRunner(provider.name, provider.run);
+      }
+
+      for (const step of steps) {
+        registry.stepNodes.push({ name: step.name, needs: [], provides: [step.name], origin });
+        registry.setRunner(step.name, step.run);
+      }
+
+      for (const route of routes) {
+        remoteRoutes.push({
+          method: route.method,
+          pattern: route.pattern,
+          transport: 'buffer',
+          handler: async (req) => route.handler(req as RequestEnvelope),
+        });
+      }
+    }
+  } catch (err) {
+    closeLinks(meshLinks);
+    throw err;
+  }
+
+  return { remoteRoutes, meshLinks };
+}
+
+/** Swaps provider/step runners by token — a value replaces the runner, a function becomes it. */
+function applyOverrides(overrides: Record | undefined, registry: Registry): void {
+  if (!overrides) return;
+  const produced = new Set([...registry.providerNodes, ...registry.stepNodes].flatMap((node) => node.provides));
+
+  for (const [token, val] of Object.entries(overrides)) {
+    if (!produced.has(token)) throw new Error(`override for unknown token '${token}'`);
+    const runner: Runner = typeof val === 'function' ? (val as Runner) : () => ({ [token]: val });
+    registry.runners.set(token, runner); // direct set (setRunner throws on dup); replaces the real runner
+  }
+}
+
+/**
+ * Runs app-scoped providers in topo order, caching each result; required failures abort, optional ones warn.
+ * @returns The names of optional providers that failed and are running degraded (unregistered).
+ */
+async function bootProviders(
+  orderedProviders: GraphNode[],
+  deps: {
+    runners: Map;
+    container: Container;
+    providerMeta: Map;
+    bus: Bus;
+  },
+): Promise {
+  const { runners, container, providerMeta, bus } = deps;
+  const degraded: string[] = [];
+
+  for (const node of orderedProviders) {
+    bus.emit('boot:provider:start', { name: node.name, scope: node.origin });
+
+    try {
+      const value = await runners.get(node.name)!(await snapshot(container, node.needs));
+      container.register(node.name, 'app', () => value);
+      await container.resolve(node.name); // warm the cache
+      bus.emit('boot:provider:ok', { name: node.name });
+    } catch (error) {
+      bus.emit('boot:provider:fail', { name: node.name, error });
+
+      if (!providerMeta.get(node.name)?.optional) {
+        throw new Error(`provider '${node.name}' failed: ${(error as Error).message}`);
+      }
+
+      // optional: warn, leave it unregistered; routes needing it fail at request time
+      // ponytail: full partial-degradation is out of scope (spec §10); warn is enough here
+      degraded.push(node.name);
+      console.warn(`[green-tea] optional provider '${node.name}' failed: ${(error as Error).message}`);
+    }
+  }
+
+  return degraded;
+}
+
+/**
+ * Builds the mesh control gateway that exposes this node's declared exports over the control channel.
+ * Returns undefined when there is nothing to export; throws if exports are declared without a gating secret.
+ */
+function buildMeshControl(
+  mesh: MeshConfig | undefined,
+  registry: Registry,
+  deps: { container: Container; orderedProviders: GraphNode[]; orderedSteps: GraphNode[]; deps: PipelineDeps },
+): MeshControl | undefined {
+  const { exportedProviders, exportedSteps, exportedRoutes, routePlans, runners } = registry;
+  const hasExports = exportedProviders.length || exportedSteps.length || exportedRoutes.length;
+
+  if (hasExports && !mesh?.secret) {
+    throw new Error('mesh: exports declared (export: true) but no mesh.secret configured to gate the control channel');
+  }
+
+  if (!mesh?.secret || !hasExports) return undefined;
+  const { container, orderedProviders, orderedSteps } = deps;
+  const { bus, providedSeed, planSteps } = deps.deps;
+  const manifest = buildManifest({ providers: exportedProviders, steps: exportedSteps, routes: exportedRoutes });
+
+  const resolveScope = async (name: string, env: RequestEnvelope): Promise => {
+    // 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 };
+
+    for (const provider of orderedProviders)
+      if (container.has(provider.name)) Object.assign(context, await container.resolve(provider.name));
+
+    for (const step of orderedSteps) {
+      const runner = runners.get(step.name)!;
+      context = { ...context, ...(await runner(context)) };
+    }
+
+    return context[name];
+  };
+
+  const resolveRoute = async (name: string, env: RequestEnvelope) => {
+    const plan = routePlans.find((candidate) => candidate.pattern === name && candidate.method === env.method);
+
+    if (!plan) {
+      const error: any = new Error(`no route ${name}`);
+      error.status = 404;
+      throw error;
+    }
+
+    const provided = await providedSeed(plan);
+    const result = await runPipeline({
+      steps: planSteps(plan),
+      handler: plan.run,
+      transformer: plan.transformer,
+      bus,
+      seed: { ...provided, req: env, params: env.params, query: env.query, body: env.body, headers: env.headers },
+    });
+
+    if ('stream' in result) {
+      const error: any = new Error('cannot proxy a streaming route');
+      error.status = 500;
+      throw error;
+    }
+
+    return result;
+  };
+
+  return createMeshControl({ secret: mesh.secret, manifest, resolveScope, resolveRoute, bus });
+}
+
+/** Compiles every non-ws route plan into an HTTP route that seeds and runs the pipeline, plus any remote routes. */
+function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps: PipelineDeps): RouteDef[] {
+  const { providedSeed, planSteps, bus } = deps;
+
+  const local = routePlans
+    .filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate
+    .map((plan): RouteDef => ({
+      method: plan.method,
+      pattern: plan.pattern,
+      transport: plan.transport,
+      bodyDuplicates: plan.duplicates,
+      handler: async (req) => {
+        const provided = await providedSeed(plan);
+        return runPipeline({
+          steps: planSteps(plan),
+          handler: plan.run,
+          transformer: plan.transformer,
+          bus,
+          seed: {
+            ...provided,
+            req,
+            params: req.params,
+            query: req.query,
+            body: req.body,
+            headers: req.headers,
+            protocol: req.protocol,
+            ip: req.ip,
+          },
+        });
+      },
+    }));
+
+  return [...local, ...remoteRoutes];
+}
+
+/** The dev-only `/__graph__` route: serves the dependency graph as Mermaid text or an HTML viewer. */
+function devGraphRoute(graph: () => GraphView): RouteDef {
+  return {
+    method: 'GET',
+    pattern: '/__graph__',
+    transport: 'buffer',
+    handler: async (req) => {
+      const mermaid = toMermaid(graph());
+      const accept = String(req.headers['accept'] ?? '');
+      return accept.includes('text/plain')
+        ? { status: 200, headers: { 'content-type': 'text/plain' }, body: mermaid }
+        : { status: 200, headers: { 'content-type': 'text/html' }, body: graphHtml(mermaid) };
+    },
+  };
+}
+
+/** Compiles every ws/negotiate route plan into a WebSocket route that seeds context and runs its steps + handler. */
+function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[] {
+  const { providedSeed, planSteps } = deps;
+
+  return routePlans
+    .filter((plan) => plan.transport === 'ws' || plan.transport === 'negotiate')
+    .map((plan) => ({
+      pattern: plan.pattern,
+      open: async ({ params, inbound, abort, req }) => {
+        const provided = await providedSeed(plan);
+        // ws upgrades come in on the raw Node req; trustProxy derivation for ws is out of scope here
+        // context is intentionally `any`: each step merges arbitrary keys into it
+        let context: any = {
+          ...provided,
+          req,
+          params,
+          query: parseQuery(req.url ?? ''),
+          body: undefined,
+          headers: req.headers,
+          inbound,
+          abort,
+          protocol: (req.socket as any).encrypted ? 'https' : 'http',
+          ip: req.socket.remoteAddress ?? '',
+        };
+
+        for (const step of planSteps(plan)) {
+          context = { ...context, ...(await step.run(context)) };
+        }
+
+        const result = await plan.run(context);
+        if (!isAsyncIterable(result)) throw new Error(`@Ws handler '${plan.handlerName}' must return an AsyncIterable`);
+        return result as AsyncIterable;
+      },
+    }));
+}
+
+/** Best-effort close of every mesh link, ignoring individual failures. */
+function closeLinks(links: Link[]): void {
+  for (const link of links) {
+    try {
+      link.close();
+    } catch {
+      /* */
+    }
+  }
+}
+
+/** Merges every app-scope provider bound to a route into a request seed (skips unresolved providers). */
+async function seedProviders(container: Container, plan: RoutePlan): Promise> {
+  const provided: Record = {};
+
+  for (const provider of plan.providers) {
+    if (container.has(provider.name))
+      Object.assign(provided, (await container.resolve(provider.name)) as Record);
+  }
+
+  return provided;
+}
+
+/** Resolves a route's step nodes into runnable pipeline steps, failing if any runner is missing. */
+function compilePlanSteps(runners: Map, plan: RoutePlan): PipelineStep[] {
+  return plan.steps.map((step) => {
+    const runner = runners.get(step.name);
+    if (!runner) throw new Error(`no runner registered for step '${step.name}'`);
+    return { name: step.name, origin: step.origin, run: runner };
+  });
+}
+
+/** Resolves the given need-keys from the container into a merged snapshot (skips unregistered keys). */
+async function snapshot(container: Container, needs: string[]): Promise> {
+  const resolved: Record = {};
+
+  for (const key of needs)
+    if (container.has(key)) Object.assign(resolved, (await container.resolve(key)) as Record);
+
+  return resolved;
+}
diff --git a/src/app/introspect.ts b/src/app/introspect.ts
new file mode 100644
index 0000000..7607c3d
--- /dev/null
+++ b/src/app/introspect.ts
@@ -0,0 +1,77 @@
+import type { GraphNode } from '../graph';
+import type { GraphView } from '../graph-viz';
+import type { InspectLine, Explain, ExplainNode, RoutePlan } from './types';
+
+/** Lists the provider/step/handler chain for a route, in execution order. */
+export function inspectRoute(routePlans: RoutePlan[], routePath: string, booted: boolean): InspectLine[] {
+  if (!booted) throw new Error('inspect() unavailable before listen() for mesh apps');
+  const plan = routePlans.find((candidate) => candidate.pattern === routePath);
+  if (!plan) throw new Error(`no route: ${routePath}`);
+  return [
+    ...plan.providers.map((provider) => ({
+      name: provider.name,
+      kind: 'provider' as const,
+      origin: provider.origin,
+    })),
+    ...plan.steps.map((step) => ({ name: step.name, kind: 'step' as const, origin: step.origin })),
+    { name: plan.handlerName, kind: 'handler' as const, origin: plan.origin },
+  ];
+}
+
+/** Builds the full dependency-graph view: every provider/step node plus each route's chain. */
+export function buildGraphView(
+  providerNodes: GraphNode[],
+  stepNodes: GraphNode[],
+  routePlans: RoutePlan[],
+  booted: boolean,
+): GraphView {
+  if (!booted) throw new Error('graph() unavailable before listen() for mesh apps');
+  return {
+    nodes: [
+      ...providerNodes.map((node) => ({
+        name: node.name,
+        kind: 'provider' as const,
+        origin: node.origin,
+        needs: node.needs,
+        provides: node.provides,
+      })),
+      ...stepNodes.map((node) => ({
+        name: node.name,
+        kind: 'step' as const,
+        origin: node.origin,
+        needs: node.needs,
+        provides: node.provides,
+      })),
+    ],
+    routes: routePlans.map((plan) => ({
+      pattern: plan.pattern,
+      method: plan.method,
+      transport: plan.transport,
+      chain: [...plan.providers.map((node) => node.name), ...plan.steps.map((node) => node.name), plan.handlerName],
+    })),
+  };
+}
+
+/** Explains a single route: its match criteria and the ordered chain with each node's needs/provides. */
+export function explainRoute(routePlans: RoutePlan[], routePath: string, booted: boolean): Explain {
+  if (!booted) throw new Error('explain() unavailable before listen() for mesh apps');
+  const plan = routePlans.find((candidate) => candidate.pattern === routePath);
+  if (!plan) throw new Error(`no route: ${routePath}`);
+  const toExplainNode = (node: GraphNode, kind: 'provider' | 'step'): ExplainNode => ({
+    name: node.name,
+    kind,
+    origin: node.origin,
+    needs: node.needs,
+    provides: node.provides,
+  });
+  return {
+    pattern: plan.pattern,
+    method: plan.method,
+    transport: plan.transport,
+    chain: [
+      ...plan.providers.map((node) => toExplainNode(node, 'provider')),
+      ...plan.steps.map((node) => toExplainNode(node, 'step')),
+      { name: plan.handlerName, kind: 'handler', origin: plan.origin, needs: plan.needs, provides: [] },
+    ],
+  };
+}
diff --git a/src/app/types.ts b/src/app/types.ts
new file mode 100644
index 0000000..8876f44
--- /dev/null
+++ b/src/app/types.ts
@@ -0,0 +1,66 @@
+import type http from 'http';
+import type { Bus } from '../bus';
+import type { GraphNode } from '../graph';
+import type { GraphView } from '../graph-viz';
+import type { HttpMethod, Transport } from '../metadata';
+import { JsonTransformer } from '../transformers';
+
+/** One entry in an {@link App.inspect} listing: a provider, step or handler and where it came from. */
+export interface InspectLine {
+  name: string;
+  kind: 'provider' | 'step' | 'handler';
+  origin: string;
+}
+
+/** A node in an {@link Explain} chain, annotated with the keys it needs and provides. */
+export interface ExplainNode {
+  name: string;
+  kind: 'provider' | 'step' | 'handler';
+  origin: string;
+  needs: string[];
+  provides: string[];
+}
+
+/** A full route explanation: its match criteria and the ordered provider/step/handler chain. */
+export interface Explain {
+  pattern: string;
+  method: HttpMethod;
+  transport: Transport;
+  chain: ExplainNode[];
+}
+
+/** A running application instance with lifecycle, introspection and graph-export methods. */
+export interface App {
+  listen(port: number): Promise;
+  close(): Promise;
+  inspect(routePath: string): InspectLine[];
+  graph(): GraphView;
+  toMermaid(): string;
+  toDOT(): string;
+  explain(routePath: string): Explain;
+  /** Names of optional providers that failed to boot and are running degraded (empty until {@link App.listen}). */
+  degraded(): string[];
+  bus: Bus;
+}
+
+/** Internal per-route plan: match criteria, its resolved provider/step closure, and the compiled handler. */
+export interface RoutePlan {
+  pattern: string;
+  method: HttpMethod;
+  transport: Transport;
+  origin: string;
+  providers: GraphNode[];
+  steps: GraphNode[];
+  handlerName: string;
+  needs: string[];
+  run: (ctx: any) => Promise;
+  transformer: typeof JsonTransformer;
+  duplicates?: 'array' | 'last';
+}
+
+/** Mesh networking options: a secret to gate this node's exports and/or remote teapots to connect to. */
+export interface MeshConfig {
+  secret?: string;
+  teapots?: Array<{ url: string; secret: string }>;
+  timeoutMs?: number;
+}
diff --git a/src/bus.ts b/src/bus.ts
index 9143d9e..149b890 100644
--- a/src/bus.ts
+++ b/src/bus.ts
@@ -1,10 +1,20 @@
+/** Names of every lifecycle event the framework emits over the {@link Bus}. */
 export type LifecycleEvent =
-  | 'boot:provider:start' | 'boot:provider:ok' | 'boot:provider:fail'
-  | 'request:step:enter' | 'request:step:leave' | 'request:step:error'
-  | 'stream:open' | 'stream:close' | 'stream:error'
-  | 'mesh:connect' | 'mesh:disconnect' | 'mesh:rpc:error'
+  | 'boot:provider:start'
+  | 'boot:provider:ok'
+  | 'boot:provider:fail'
+  | 'request:step:enter'
+  | 'request:step:leave'
+  | 'request:step:error'
+  | 'stream:open'
+  | 'stream:close'
+  | 'stream:error'
+  | 'mesh:connect'
+  | 'mesh:disconnect'
+  | 'mesh:rpc:error'
   | 'plugin:mounted';
 
+/** Data carried by a lifecycle event: the subject's name plus optional scope, error and timing. */
 export interface EventPayload {
   name: string;
   scope?: string;
@@ -12,19 +22,26 @@ export interface EventPayload {
   durationMs?: number;
 }
 
+/** In-process pub/sub for framework lifecycle events; observer failures are swallowed so they never break the pipeline. */
 export class Bus {
   private readonly listeners = new Map void>>();
 
-  on(event: LifecycleEvent, fn: (p: EventPayload) => void): () => void {
-    const set = this.listeners.get(event) ?? new Set();
-    set.add(fn);
-    this.listeners.set(event, set);
-    return () => set.delete(fn);
+  /** Subscribe `listener` to `event`; returns an unsubscribe function. */
+  on(event: LifecycleEvent, listener: (p: EventPayload) => void): () => void {
+    const listenerSet = this.listeners.get(event) ?? new Set();
+    listenerSet.add(listener);
+    this.listeners.set(event, listenerSet);
+    return () => listenerSet.delete(listener);
   }
 
-  emit(event: LifecycleEvent, p: EventPayload): void {
-    for (const fn of this.listeners.get(event) ?? []) {
-      try { fn(p); } catch { /* observers must never break the pipeline */ }
+  /** Dispatch `payload` to every listener of `event`; a throwing listener is isolated and does not affect the others. */
+  emit(event: LifecycleEvent, payload: EventPayload): void {
+    for (const listener of this.listeners.get(event) ?? []) {
+      try {
+        listener(payload);
+      } catch {
+        /* observers must never break the pipeline */
+      }
     }
   }
 }
diff --git a/src/channel.ts b/src/channel.ts
index def9077..7f71793 100644
--- a/src/channel.ts
+++ b/src/channel.ts
@@ -1,3 +1,7 @@
+/**
+ * A push-driven async stream: producers call `push`/`close`/`fail`, consumers use `for await`.
+ * Each `for await` gets its own independent subscription (fan-out).
+ */
 export interface Channel extends AsyncIterable {
   push(value: T): void;
   close(): void;
@@ -5,15 +9,16 @@ export interface Channel extends AsyncIterable {
   readonly closed: boolean;
 }
 
+/** Type guard: true when `x` implements the async-iterable protocol. */
 export function isAsyncIterable(x: unknown): x is AsyncIterable {
   return x != null && typeof (x as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function';
 }
 
 interface Sub {
   iterator: AsyncIterator;
-  push(v: T, cap: number): void;
+  push(value: T, cap: number): void;
   end(): void;
-  fail(e: unknown): void;
+  fail(err: unknown): void;
 }
 
 function newSub(onReturn: () => void): Sub {
@@ -23,29 +28,48 @@ function newSub(onReturn: () => void): Sub {
   let failure: { err: unknown } | null = null;
 
   return {
-    push(v, cap) {
+    push(value, cap) {
       if (ended) return;
-      if (pending) { const p = pending; pending = null; p.resolve({ value: v, done: false }); return; }
-      queue.push(v);
+
+      if (pending) {
+        const waiter = pending;
+        pending = null;
+        waiter.resolve({ value, done: false });
+        return;
+      }
+
+      queue.push(value);
       if (queue.length > cap) queue.shift(); // drop-oldest when buffer is full
     },
     end() {
       if (ended) return;
       ended = true;
-      if (pending) { const p = pending; pending = null; p.resolve({ value: undefined as never, done: true }); }
+
+      if (pending) {
+        const waiter = pending;
+        pending = null;
+        waiter.resolve({ value: undefined as never, done: true });
+      }
     },
-    fail(e) {
+    fail(err) {
       if (ended) return;
       ended = true;
-      failure = { err: e };
-      if (pending) { const p = pending; pending = null; p.reject(e); }
+      failure = { err };
+
+      if (pending) {
+        const waiter = pending;
+        pending = null;
+        waiter.reject(err);
+      }
     },
     iterator: {
       next(): Promise> {
         if (queue.length) return Promise.resolve({ value: queue.shift() as T, done: false });
         if (failure) return Promise.reject(failure.err);
         if (ended) return Promise.resolve({ value: undefined as never, done: true });
-        return new Promise>((resolve, reject) => { pending = { resolve, reject }; });
+        return new Promise>((resolve, reject) => {
+          pending = { resolve, reject };
+        });
       },
       return(): Promise> {
         ended = true;
@@ -56,6 +80,10 @@ function newSub(onReturn: () => void): Sub {
   };
 }
 
+/**
+ * Creates a fan-out {@link Channel}. Values pushed are delivered to every active subscriber.
+ * @param opts.buffer Per-subscriber queue cap; drops oldest when exceeded (default: unbounded).
+ */
 export function channel(opts: { buffer?: number } = {}): Channel {
   const cap = opts.buffer ?? Infinity;
   const subs = new Set>();
@@ -63,27 +91,31 @@ export function channel(opts: { buffer?: number } = {}): Channel {
   let closedFlag = false;
 
   return {
-    get closed() { return closedFlag; },
+    get closed() {
+      return closedFlag;
+    },
     push(value) {
       if (done) return;
-      for (const s of subs) s.push(value, cap);
+      for (const sub of subs) sub.push(value, cap);
     },
     close() {
       if (done) return;
-      done = true; closedFlag = true;
-      for (const s of subs) s.end();
+      done = true;
+      closedFlag = true;
+      for (const sub of subs) sub.end();
       subs.clear();
     },
     fail(err) {
       if (done) return;
-      done = true; closedFlag = true;
-      for (const s of subs) s.fail(err);
+      done = true;
+      closedFlag = true;
+      for (const sub of subs) sub.fail(err);
       subs.clear();
     },
     [Symbol.asyncIterator](): AsyncIterator {
-      const s = newSub(() => subs.delete(s));
-      subs.add(s);
-      return s.iterator;
+      const sub = newSub(() => subs.delete(sub));
+      subs.add(sub);
+      return sub.iterator;
     },
   };
 }
diff --git a/src/container.ts b/src/container.ts
index d376eeb..af53dd0 100644
--- a/src/container.ts
+++ b/src/container.ts
@@ -1,27 +1,43 @@
+/** Lifetime of a binding: `app` values are memoized for the process, `request` values are recomputed per resolve. */
 export type Scope = 'app' | 'request';
+/** Produces a bound value from the current context; may be async. */
 export type Factory = (ctx: Record) => unknown | Promise;
 
-interface Binding { scope: Scope; factory: Factory; cached?: unknown; resolved?: boolean }
+interface Binding {
+  scope: Scope;
+  factory: Factory;
+  cached?: unknown;
+  resolved?: boolean;
+}
 
+/** Minimal token-keyed dependency container with app-scoped memoization and async, mesh-ready resolution. */
 export class Container {
   private readonly bindings = new Map();
 
+  /** Bind `token` to `factory` under `scope`, replacing any existing binding. */
   register(token: string, scope: Scope, factory: Factory): void {
     this.bindings.set(token, { scope, factory });
   }
 
+  /** Whether `token` currently has a binding. */
   has(token: string): boolean {
     return this.bindings.has(token);
   }
 
+  /** Resolve `token`'s value; app-scoped results are cached, request-scoped ones re-run the factory. Throws on unknown tokens. */
   // ponytail: app-scope memoizes; request-scope always re-runs. resolve is async
   // so a future remote transport (mesh) slots in without changing callers.
   async resolve(token: string, ctx: Record = {}): Promise {
-    const b = this.bindings.get(token);
-    if (!b) throw new Error(`unknown token: ${token}`);
-    if (b.scope === 'app' && b.resolved) return b.cached;
-    const value = await b.factory(ctx);
-    if (b.scope === 'app') { b.cached = value; b.resolved = true; }
+    const binding = this.bindings.get(token);
+    if (!binding) throw new Error(`unknown token: ${token}`);
+    if (binding.scope === 'app' && binding.resolved) return binding.cached;
+    const value = await binding.factory(ctx);
+
+    if (binding.scope === 'app') {
+      binding.cached = value;
+      binding.resolved = true;
+    }
+
     return value;
   }
 }
diff --git a/src/encoders.ts b/src/encoders.ts
index e5642e3..9819a88 100644
--- a/src/encoders.ts
+++ b/src/encoders.ts
@@ -1,3 +1,7 @@
+/**
+ * Serializes stream items into wire frames for a streaming transport (SSE, NDJSON).
+ * `headers` is written once before the first frame; `ping` (if present) is sent periodically to keep the connection alive.
+ */
 export interface StreamEncoder {
   headers: Record;
   encode(item: unknown): string | Buffer;
@@ -5,17 +9,19 @@ export interface StreamEncoder {
   ping?(): string;
 }
 
-const msgOf = (e: unknown): string => (e instanceof Error ? e.message : String(e));
+const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));
 
+/** Server-Sent Events encoder: one JSON payload per `data:` event, with comment-line pings. */
 export const sseEncoder: StreamEncoder = {
   headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' },
   encode: (item) => `data: ${JSON.stringify(item)}\n\n`,
-  encodeError: (err) => `event: error\ndata: ${JSON.stringify({ error: msgOf(err) })}\n\n`,
+  encodeError: (err) => `event: error\ndata: ${JSON.stringify({ error: messageOf(err) })}\n\n`,
   ping: () => ': ping\n\n',
 };
 
+/** Newline-delimited JSON encoder: one JSON object per line. */
 export const ndjsonEncoder: StreamEncoder = {
   headers: { 'content-type': 'application/x-ndjson' },
   encode: (item) => `${JSON.stringify(item)}\n`,
-  encodeError: (err) => `${JSON.stringify({ error: msgOf(err) })}\n`,
+  encodeError: (err) => `${JSON.stringify({ error: messageOf(err) })}\n`,
 };
diff --git a/src/flow.ts b/src/flow.ts
index 263af84..1728083 100644
--- a/src/flow.ts
+++ b/src/flow.ts
@@ -1,18 +1,23 @@
+/** A single flow step: receives the accumulated context and returns the fields it contributes. */
 export type StepFn = (ctx: In) => Out | Promise;
 
+/** A built flow ready to execute: its ordered steps, terminal handler, and a `run` entry point. */
 export interface CompiledFlow {
   steps: { name: string; fn: StepFn }[];
   handler: (ctx: Acc) => unknown;
   run(seed: Seed): Promise;
 }
 
+/** Immutable builder that chains typed steps, each widening the accumulated context type. */
 export class Flow {
   constructor(private readonly steps: { name: string; fn: StepFn }[] = []) {}
 
+  /** Appends a step and returns a new Flow whose context now includes the step's output. */
   step(name: string, fn: StepFn): Flow {
     return new Flow([...this.steps, { name, fn }]);
   }
 
+  /** Seals the flow with a terminal handler, producing a runnable CompiledFlow. */
   handle(handler: (ctx: Acc) => unknown): CompiledFlow {
     const steps = this.steps;
     return {
@@ -20,16 +25,19 @@ export class Flow {
       handler,
       async run(seed: Seed): Promise {
         let ctx: any = { ...seed };
-        for (const s of steps) {
-          const out = await s.fn(ctx);
-          ctx = { ...ctx, ...out };
+
+        for (const step of steps) {
+          const output = await step.fn(ctx);
+          ctx = { ...ctx, ...output };
         }
+
         return handler(ctx);
       },
     };
   }
 }
 
+/** Starts a new flow whose seed and initial context are the same type. */
 export function flow(): Flow {
   return new Flow();
 }
diff --git a/src/graph-viz.ts b/src/graph-viz.ts
index f981962..686c2eb 100644
--- a/src/graph-viz.ts
+++ b/src/graph-viz.ts
@@ -1,45 +1,81 @@
-export interface GraphNodeView { name: string; kind: 'provider' | 'step'; origin: string; needs: string[]; provides: string[] }
-export interface GraphRouteView { pattern: string; method: string; transport: string; chain: string[] }
-export interface GraphView { nodes: GraphNodeView[]; routes: GraphRouteView[] }
+/** Renderable view of a graph node (provider or step). */
+export interface GraphNodeView {
+  name: string;
+  kind: 'provider' | 'step';
+  origin: string;
+  needs: string[];
+  provides: string[];
+}
+/** Renderable view of a route and the chain of nodes feeding its handler. */
+export interface GraphRouteView {
+  pattern: string;
+  method: string;
+  transport: string;
+  chain: string[];
+}
+/** Full graph payload consumed by the diagram renderers. */
+export interface GraphView {
+  nodes: GraphNodeView[];
+  routes: GraphRouteView[];
+}
 
-const nid = (s: string) => 'n_' + s.replace(/[^a-zA-Z0-9]/g, '_');
-const rid = (s: string) => 'r_' + s.replace(/[^a-zA-Z0-9]/g, '_');
+/** Sanitizes a node name into a Mermaid/DOT-safe node id. */
+const nid = (name: string) => 'n_' + name.replace(/[^a-zA-Z0-9]/g, '_');
+/** Sanitizes a route pattern into a Mermaid/DOT-safe node id. */
+const rid = (pattern: string) => 'r_' + pattern.replace(/[^a-zA-Z0-9]/g, '_');
 
+/** Renders the graph view as Mermaid `flowchart` source. */
 export function toMermaid(view: GraphView): string {
-  const known = new Set(view.nodes.map((n) => n.name));
+  const known = new Set(view.nodes.map((node) => node.name));
   const out: string[] = ['flowchart LR'];
-  for (const n of view.nodes) {
-    out.push(n.kind === 'provider' ? `  ${nid(n.name)}(["${n.name}"])` : `  ${nid(n.name)}["${n.name}"]`);
+
+  for (const node of view.nodes) {
+    out.push(
+      node.kind === 'provider' ? `  ${nid(node.name)}(["${node.name}"])` : `  ${nid(node.name)}["${node.name}"]`,
+    );
   }
-  for (const n of view.nodes) for (const need of n.needs) if (known.has(need)) out.push(`  ${nid(need)} --> ${nid(n.name)}`);
-  for (const r of view.routes) {
-    out.push(`  ${rid(r.pattern)}{{"${r.method} ${r.pattern}"}}`);
-    for (const c of r.chain) if (known.has(c)) out.push(`  ${nid(c)} --> ${rid(r.pattern)}`);
+
+  for (const node of view.nodes)
+    for (const need of node.needs) if (known.has(need)) out.push(`  ${nid(need)} --> ${nid(node.name)}`);
+
+  for (const route of view.routes) {
+    out.push(`  ${rid(route.pattern)}{{"${route.method} ${route.pattern}"}}`);
+    for (const link of route.chain) if (known.has(link)) out.push(`  ${nid(link)} --> ${rid(route.pattern)}`);
   }
+
   return out.join('\n');
 }
 
+/** Renders the graph view as Graphviz DOT source. */
 export function toDOT(view: GraphView): string {
-  const known = new Set(view.nodes.map((n) => n.name));
+  const known = new Set(view.nodes.map((node) => node.name));
   const out: string[] = ['digraph green_tea {', '  rankdir=LR;'];
-  for (const n of view.nodes) {
-    out.push(`  "${n.name}" [shape=${n.kind === 'provider' ? 'ellipse' : 'box'}];`);
+
+  for (const node of view.nodes) {
+    out.push(`  "${node.name}" [shape=${node.kind === 'provider' ? 'ellipse' : 'box'}];`);
   }
-  for (const n of view.nodes) for (const need of n.needs) if (known.has(need)) out.push(`  "${need}" -> "${n.name}";`);
-  for (const r of view.routes) {
-    const label = `${r.method} ${r.pattern}`;
+
+  for (const node of view.nodes)
+    for (const need of node.needs) if (known.has(need)) out.push(`  "${need}" -> "${node.name}";`);
+
+  for (const route of view.routes) {
+    const label = `${route.method} ${route.pattern}`;
     out.push(`  "${label}" [shape=hexagon];`);
-    for (const c of r.chain) if (known.has(c)) out.push(`  "${c}" -> "${label}";`);
+    for (const link of route.chain) if (known.has(link)) out.push(`  "${link}" -> "${label}";`);
   }
+
   out.push('}');
   return out.join('\n');
 }
 
+/** Wraps Mermaid source in a self-contained HTML page that renders it in the browser. */
 export function graphHtml(mermaid: string): string {
   return [
     'green-tea graph',
     '',
-    '
', mermaid, '
', + '
',
+    mermaid,
+    '
', '', ].join('\n'); } diff --git a/src/graph.ts b/src/graph.ts index 1e992d1..b576dfd 100644 --- a/src/graph.ts +++ b/src/graph.ts @@ -1,21 +1,40 @@ function levenshtein(a: string, b: string): number { - const m = a.length, n = b.length; - const d: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)); - for (let i = 0; i <= m; i++) d[i][0] = i; - for (let j = 0; j <= n; j++) d[0][j] = j; - for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++) { - d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)); - } - return d[m][n]; + const aLen = a.length, + bLen = b.length; + const matrix: number[][] = Array.from({ length: aLen + 1 }, () => Array(bLen + 1).fill(0)); + for (let i = 0; i <= aLen; i++) matrix[i][0] = i; + for (let j = 0; j <= bLen; j++) matrix[0][j] = j; + + for (let i = 1; i <= aLen; i++) + for (let j = 1; j <= bLen; j++) { + matrix[i][j] = Math.min( + matrix[i - 1][j] + 1, + matrix[i][j - 1] + 1, + matrix[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1), + ); + } + + return matrix[aLen][bLen]; } +/** Returns the candidate within edit distance 2 of `token`, for "did you mean?" hints. */ export function nearest(token: string, candidates: Iterable): string | undefined { let best: string | undefined; - let bestD = 3; // only suggest edit distance <= 2 - for (const c of candidates) { const dist = levenshtein(token, c); if (dist < bestD) { bestD = dist; best = c; } } + let bestDistance = 3; // only suggest edit distance <= 2 + + for (const candidate of candidates) { + const distance = levenshtein(token, candidate); + + if (distance < bestDistance) { + bestDistance = distance; + best = candidate; + } + } + return best; } +/** A node in the dependency graph: what it provides, what it needs, and where it came from. */ export interface GraphNode { name: string; needs: string[]; @@ -23,15 +42,16 @@ export interface GraphNode { origin: string; } +/** Orders nodes so every dependency precedes its dependents; throws on missing keys or cycles. */ export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] { const producedBy = new Map(); - for (const n of nodes) for (const key of n.provides) producedBy.set(key, n); + for (const node of nodes) for (const key of node.provides) producedBy.set(key, node); // validate dependencies exist - for (const n of nodes) { - for (const key of n.needs) { + for (const node of nodes) { + for (const key of node.needs) { if (!seedKeys.includes(key) && !producedBy.has(key)) { - throw new Error(`missing dependency: ${key} needed by ${n.name}`); + throw new Error(`missing dependency: ${key} needed by ${node.name}`); } } } @@ -39,28 +59,32 @@ export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] { const ordered: GraphNode[] = []; const state = new Map(); - const visit = (n: GraphNode, trail: string[]): void => { - const s = state.get(n); - if (s === 'done') return; - if (s === 'visiting') throw new Error(`cycle detected: ${[...trail, n.name].join(' -> ')}`); - state.set(n, 'visiting'); - for (const key of n.needs) { - const dep = producedBy.get(key); - if (dep && dep !== n) visit(dep, [...trail, n.name]); + const visit = (node: GraphNode, trail: string[]): void => { + const visitState = state.get(node); + if (visitState === 'done') return; + if (visitState === 'visiting') throw new Error(`cycle detected: ${[...trail, node.name].join(' -> ')}`); + state.set(node, 'visiting'); + + for (const key of node.needs) { + const dependency = producedBy.get(key); + if (dependency && dependency !== node) visit(dependency, [...trail, node.name]); } - state.set(n, 'done'); - ordered.push(n); + + state.set(node, 'done'); + ordered.push(node); }; - for (const n of nodes) visit(n, []); + for (const node of nodes) visit(node, []); return ordered; } +/** Filters `ordered` down to the transitive closure of producers reachable from `needs`. */ export function subgraphFor(needs: string[], ordered: GraphNode[]): GraphNode[] { const producedBy = new Map(); - for (const n of ordered) for (const k of n.provides) producedBy.set(k, n); + for (const node of ordered) for (const key of node.provides) producedBy.set(key, node); const inClosure = new Set(); const work = [...needs]; + while (work.length) { const token = work.pop() as string; const node = producedBy.get(token); @@ -68,5 +92,6 @@ export function subgraphFor(needs: string[], ordered: GraphNode[]): GraphNode[] inClosure.add(node); work.push(...node.needs); } - return ordered.filter((n) => inClosure.has(n)); + + return ordered.filter((node) => inClosure.has(node)); } diff --git a/src/http.ts b/src/http.ts deleted file mode 100644 index 4b28355..0000000 --- a/src/http.ts +++ /dev/null @@ -1,316 +0,0 @@ -import http from 'http'; -import https from 'https'; -import { once } from 'events'; -import { channel } from './channel'; -import { errorToResponse } from './transformers'; -import { HttpError, isHttpError } from './signals'; -import { sseEncoder, ndjsonEncoder, StreamEncoder } from './encoders'; -import { isStreamResult, type PipelineResult, type ResponseShape } from './pipeline'; -import type { Transport } from './metadata'; -import type { Bus } from './bus'; -import { buildSecurityHeaders, mergeVary, resolveCors, corsPreflightHeaders } from './security'; -import type { TlsOptions, SecurityOptions, CorsOptions } from './security'; -import { parseMultipart, extractBoundary, collapseDuplicates } from './multipart'; - -export interface RequestLimits { - maxBodyBytes?: number; // default 1_000_000 - requestTimeoutMs?: number; // default 30_000 - headersTimeoutMs?: number; // default 10_000 - keepAliveTimeoutMs?: number; // default 5_000 - maxParts?: number; // default 1000 -} -export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void>; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions; cors?: CorsOptions; bodyDuplicates?: 'array' | 'last' } - -export type RouteHandler = (req: { - method: string; url: string; - headers: Record; - params: Record; - query: Record; - body: unknown; - protocol: 'http' | 'https'; - ip: string; -}) => Promise; - -export interface RouteDef { method: string; pattern: string; transport: Transport; handler: RouteHandler; bodyDuplicates?: 'array' | 'last' } -export interface MatchedRoute { params: Record; def: RouteDef } - -export interface WsOpenCtx { - params: Record; - inbound: AsyncIterable; - abort: AbortSignal; - req: http.IncomingMessage; -} -export interface WsRouteDef { pattern: string; open: (ctx: WsOpenCtx) => Promise> } - -export interface MeshControl { path: string; handle(ws: any, req: http.IncomingMessage): void } - -const PING_MS = 15_000; - -export function matchPattern(pattern: string, path: string): Record | undefined { - const segs = path.split('/').filter(Boolean); - const pat = pattern.split('/').filter(Boolean); - if (pat.length !== segs.length) return undefined; - const params: Record = {}; - for (let i = 0; i < pat.length; i++) { - if (pat[i].startsWith(':')) params[pat[i].slice(1)] = decodeURIComponent(segs[i]); - else if (pat[i] !== segs[i]) return undefined; - } - return params; -} - -export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined { - for (const r of routes) { - if (r.method !== method) continue; - const params = matchPattern(r.pattern, path); - if (params) return { params, def: r }; - } - return undefined; -} - -export function parseQuery(url: string): Record { - const qs = url.split('?')[1] ?? ''; - const out: Record = {}; - for (const [k, v] of new URLSearchParams(qs)) out[k] = v; - return out; -} - -async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise { - const chunks: Buffer[] = []; - let total = 0; - for await (const chunk of req) { - total += (chunk as Buffer).length; - if (total > maxBodyBytes) throw new HttpError(413, 'Payload Too Large'); - chunks.push(chunk as Buffer); - } - return chunks.length === 0 ? undefined : Buffer.concat(chunks); -} - -function firstToken(v: string | string[] | undefined): string | undefined { - const s = Array.isArray(v) ? v[0] : v; - return s?.split(',')[0].trim(); -} -function deriveSecure(req: http.IncomingMessage, trustProxy: boolean): boolean { - if (trustProxy) { const p = firstToken(req.headers['x-forwarded-proto']); if (p) return p === 'https'; } - return (req.socket as any).encrypted === true; -} -function deriveIp(req: http.IncomingMessage, trustProxy: boolean): string { - if (trustProxy) { const f = firstToken(req.headers['x-forwarded-for']); if (f) return f; } - return req.socket.remoteAddress ?? ''; -} - -function pickEncoder(transport: Transport, accept: string): StreamEncoder { - if (transport === 'sse') return sseEncoder; - if (transport === 'ndjson') return ndjsonEncoder; - return accept.includes('text/event-stream') ? sseEncoder : ndjsonEncoder; -} - -async function pipeStream( - res: http.ServerResponse, stream: AsyncIterable, encoder: StreamEncoder, - bus?: Bus, name = '', streams?: Set<() => void>, -): Promise { - res.writeHead(200, encoder.headers); - res.flushHeaders(); // establish the stream immediately so idle-until-event sources (e.g. subscriptions) don't deadlock clients awaiting headers - bus?.emit('stream:open', { name }); - const it = stream[Symbol.asyncIterator](); - let ping: ReturnType | undefined; - if (encoder.ping) { ping = setInterval(() => res.write(encoder.ping!()), PING_MS); ping.unref?.(); } - const stop = () => { if (ping) clearInterval(ping); void Promise.resolve(it.return?.()).catch(() => {}); }; - res.on('close', stop); - const closer = () => { try { res.destroy(); } catch { /* */ } }; - streams?.add(closer); - const onClose = once(res, 'close'); - try { - while (true) { - const { value, done } = await it.next(); - if (done) break; - if (!res.write(encoder.encode(value))) { - await Promise.race([once(res, 'drain'), onClose]); - if (res.destroyed) break; // let finally clean up - } - } - } catch (err) { - bus?.emit('stream:error', { name, error: err }); - const frame = encoder.encodeError(err); - if (frame && !res.writableEnded) res.write(frame); - } finally { - if (ping) clearInterval(ping); - streams?.delete(closer); - if (!res.writableEnded && !res.destroyed) res.end(); - bus?.emit('stream:close', { name }); - } -} - -function loadWss(): any | null { - try { return require('ws').WebSocketServer; } catch { return null; } -} - -function attachWs( - server: http.Server, wsRoutes: WsRouteDef[], bus?: Bus, meshControl?: MeshControl, streams?: Set<() => void>, -): void { - if (wsRoutes.length === 0 && !meshControl) return; - const WSS = loadWss(); - const wss = WSS ? new WSS({ noServer: true }) : null; - server.on('upgrade', (req, socket, head) => { - const path = (req.url ?? '/').split('?')[0]; - if (meshControl && path === meshControl.path) { - if (!wss) { socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n'); socket.destroy(); return; } - wss.handleUpgrade(req, socket, head, (ws: any) => meshControl.handle(ws, req)); - return; - } - const route = wsRoutes.map((r) => ({ r, params: matchPattern(r.pattern, path) })).find((x) => x.params); - if (!route) { socket.destroy(); return; } - if (!wss) { socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n'); socket.destroy(); return; } - wss.handleUpgrade(req, socket, head, async (ws: any) => { - const closer = () => { try { (ws.terminate ?? ws.close).call(ws); } catch { /* */ } }; - streams?.add(closer); - ws.on('close', () => streams?.delete(closer)); - const inbound = channel(); - const ac = new AbortController(); - ws.on('message', (d: Buffer) => inbound.push(d.toString())); - ws.on('close', () => { inbound.close(); ac.abort(); }); - ws.on('error', (e: unknown) => inbound.fail(e)); - - const name = route.r.pattern; - let it: AsyncIterator | undefined; - ws.on('close', () => { void Promise.resolve(it?.return?.()).catch(() => {}); }); // force-cancel outbound - bus?.emit('stream:open', { name }); - try { - const out = await route.r.open({ params: route.params!, inbound, abort: ac.signal, req }); - it = out[Symbol.asyncIterator](); - while (true) { - const { value, done } = await it.next(); - if (done) break; - if (ws.readyState !== 1) break; // 1 = OPEN; stop if socket gone - ws.send(typeof value === 'string' ? value : JSON.stringify(value)); - } - try { ws.close(); } catch { /* already closed */ } - } catch (err) { - bus?.emit('stream:error', { name, error: err }); - if (isHttpError(err)) { - const reason = Buffer.from(String(err.message)).subarray(0, 120).toString(); - try { ws.close(4000 + err.status, reason); } catch { /* already closed */ } - } else { - try { ws.close(1011); } catch { /* already closed */ } - } - } finally { - ac.abort(); - bus?.emit('stream:close', { name }); - } - }); - }); -} - -export function createHttpServer( - routes: RouteDef[], wsRoutes: WsRouteDef[] = [], bus?: Bus, meshControl?: MeshControl, opts?: HttpOptions, -): http.Server { - const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000; - const trustProxy = opts?.trustProxy ?? false; - const handler = async (req: http.IncomingMessage, res: http.ServerResponse): Promise => { - const url = req.url ?? '/'; - const path = url.split('?')[0]; - // Install the security-header patch BEFORE any routing/response so every path - // (200, 404, error, stream) writes headers through the same patched writeHead. - const secure = deriveSecure(req, trustProxy); - const injected: Record = { ...buildSecurityHeaders(opts?.security ?? true, secure) }; - const orig = res.writeHead.bind(res); - (res as any).writeHead = (status: number, arg2?: any, arg3?: any) => { - // normalize (statusMessage?, headers?) overloads - const hdrs = (typeof arg2 === 'string' ? arg3 : arg2) as Record | undefined; - // injected (security/CORS) is authoritative. Node's writeHead does NOT dedupe case-variant - // keys — both lines would ship and a browser honors the first — so drop any handler header - // whose name case-insensitively collides with an injected one before merging. - const merged: Record = {}; - const injectedLower = new Set(Object.keys(injected).map((k) => k.toLowerCase())); - let handlerVary: string | undefined; - if (hdrs) for (const k of Object.keys(hdrs)) { - const lk = k.toLowerCase(); - if (lk === 'vary') { handlerVary = hdrs[k]; continue; } // merged separately below - if (!injectedLower.has(lk)) merged[k] = hdrs[k]; - } - Object.assign(merged, injected); - if (injected['vary']) merged['vary'] = mergeVary(handlerVary, injected['vary']); - else if (handlerVary !== undefined) merged['vary'] = handlerVary; // preserve handler Vary when no CORS - return typeof arg2 === 'string' ? orig(status, arg2, merged) : orig(status, merged); - }; - // CORS is added to `injected` AFTER the patch is installed — the patch reads it lazily - // by reference at writeHead time, so keys added here still land on every response. - if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req)); - if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) { - const pf = corsPreflightHeaders(opts.cors, req); - res.writeHead(204, pf); - res.end(); - return; - } - const matched = matchRoute(routes, req.method ?? 'GET', path); - if (!matched) { - res.writeHead(404, { 'content-type': 'application/json' }); - res.end(JSON.stringify({ error: 'Not Found' })); - return; - } - let buf: Buffer | undefined; - try { - buf = await readBody(req, maxBody); - } catch (error) { - const r = errorToResponse(error); - res.writeHead(r.status, { ...r.headers, connection: 'close' }); - res.end(r.body); - return; - } - let body: unknown; - const ct = String(req.headers['content-type'] ?? ''); - const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last'; - if (buf !== undefined && ct.includes('application/json')) { - try { body = JSON.parse(buf.toString('utf8')); } - catch { - res.writeHead(400, { 'content-type': 'application/json' }); - res.end(JSON.stringify({ error: 'Invalid JSON body' })); - return; - } - } else if (buf !== undefined && ct.includes('application/x-www-form-urlencoded')) { - body = collapseDuplicates(new URLSearchParams(buf.toString('utf8')), duplicates); - } else if (buf !== undefined && ct.includes('multipart/form-data')) { - const boundary = extractBoundary(ct); - if (!boundary) { - res.writeHead(400, { 'content-type': 'application/json' }); - res.end(JSON.stringify({ error: 'Invalid multipart body' })); - return; - } - try { body = parseMultipart(buf, boundary, { maxParts: opts?.limits?.maxParts ?? 1000, duplicates }); } - catch { - res.writeHead(400, { 'content-type': 'application/json' }); - res.end(JSON.stringify({ error: 'Invalid multipart body' })); - return; - } - } else { - const s = buf?.toString('utf8'); - body = s === '' ? undefined : s; - } - let result: PipelineResult; - try { - result = await matched.def.handler({ - method: req.method ?? 'GET', url, headers: req.headers, - params: matched.params, query: parseQuery(url), body, - protocol: secure ? 'https' : 'http', ip: deriveIp(req, trustProxy), - }); - } catch (error) { - result = errorToResponse(error); - } - if (isStreamResult(result)) { - const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? '')); - await pipeStream(res, result.stream, encoder, bus, matched.def.pattern, opts?.streams); - return; - } - const r: ResponseShape = result; - res.writeHead(r.status, r.headers); - res.end(r.body); - }; - // runtime-compatible; only @types differ (https.Server lacks the http-only timeout props) - const server: http.Server = (opts?.tls - ? https.createServer(opts.tls as https.ServerOptions, handler) - : http.createServer(handler)) as unknown as http.Server; - server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000; - server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000; - server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000; - attachWs(server, wsRoutes, bus, meshControl, opts?.streams); - return server; -} diff --git a/src/http/index.ts b/src/http/index.ts new file mode 100644 index 0000000..afea4d6 --- /dev/null +++ b/src/http/index.ts @@ -0,0 +1,14 @@ +// Public surface of the HTTP module. Internal helpers (request parsing, streaming, +// ws upgrade) live in sibling files and are composed by ./server. +export type { + RequestLimits, + HttpOptions, + RouteHandler, + RouteDef, + MatchedRoute, + WsOpenCtx, + WsRouteDef, + MeshControl, +} from './types'; +export { matchPattern, matchRoute, parseQuery } from './router'; +export { createHttpServer } from './server'; diff --git a/src/http/request.ts b/src/http/request.ts new file mode 100644 index 0000000..2eef0cd --- /dev/null +++ b/src/http/request.ts @@ -0,0 +1,42 @@ +import http from 'http'; +import { HttpError } from '../signals'; + +/** Reads the full request body, enforcing the max-bytes ceiling (throws 413 if exceeded). */ +export async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise { + const chunks: Buffer[] = []; + let total = 0; + + for await (const chunk of req) { + total += (chunk as Buffer).length; + if (total > maxBodyBytes) throw new HttpError(413, 'Payload Too Large'); + chunks.push(chunk as Buffer); + } + + return chunks.length === 0 ? undefined : Buffer.concat(chunks); +} + +/** Returns the first comma-separated token of a header value (handles array-valued headers). */ +function firstToken(value: string | string[] | undefined): string | undefined { + const first = Array.isArray(value) ? value[0] : value; + return first?.split(',')[0].trim(); +} + +/** Determines whether the request arrived over HTTPS, honoring `x-forwarded-proto` when proxy is trusted. */ +export function deriveSecure(req: http.IncomingMessage, trustProxy: boolean): boolean { + if (trustProxy) { + const proto = firstToken(req.headers['x-forwarded-proto']); + if (proto) return proto === 'https'; + } + + return (req.socket as any).encrypted === true; +} + +/** Resolves the client IP, honoring `x-forwarded-for` when proxy is trusted. */ +export function deriveIp(req: http.IncomingMessage, trustProxy: boolean): string { + if (trustProxy) { + const forwarded = firstToken(req.headers['x-forwarded-for']); + if (forwarded) return forwarded; + } + + return req.socket.remoteAddress ?? ''; +} diff --git a/src/http/router.ts b/src/http/router.ts new file mode 100644 index 0000000..6b7aedf --- /dev/null +++ b/src/http/router.ts @@ -0,0 +1,92 @@ +import type { RouteDef, MatchedRoute } from './types'; + +/** + * Matches a route pattern against a request path. Supports static segments, `:param` (one segment), + * and a trailing `:name*` catch-all that captures the rest of the path (slashes included) into `params.name`. + * @returns Extracted params (decoded) when the path matches, otherwise undefined. + */ +export function matchPattern(pattern: string, path: string): Record | undefined { + const pathSegs = path.split('/').filter(Boolean); + const patternSegs = pattern.split('/').filter(Boolean); + const params: Record = {}; + + for (let i = 0; i < patternSegs.length; i++) { + const seg = patternSegs[i]; + + // Trailing catch-all: capture every remaining segment (possibly none) as one decoded value. + if (seg.startsWith(':') && seg.endsWith('*')) { + params[seg.slice(1, -1)] = pathSegs.slice(i).map(decodeURIComponent).join('/'); + return params; + } + + if (i >= pathSegs.length) return undefined; // pattern longer than path + + if (seg.startsWith(':')) params[seg.slice(1)] = decodeURIComponent(pathSegs[i]); + else if (seg !== pathSegs[i]) return undefined; + } + + // No catch-all consumed the tail, so the lengths must match exactly. + return patternSegs.length === pathSegs.length ? params : undefined; +} + +/** Splits a pattern into its fixed-prefix segment kinds (2 = static, 1 = param) and whether it ends in a catch-all. */ +function segScores(pattern: string): { catchAll: boolean; kinds: number[] } { + const kinds: number[] = []; + + for (const seg of pattern.split('/').filter(Boolean)) { + if (seg.startsWith(':') && seg.endsWith('*')) return { catchAll: true, kinds }; + kinds.push(seg.startsWith(':') ? 1 : 2); + } + + return { catchAll: false, kinds }; +} + +/** Orders two matching patterns by specificity: exact beats catch-all, then static beats param, then longer wins. */ +function moreSpecific(a: string, b: string): number { + const scoreA = segScores(a); + const scoreB = segScores(b); + if (scoreA.catchAll !== scoreB.catchAll) return scoreA.catchAll ? -1 : 1; + const length = Math.max(scoreA.kinds.length, scoreB.kinds.length); + + for (let i = 0; i < length; i++) { + const kindA = scoreA.kinds[i] ?? -1; + const kindB = scoreB.kinds[i] ?? -1; + if (kindA !== kindB) return kindA - kindB; + } + + return 0; +} + +/** Finds the most specific route matching both method and path (static > param > catch-all; ties keep registration order). */ +export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined { + let best: MatchedRoute | undefined; + let bestPattern = ''; + + for (const route of routes) { + if (route.method !== method) continue; + const params = matchPattern(route.pattern, path); + if (!params) continue; + + if (!best || moreSpecific(route.pattern, bestPattern) > 0) { + best = { params, def: route }; + bestPattern = route.pattern; + } + } + + return best; +} + +/** Lists the distinct HTTP methods whose pattern matches the path — used to build a 405 `Allow` header. */ +export function allowedMethods(routes: RouteDef[], path: string): string[] { + const methods = new Set(); + for (const route of routes) if (matchPattern(route.pattern, path)) methods.add(route.method); + return [...methods]; +} + +/** Parses a URL's query string into a flat string map (last value wins for repeated keys). */ +export function parseQuery(url: string): Record { + const queryString = url.split('?')[1] ?? ''; + const out: Record = {}; + for (const [key, value] of new URLSearchParams(queryString)) out[key] = value; + return out; +} diff --git a/src/http/server.ts b/src/http/server.ts new file mode 100644 index 0000000..eb3a327 --- /dev/null +++ b/src/http/server.ts @@ -0,0 +1,242 @@ +import http from 'http'; +import https from 'https'; +import { errorToResponse } from '../transformers'; +import { isHttpError } from '../signals'; +import { isStreamResult, type PipelineResult, type ResponseShape } from '../pipeline'; +import type { Bus } from '../bus'; +import { buildSecurityHeaders, mergeVary, resolveCors, corsPreflightHeaders } from '../security'; +import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart'; +import { matchRoute, allowedMethods, parseQuery } from './router'; +import { readBody, deriveSecure, deriveIp } from './request'; +import { pickEncoder, pipeStream } from './stream'; +import { attachWs } from './ws'; +import type { RouteDef, WsRouteDef, MatchedRoute, MeshControl, HttpOptions } from './types'; + +interface HandlerConfig { + routes: RouteDef[]; + bus?: Bus; + opts?: HttpOptions; + maxBody: number; + trustProxy: boolean; +} + +/** A ready-to-send error response produced while acquiring the request body. */ +type BodyFailure = { fail: { status: number; headers: Record; body: string } }; + +/** + * Builds an HTTP/HTTPS server that routes requests, parses bodies, streams results, and handles WebSocket upgrades. + * @param routes HTTP route definitions. + * @param wsRoutes WebSocket route definitions (requires the optional `ws` peer dependency). + * @param bus Optional event bus for stream lifecycle events. + * @param meshControl Optional mesh gateway hook for a reserved upgrade path. + * @param opts Limits, TLS, security, CORS, and body-parsing options. + */ +export function createHttpServer( + routes: RouteDef[], + wsRoutes: WsRouteDef[] = [], + bus?: Bus, + meshControl?: MeshControl, + opts?: HttpOptions, +): http.Server { + const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000; + const trustProxy = opts?.trustProxy ?? false; + const handler = createRequestHandler({ routes, bus, opts, maxBody, trustProxy }); + + // runtime-compatible; only @types differ (https.Server lacks the http-only timeout props) + const server: http.Server = (opts?.tls + ? https.createServer(opts.tls as https.ServerOptions, handler) + : http.createServer(handler)) as unknown as http.Server; + server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000; + server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000; + server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000; + attachWs(server, wsRoutes, bus, meshControl, opts?.streams); + return server; +} + +/** Builds the request listener: security/CORS headers, routing, body parsing, then buffered or streamed response. */ +function createRequestHandler(cfg: HandlerConfig) { + const { routes, bus, opts, maxBody, trustProxy } = cfg; + + return async (req: http.IncomingMessage, res: http.ServerResponse): Promise => { + const url = req.url ?? '/'; + const path = url.split('?')[0]; + // Install the security-header patch BEFORE any routing/response so every path + // (200, 404, error, stream) writes headers through the same patched writeHead. + const secure = deriveSecure(req, trustProxy); + const injected: Record = { ...buildSecurityHeaders(opts?.security ?? true, secure) }; + patchResponseHeaders(res, injected); + + // CORS is added to `injected` AFTER the patch is installed — the patch reads it lazily + // by reference at writeHead time, so keys added here still land on every response. + if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req)); + + if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) { + res.writeHead(204, corsPreflightHeaders(opts.cors, req)); + res.end(); + return; + } + + const matched = matchRoute(routes, req.method ?? 'GET', path); + + if (!matched) { + // Path matches a route under a different method → 405 with Allow; otherwise 404. + const allow = allowedMethods(routes, path); + + if (allow.length) { + res.writeHead(405, { 'content-type': 'application/json', allow: allow.join(', ') }); + res.end(JSON.stringify({ error: 'Method Not Allowed' })); + return; + } + + res.writeHead(404, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ error: 'Not Found' })); + return; + } + + const acquired = await acquireBody(req, matched, opts, maxBody); + + if ('fail' in acquired) { + res.writeHead(acquired.fail.status, acquired.fail.headers); + res.end(acquired.fail.body); + return; + } + + let result: PipelineResult; + + try { + result = await matched.def.handler({ + method: req.method ?? 'GET', + url, + headers: req.headers, + params: matched.params, + query: parseQuery(url), + body: acquired.body, + protocol: secure ? 'https' : 'http', + ip: deriveIp(req, trustProxy), + }); + } catch (error) { + result = errorToResponse(error); + } + + if (isStreamResult(result)) { + const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? '')); + await pipeStream(res, result.stream, encoder, bus, matched.def.pattern, opts?.streams); + return; + } + + const response: ResponseShape = result; + res.writeHead(response.status, response.headers); + res.end(response.body); + }; +} + +/** Reads and parses the request body, returning `{ body }` or a ready-to-send `{ fail }` error response. */ +async function acquireBody( + req: http.IncomingMessage, + matched: MatchedRoute, + opts: HttpOptions | undefined, + maxBody: number, +): Promise<{ body: unknown } | BodyFailure> { + let buf: Buffer | undefined; + + try { + buf = await readBody(req, maxBody); + } catch (error) { + const response = errorToResponse(error); + return { + fail: { status: response.status, headers: { ...response.headers, connection: 'close' }, body: response.body }, + }; + } + + const contentType = String(req.headers['content-type'] ?? ''); + const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last'; + const parsed = await parseRequestBody(buf, contentType, duplicates, opts?.limits?.maxParts ?? 1000); + + if ('error' in parsed) { + return { + fail: { + status: parsed.status ?? 400, + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ error: parsed.error }), + }, + }; + } + + return { body: parsed.body }; +} + +/** + * Monkey-patches `res.writeHead` so injected (security/CORS) headers are authoritative on every response. + * Handler headers that case-insensitively collide with an injected key are dropped; `Vary` is merged. + * Reads `injected` by reference, so CORS keys added after installation still land. + */ +function patchResponseHeaders(res: http.ServerResponse, injected: Record): void { + const origWriteHead = res.writeHead.bind(res); + + (res as any).writeHead = (status: number, arg2?: any, arg3?: any) => { + // normalize (statusMessage?, headers?) overloads + const handlerHeaders = (typeof arg2 === 'string' ? arg3 : arg2) as Record | undefined; + const merged: Record = {}; + const injectedLower = new Set(Object.keys(injected).map((key) => key.toLowerCase())); + let handlerVary: string | undefined; + + if (handlerHeaders) + for (const key of Object.keys(handlerHeaders)) { + const lowerKey = key.toLowerCase(); + + if (lowerKey === 'vary') { + handlerVary = handlerHeaders[key]; + continue; + } // merged separately below + + if (!injectedLower.has(lowerKey)) merged[key] = handlerHeaders[key]; + } + + Object.assign(merged, injected); + if (injected['vary']) merged['vary'] = mergeVary(handlerVary, injected['vary']); + else if (handlerVary !== undefined) merged['vary'] = handlerVary; // preserve handler Vary when no CORS + return typeof arg2 === 'string' ? origWriteHead(status, arg2, merged) : origWriteHead(status, merged); + }; +} + +/** Parse outcome: the decoded body, or an error message plus the status to send (400 unless set). */ +type ParseResult = { body: unknown } | { error: string; status?: number }; + +/** + * Parses a raw request body by content type (JSON, urlencoded, multipart, or plain text). + * @returns `{ body }` on success, or `{ error, status? }` on malformed input / missing multipart support. + */ +async function parseRequestBody( + buf: Buffer | undefined, + contentType: string, + duplicates: 'array' | 'last', + maxParts: number, +): Promise { + if (buf !== undefined && contentType.includes('application/json')) { + try { + return { body: JSON.parse(buf.toString('utf8')) }; + } catch { + return { error: 'Invalid JSON body' }; + } + } + + if (buf !== undefined && contentType.includes('application/x-www-form-urlencoded')) { + return { body: collapseDuplicates(new URLSearchParams(buf.toString('utf8')), duplicates) }; + } + + if (buf !== undefined && contentType.includes('multipart/form-data')) { + const boundary = extractBoundary(contentType); + if (!boundary) return { error: 'Invalid multipart body' }; + + try { + return { body: await parseMultipart(buf, boundary, { maxParts, duplicates }) }; + } catch (error) { + // HttpError = the busboy peer dep is missing (501); anything else = malformed input (400). + if (isHttpError(error)) return { error: error.message, status: error.status }; + return { error: 'Invalid multipart body' }; + } + } + + const text = buf?.toString('utf8'); + return { body: text === '' ? undefined : text }; +} diff --git a/src/http/stream.ts b/src/http/stream.ts new file mode 100644 index 0000000..1239459 --- /dev/null +++ b/src/http/stream.ts @@ -0,0 +1,74 @@ +import http from 'http'; +import { once } from 'events'; +import { sseEncoder, ndjsonEncoder, StreamEncoder } from '../encoders'; +import type { Transport } from '../metadata'; +import type { Bus } from '../bus'; + +const PING_MS = 15_000; + +/** Selects the stream encoder for a transport, falling back to the client's `Accept` header for `stream`. */ +export function pickEncoder(transport: Transport, accept: string): StreamEncoder { + if (transport === 'sse') return sseEncoder; + if (transport === 'ndjson') return ndjsonEncoder; + return accept.includes('text/event-stream') ? sseEncoder : ndjsonEncoder; +} + +/** Pipes an async-iterable result to the response as an HTTP stream, with keep-alive pings and backpressure handling. */ +export async function pipeStream( + res: http.ServerResponse, + stream: AsyncIterable, + encoder: StreamEncoder, + bus?: Bus, + name = '', + streams?: Set<() => void>, +): Promise { + res.writeHead(200, encoder.headers); + res.flushHeaders(); // establish the stream immediately so idle-until-event sources (e.g. subscriptions) don't deadlock clients awaiting headers + bus?.emit('stream:open', { name }); + const iterator = stream[Symbol.asyncIterator](); + let ping: ReturnType | undefined; + + if (encoder.ping) { + ping = setInterval(() => res.write(encoder.ping!()), PING_MS); + ping.unref?.(); + } + + const stop = () => { + if (ping) clearInterval(ping); + void Promise.resolve(iterator.return?.()).catch(() => {}); + }; + + res.on('close', stop); + + const closer = () => { + try { + res.destroy(); + } catch { + /* */ + } + }; + + streams?.add(closer); + const onClose = once(res, 'close'); + + try { + while (true) { + const { value, done } = await iterator.next(); + if (done) break; + + if (!res.write(encoder.encode(value))) { + await Promise.race([once(res, 'drain'), onClose]); + if (res.destroyed) break; // let finally clean up + } + } + } catch (err) { + bus?.emit('stream:error', { name, error: err }); + const frame = encoder.encodeError(err); + if (frame && !res.writableEnded) res.write(frame); + } finally { + if (ping) clearInterval(ping); + streams?.delete(closer); + if (!res.writableEnded && !res.destroyed) res.end(); + bus?.emit('stream:close', { name }); + } +} diff --git a/src/http/types.ts b/src/http/types.ts new file mode 100644 index 0000000..2afa1a0 --- /dev/null +++ b/src/http/types.ts @@ -0,0 +1,71 @@ +import http from 'http'; +import type { Transport } from '../metadata'; +import type { PipelineResult } from '../pipeline'; +import type { TlsOptions, SecurityOptions, CorsOptions } from '../security'; + +/** Per-request size and timeout ceilings applied by the server. */ +export interface RequestLimits { + maxBodyBytes?: number; // default 1_000_000 + requestTimeoutMs?: number; // default 30_000 + headersTimeoutMs?: number; // default 10_000 + keepAliveTimeoutMs?: number; // default 5_000 + maxParts?: number; // default 1000 +} + +/** Options controlling server construction: limits, TLS, proxy trust, security headers, CORS, and body parsing. */ +export interface HttpOptions { + limits?: RequestLimits; + streams?: Set<() => void>; + tls?: TlsOptions; + trustProxy?: boolean; + security?: boolean | SecurityOptions; + cors?: CorsOptions; + bodyDuplicates?: 'array' | 'last'; +} + +/** Handler for a matched HTTP route; receives a normalized request and resolves to a pipeline result. */ +export type RouteHandler = (req: { + method: string; + url: string; + headers: Record; + params: Record; + query: Record; + body: unknown; + protocol: 'http' | 'https'; + ip: string; +}) => Promise; + +/** A registered HTTP route: method, path pattern, streaming transport, and handler. */ +export interface RouteDef { + method: string; + pattern: string; + transport: Transport; + handler: RouteHandler; + bodyDuplicates?: 'array' | 'last'; +} + +/** Result of matching a request path against a route: extracted params plus the matched definition. */ +export interface MatchedRoute { + params: Record; + def: RouteDef; +} + +/** Context passed to a WebSocket route's `open`: path params, inbound message stream, abort signal, and raw request. */ +export interface WsOpenCtx { + params: Record; + inbound: AsyncIterable; + abort: AbortSignal; + req: http.IncomingMessage; +} + +/** A registered WebSocket route: path pattern and an `open` that returns the outbound message stream. */ +export interface WsRouteDef { + pattern: string; + open: (ctx: WsOpenCtx) => Promise>; +} + +/** Hook for a mesh gateway to take over WebSocket upgrades on a fixed path. */ +export interface MeshControl { + path: string; + handle(ws: any, req: http.IncomingMessage): void; +} diff --git a/src/http/ws.ts b/src/http/ws.ts new file mode 100644 index 0000000..a2736fe --- /dev/null +++ b/src/http/ws.ts @@ -0,0 +1,180 @@ +import http from 'http'; +import { channel } from '../channel'; +import { isHttpError } from '../signals'; +import type { Bus } from '../bus'; +import { matchPattern } from './router'; +import type { WsRouteDef, MeshControl } from './types'; + +/** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */ +function loadWss(): any | null { + try { + // `ws` is an OPTIONAL peer dependency: lazy-required so installs without WebSocket + // support don't fail. When absent this throws and we fall back to null (501 on upgrade). + // eslint-disable-next-line @typescript-eslint/no-require-imports + return require('ws').WebSocketServer; + } catch { + return null; + } +} + +/** Writes a 501 Not Implemented status to the raw socket and destroys it. */ +function reject501(socket: any): void { + socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n'); + socket.destroy(); +} + +/** Handles the mesh-control upgrade path; returns true when the request was for the mesh control endpoint. */ +function handleMeshUpgrade( + wss: any, + meshControl: MeshControl, + path: string, + req: http.IncomingMessage, + socket: any, + head: Buffer, +): boolean { + if (path !== meshControl.path) return false; + + if (!wss) { + reject501(socket); + return true; + } + + wss.handleUpgrade(req, socket, head, (ws: any) => meshControl.handle(ws, req)); + return true; +} + +/** Finds the first ws route whose pattern matches `path`, capturing its params. */ +function matchWsRoute( + wsRoutes: WsRouteDef[], + path: string, +): { def: WsRouteDef; params: Record | undefined } | undefined { + return wsRoutes + .map((candidate) => ({ def: candidate, params: matchPattern(candidate.pattern, path) })) + .find((entry) => entry.params); +} + +/** Wires inbound message/close/error events into a channel and returns the channel plus its abort controller. */ +function wireInbound(ws: any): { inbound: ReturnType>; abortController: AbortController } { + const inbound = channel(); + const abortController = new AbortController(); + ws.on('message', (data: Buffer) => inbound.push(data.toString())); + ws.on('close', () => { + inbound.close(); + abortController.abort(); + }); + ws.on('error', (err: unknown) => inbound.fail(err)); + + return { inbound, abortController }; +} + +/** Registers the connection with the stream registry so it can be force-closed on shutdown. */ +function trackConnection(ws: any, streams?: Set<() => void>): void { + const closer = () => { + try { + (ws.terminate ?? ws.close).call(ws); + } catch { + /* */ + } + }; + + streams?.add(closer); + ws.on('close', () => streams?.delete(closer)); +} + +/** Drives the outbound async iterator, sending each yielded value over the socket until done or closed. */ +async function pumpOutbound(ws: any, iterator: AsyncIterator): Promise { + while (true) { + const { value, done } = await iterator.next(); + if (done) break; + if (ws.readyState !== 1) break; // 1 = OPEN; stop if socket gone + ws.send(typeof value === 'string' ? value : JSON.stringify(value)); + } + + try { + ws.close(); + } catch { + /* already closed */ + } +} + +/** Closes the socket with the appropriate code after an outbound error (4000+status for HTTP errors, 1011 otherwise). */ +function closeOnError(ws: any, err: unknown): void { + if (isHttpError(err)) { + const reason = Buffer.from(String(err.message)).subarray(0, 120).toString(); + + try { + ws.close(4000 + err.status, reason); + } catch { + /* already closed */ + } + } else { + try { + ws.close(1011); + } catch { + /* already closed */ + } + } +} + +/** Runs the full per-connection lifecycle: inbound wiring, opening the route stream, and pumping outbound values. */ +async function openWsConnection( + ws: any, + route: { def: WsRouteDef; params: Record | undefined }, + req: http.IncomingMessage, + bus?: Bus, + streams?: Set<() => void>, +): Promise { + trackConnection(ws, streams); + const { inbound, abortController } = wireInbound(ws); + + const name = route.def.pattern; + let iterator: AsyncIterator | undefined; + ws.on('close', () => { + void Promise.resolve(iterator?.return?.()).catch(() => {}); + }); // force-cancel outbound + bus?.emit('stream:open', { name }); + + try { + const outbound = await route.def.open({ params: route.params!, inbound, abort: abortController.signal, req }); + iterator = outbound[Symbol.asyncIterator](); + await pumpOutbound(ws, iterator); + } catch (err) { + bus?.emit('stream:error', { name, error: err }); + closeOnError(ws, err); + } finally { + abortController.abort(); + bus?.emit('stream:close', { name }); + } +} + +/** Attaches WebSocket upgrade handling to the server: routes to `wsRoutes` or a mesh control path. */ +export function attachWs( + server: http.Server, + wsRoutes: WsRouteDef[], + bus?: Bus, + meshControl?: MeshControl, + streams?: Set<() => void>, +): void { + if (wsRoutes.length === 0 && !meshControl) return; + const WebSocketServer = loadWss(); + const wss = WebSocketServer ? new WebSocketServer({ noServer: true }) : null; + server.on('upgrade', (req, socket, head) => { + const path = (req.url ?? '/').split('?')[0]; + + if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head)) return; + + const route = matchWsRoute(wsRoutes, path); + + if (!route) { + socket.destroy(); + return; + } + + if (!wss) { + reject501(socket); + return; + } + + wss.handleUpgrade(req, socket, head, (ws: any) => openWsConnection(ws, route, req, bus, streams)); + }); +} diff --git a/src/index.ts b/src/index.ts index b7e7be5..162f748 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,32 +1,53 @@ +/** + * @green-tea/core — a decorator-driven, type-safe HTTP framework. + * Public API barrel: application bootstrap, routing/DI decorators, streaming, + * request validation, security helpers, and the cross-server mesh. + */ import 'reflect-metadata'; -export const VERSION = '0.0.0'; +/** Package version, replaced at publish time. */ +export const VERSION = '26.07.0-beta.0'; + +// Application export { createApp } from './app'; -export type { App, InspectLine, Explain } from './app'; +export type { App, InspectLine, Explain, MeshConfig } from './app'; + +// Graph visualization export { toMermaid, toDOT } from './graph-viz'; export type { GraphView } from './graph-viz'; -export { Provider, Step, Route, Get, Module, Transformer } from './metadata'; + +// Routing & decorators +export { Provider, Step, Route, Get, Module, Transformer, Sse, Ws, Stream, Post, Put, Patch, Delete } from './metadata'; +export type { Transport, HttpMethod } from './metadata'; export type { Plugin } from './plugin'; + +// Transformers & error signals export { JsonTransformer } from './transformers'; export { HttpError, Unauthorized, NotFound, Redirect, NotModified, ValidationError } from './signals'; + +// Bus & flow export { Bus } from './bus'; export { flow, Flow } from './flow'; export type { StepFn, CompiledFlow } from './flow'; -export { needs, ctx, param, query, body, headers } from './params'; + +// Parameter decorators +export { needs, ctx, param, query, body, headers, header, inbound, abort } from './params'; export type { Query, Headers, Context, ArgSpec } from './params'; + +// Streaming export { channel, isAsyncIterable } from './channel'; export type { Channel } from './channel'; export { Rooms } from './rooms'; -export { Sse, Ws, Stream, Post, Put, Patch, Delete } from './metadata'; -export type { Transport, HttpMethod } from './metadata'; -export { inbound, abort } from './params'; export { sseEncoder, ndjsonEncoder } from './encoders'; export type { StreamEncoder } from './encoders'; -export type { MeshConfig } from './app'; + +// HTTP, security & validation export type { RequestLimits } from './http'; export type { TlsOptions, CorsOptions, SecurityOptions } from './security'; export type { UploadedFile, MultipartBody } from './multipart'; export type { StandardSchemaV1 } from './standard-schema'; + +// Mesh export { connectLink } from './mesh/link'; export { buildRemote, envelopeFrom } from './mesh/teacup'; export { buildManifest, createMeshControl, MESH_CONTROL_PATH } from './mesh/teapot'; diff --git a/src/mesh/link.ts b/src/mesh/link.ts index 10105d6..397364a 100644 --- a/src/mesh/link.ts +++ b/src/mesh/link.ts @@ -4,30 +4,105 @@ import { encode, decode, type Manifest, type RequestEnvelope, type Frame } from let connSeq = 0; // module-level: deterministic unique connection-id prefix (no Date.now/Math.random) +/** Client handle to a remote mesh server: its manifest, an RPC caller, and a close(). */ export interface Link { manifest: Manifest; rpc(kind: 'scope' | 'route', name: string, ctx: RequestEnvelope): Promise; close(): void; } +/** An in-flight RPC awaiting its `rpc-res`, keyed by id in the pending map. */ +type PendingEntry = { + resolve: (v: unknown) => void; + reject: (e: unknown) => void; + timer: ReturnType; +}; + function loadWs(): any { - return require('ws'); // lazy/optional, like streams; the ws CJS export is the WebSocket class + // lazy/optional, like streams; the ws CJS export is the WebSocket class + // eslint-disable-next-line @typescript-eslint/no-require-imports + return require('ws'); } -export function connectLink(args: { - url: string; - secret: string; - timeoutMs?: number; - bus?: Bus; -}): Promise { +/** Reject and clear every in-flight RPC — used when the link closes. */ +function rejectAllPending(pending: Map, reason: string): void { + for (const [, entry] of pending) { + clearTimeout(entry.timer); + entry.reject(new Error(reason)); + } + + pending.clear(); +} + +/** Register one RPC in `pending` by id, send its request, and reject it on timeout. */ +function sendRpc( + ws: any, + pending: Map, + id: string, + kind: 'scope' | 'route', + name: string, + ctx: RequestEnvelope, + timeoutMs: number, +): Promise { + return new Promise((resolveCall, rejectCall) => { + const timer = setTimeout(() => { + pending.delete(id); + rejectCall(new Error(`mesh rpc timeout: ${name}`)); + }, timeoutMs); + + pending.set(id, { resolve: resolveCall, reject: rejectCall, timer }); + ws.send(encode({ type: 'rpc-req', id, kind, name, ctx })); + }); +} + +/** Assemble the client-facing Link once the manifest arrives. */ +function buildLink( + ws: any, + pending: Map, + manifest: Manifest, + connId: string, + timeoutMs: number, +): Link { + let counter = 0; + + return { + manifest, + rpc(kind, name, ctx) { + const id = `${connId}:${counter++}`; + + return sendRpc(ws, pending, id, kind, name, ctx, timeoutMs); + }, + close() { + ws.close(); + }, + }; +} + +/** Settle a pending RPC from its `rpc-res` frame — resolve on ok, reject (and emit) on error. */ +function settleRpcResponse( + pending: Map, + frame: Extract, + bus?: Bus, +): void { + const entry = pending.get(frame.id); + if (!entry) return; + pending.delete(frame.id); + clearTimeout(entry.timer); + + if (frame.ok) { + entry.resolve(frame.result); + } else { + bus?.emit('mesh:rpc:error', { name: frame.id, error: frame.error }); + entry.reject(new HttpError(frame.error.status ?? 500, frame.error.message)); + } +} + +/** Open a WebSocket link to a mesh server, handshake with `secret`, and resolve once its manifest arrives. */ +export function connectLink(args: { url: string; secret: string; timeoutMs?: number; bus?: Bus }): Promise { const timeoutMs = args.timeoutMs ?? 30_000; const WS = loadWs(); const ws = new WS(args.url); - const pending = new Map< - string, - { resolve: (v: unknown) => void; reject: (e: unknown) => void; timer: ReturnType } - >(); - let counter = 0; + const pending = new Map(); const connId = `c${connSeq++}`; let manifest: Manifest | undefined; @@ -38,20 +113,17 @@ export function connectLink(args: { }, timeoutMs); ws.on('open', () => ws.send(encode({ type: 'hello', secret: args.secret }))); - ws.on('error', (e: unknown) => reject(e)); + ws.on('error', (error: unknown) => reject(error)); ws.on('close', () => { clearTimeout(connectTimer); args.bus?.emit('mesh:disconnect', { name: args.url }); - for (const [, p] of pending) { - clearTimeout(p.timer); - p.reject(new Error('mesh link closed')); - } - pending.clear(); + rejectAllPending(pending, 'mesh link closed'); if (!manifest) reject(new Error(`mesh handshake failed: ${args.url}`)); }); ws.on('message', (data: unknown) => { let frame: Frame; + try { frame = decode(String(data)); } catch { @@ -62,37 +134,12 @@ export function connectLink(args: { manifest = { scopes: frame.scopes, routes: frame.routes }; clearTimeout(connectTimer); args.bus?.emit('mesh:connect', { name: args.url }); - resolve({ - manifest, - rpc(kind, name, ctx) { - const id = `${connId}:${counter++}`; - return new Promise((res, rej) => { - const timer = setTimeout(() => { - pending.delete(id); - rej(new Error(`mesh rpc timeout: ${name}`)); - }, timeoutMs); - pending.set(id, { resolve: res, reject: rej, timer }); - ws.send(encode({ type: 'rpc-req', id, kind, name, ctx })); - }); - }, - close() { - ws.close(); - }, - }); + resolve(buildLink(ws, pending, manifest, connId, timeoutMs)); return; } if (frame.type === 'rpc-res') { - const p = pending.get(frame.id); - if (!p) return; - pending.delete(frame.id); - clearTimeout(p.timer); - if (frame.ok) { - p.resolve(frame.result); - } else { - args.bus?.emit('mesh:rpc:error', { name: frame.id, error: frame.error }); - p.reject(new HttpError(frame.error.status ?? 500, frame.error.message)); - } + settleRpcResponse(pending, frame, args.bus); } }); }); diff --git a/src/mesh/protocol.ts b/src/mesh/protocol.ts index b37d242..e2731b2 100644 --- a/src/mesh/protocol.ts +++ b/src/mesh/protocol.ts @@ -1,3 +1,4 @@ +/** Serialized request context sent across the mesh for a scope or route RPC. */ export interface RequestEnvelope { method: string; params: Record; @@ -6,10 +7,23 @@ export interface RequestEnvelope { headers: Record; } -export interface ScopeEntry { token: string; scope: 'app' | 'request' } -export interface RouteEntry { method: string; pattern: string } -export interface Manifest { scopes: ScopeEntry[]; routes: RouteEntry[] } +/** Manifest entry for an exported scope token and its lifetime. */ +export interface ScopeEntry { + token: string; + scope: 'app' | 'request'; +} +/** Manifest entry for an exported route. */ +export interface RouteEntry { + method: string; + pattern: string; +} +/** A mesh server's advertised scopes and routes. */ +export interface Manifest { + scopes: ScopeEntry[]; + routes: RouteEntry[]; +} +/** Discriminated union of every message on the mesh wire. */ export type Frame = | { type: 'hello'; secret: string } | { type: 'manifest'; scopes: ScopeEntry[]; routes: RouteEntry[] } @@ -19,14 +33,18 @@ export type Frame = const TYPES = new Set(['hello', 'manifest', 'rpc-req', 'rpc-res']); -export function encode(f: Frame): string { - return JSON.stringify(f); +/** Serialize a frame to a JSON wire string. */ +export function encode(frame: Frame): string { + return JSON.stringify(frame); } -export function decode(s: string): Frame { - const f = JSON.parse(s) as { type?: unknown }; - if (typeof f.type !== 'string' || !TYPES.has(f.type)) { - throw new Error(`unknown frame type: ${String(f.type)}`); +/** Parse a wire string into a frame, throwing if the `type` tag is unknown. */ +export function decode(json: string): Frame { + const parsed = JSON.parse(json) as { type?: unknown }; + + if (typeof parsed.type !== 'string' || !TYPES.has(parsed.type)) { + throw new Error(`unknown frame type: ${String(parsed.type)}`); } - return f as Frame; + + return parsed as Frame; } diff --git a/src/mesh/teacup.ts b/src/mesh/teacup.ts index 39fe36c..0e0870e 100644 --- a/src/mesh/teacup.ts +++ b/src/mesh/teacup.ts @@ -2,9 +2,19 @@ import type { Link } from './link'; import type { RequestEnvelope } from './protocol'; import type { ResponseShape } from '../pipeline'; -export interface RemoteScopeNode { name: string; run: (ctx: any) => Promise> } -export interface RemoteRoute { method: string; pattern: string; handler: (req: RequestEnvelope) => Promise } +/** Local proxy for a remote scope: runs the RPC and returns its token→value binding. */ +export interface RemoteScopeNode { + name: string; + run: (ctx: any) => Promise>; +} +/** Local proxy for a remote route: forwards the request envelope over the link. */ +export interface RemoteRoute { + method: string; + pattern: string; + handler: (req: RequestEnvelope) => Promise; +} +/** Extract a {@link RequestEnvelope} from a local request context for transmission over the mesh. */ export function envelopeFrom(ctx: any): RequestEnvelope { return { method: ctx?.req?.method ?? ctx?.method ?? 'GET', @@ -15,21 +25,27 @@ export function envelopeFrom(ctx: any): RequestEnvelope { }; } -export function buildRemote(link: Link, origin: string): { - providers: RemoteScopeNode[]; steps: RemoteScopeNode[]; routes: RemoteRoute[]; +/** Turn a link's manifest into local proxy nodes: app-scope providers, request-scope steps, and routes. */ +export function buildRemote(link: Link): { + providers: RemoteScopeNode[]; + steps: RemoteScopeNode[]; + routes: RemoteRoute[]; } { const providers: RemoteScopeNode[] = []; const steps: RemoteScopeNode[] = []; - for (const s of link.manifest.scopes) { + + for (const scope of link.manifest.scopes) { const node: RemoteScopeNode = { - name: s.token, - run: async (ctx: any) => ({ [s.token]: await link.rpc('scope', s.token, envelopeFrom(ctx)) }), + name: scope.token, + run: async (ctx: any) => ({ [scope.token]: await link.rpc('scope', scope.token, envelopeFrom(ctx)) }), }; - (s.scope === 'app' ? providers : steps).push(node); + (scope.scope === 'app' ? providers : steps).push(node); } - const routes: RemoteRoute[] = link.manifest.routes.map((r) => ({ - method: r.method, pattern: r.pattern, - handler: async (req: RequestEnvelope) => (await link.rpc('route', r.pattern, req)) as ResponseShape, + + const routes: RemoteRoute[] = link.manifest.routes.map((route) => ({ + method: route.method, + pattern: route.pattern, + handler: async (req: RequestEnvelope) => (await link.rpc('route', route.pattern, req)) as ResponseShape, })); return { providers, steps, routes }; } diff --git a/src/mesh/teapot.ts b/src/mesh/teapot.ts index e0e5496..b7922fa 100644 --- a/src/mesh/teapot.ts +++ b/src/mesh/teapot.ts @@ -4,12 +4,14 @@ import type { ResponseShape } from '../pipeline'; import { isHttpError } from '../signals'; import { encode, decode, type Manifest, type RequestEnvelope, type RouteEntry, type Frame } from './protocol'; +/** WebSocket path where a teapot exposes its mesh control channel. */ export const MESH_CONTROL_PATH = '/__mesh__/control'; +/** Assemble a {@link Manifest} from exported provider/step tokens and buffered routes. */ export function buildManifest(args: { - providers: string[]; // exported provider tokens (app-scope) - steps: string[]; // exported step tokens (request-scope) - routes: RouteEntry[]; // exported buffered routes + providers: string[]; // exported provider tokens (app-scope) + steps: string[]; // exported step tokens (request-scope) + routes: RouteEntry[]; // exported buffered routes }): Manifest { return { scopes: [ @@ -20,13 +22,14 @@ export function buildManifest(args: { }; } -function safeEqual(a: string, b: string): boolean { - const ba = Buffer.from(a); - const bb = Buffer.from(b); - if (ba.length !== bb.length) return false; - return crypto.timingSafeEqual(ba, bb); +function safeEqual(left: string, right: string): boolean { + const leftBuf = Buffer.from(left); + const rightBuf = Buffer.from(right); + if (leftBuf.length !== rightBuf.length) return false; + return crypto.timingSafeEqual(leftBuf, rightBuf); } +/** Dependencies for the mesh control handler: shared secret, manifest, and scope/route resolvers. */ export interface MeshControlDeps { secret: string; manifest: Manifest; @@ -35,9 +38,77 @@ export interface MeshControlDeps { bus?: Bus; } +/** The rpc-req member of the {@link Frame} union. */ +type RpcReqFrame = Extract; + +/** Build a 403 "not exported" error for an unknown scope/route token. */ +function notExported(name: string): Error { + const error: any = new Error(`not exported: ${name}`); + error.status = 403; + + return error; +} + +/** Validate an unauthenticated hello frame; reply with the manifest on success or close on mismatch. */ +function handleHandshake(ws: any, frame: Frame, deps: MeshControlDeps): boolean { + if (frame.type === 'hello' && safeEqual(frame.secret, deps.secret)) { + ws.send(encode({ type: 'manifest', scopes: deps.manifest.scopes, routes: deps.manifest.routes })); + deps.bus?.emit('mesh:connect', { name: 'teapot' }); + + return true; + } + + ws.close(1008); + + return false; +} + +/** Resolve an authenticated rpc-req against the exported scopes/routes, enforcing export gating. */ +function resolveRpc( + frame: RpcReqFrame, + deps: MeshControlDeps, + exportedScopes: Set, + exportedRoutes: Set, +): Promise { + const { kind, name, ctx } = frame; + + if (kind === 'scope') { + if (!exportedScopes.has(name)) throw notExported(name); + + return deps.resolveScope(name, ctx); + } + + if (![...exportedRoutes].some((key) => key.endsWith(` ${name}`))) throw notExported(name); + + return deps.resolveRoute(name, ctx); +} + +/** Serve one authenticated rpc-req: resolve it and frame the ok/error response back to the peer. */ +async function handleRpc( + ws: any, + frame: RpcReqFrame, + deps: MeshControlDeps, + exportedScopes: Set, + exportedRoutes: Set, +): Promise { + const { id, name } = frame; + + try { + const result = await resolveRpc(frame, deps, exportedScopes, exportedRoutes); + + ws.send(encode({ type: 'rpc-res', id, ok: true, result })); + } catch (err) { + const status = isHttpError(err) ? err.status : ((err as any)?.status ?? 500); + + deps.bus?.emit('mesh:rpc:error', { name, error: err }); + ws.send(encode({ type: 'rpc-res', id, ok: false, error: { message: (err as Error).message, status } })); + } +} + +/** Build a WebSocket handler that authenticates peers and serves scope/route RPCs from the manifest. */ export function createMeshControl(deps: MeshControlDeps): { path: string; handle: (ws: any) => void } { - const exportedScopes = new Set(deps.manifest.scopes.map((s) => s.token)); - const exportedRoutes = new Set(deps.manifest.routes.map((r) => `${r.method} ${r.pattern}`)); + const exportedScopes = new Set(deps.manifest.scopes.map((scope) => scope.token)); + const exportedRoutes = new Set(deps.manifest.routes.map((route) => `${route.method} ${route.pattern}`)); return { path: MESH_CONTROL_PATH, @@ -45,36 +116,22 @@ export function createMeshControl(deps: MeshControlDeps): { path: string; handle let authed = false; ws.on('message', async (data: unknown) => { let frame: Frame; - try { frame = decode(String(data)); } catch { return; } + + try { + frame = decode(String(data)); + } catch { + return; + } if (!authed) { - if (frame.type === 'hello' && safeEqual(frame.secret, deps.secret)) { - authed = true; - ws.send(encode({ type: 'manifest', scopes: deps.manifest.scopes, routes: deps.manifest.routes })); - deps.bus?.emit('mesh:connect', { name: 'teapot' }); - } else { - ws.close(1008); - } + authed = handleHandshake(ws, frame, deps); + return; } if (frame.type !== 'rpc-req') return; - const { id, kind, name, ctx } = frame; - try { - let result: unknown; - if (kind === 'scope') { - if (!exportedScopes.has(name)) { const e: any = new Error(`not exported: ${name}`); e.status = 403; throw e; } - result = await deps.resolveScope(name, ctx); - } else { - if (![...exportedRoutes].some((k) => k.endsWith(` ${name}`))) { const e: any = new Error(`not exported: ${name}`); e.status = 403; throw e; } - result = await deps.resolveRoute(name, ctx); - } - ws.send(encode({ type: 'rpc-res', id, ok: true, result })); - } catch (err) { - const status = isHttpError(err) ? err.status : (err as any)?.status ?? 500; - deps.bus?.emit('mesh:rpc:error', { name, error: err }); - ws.send(encode({ type: 'rpc-res', id, ok: false, error: { message: (err as Error).message, status } })); - } + + await handleRpc(ws, frame, deps, exportedScopes, exportedRoutes); }); ws.on('close', () => deps.bus?.emit('mesh:disconnect', { name: 'teapot' })); }, diff --git a/src/metadata.ts b/src/metadata.ts index be4efce..9d47050 100644 --- a/src/metadata.ts +++ b/src/metadata.ts @@ -1,15 +1,43 @@ import 'reflect-metadata'; +/** Any class constructor. Kept `any` because decorators must accept every target shape. */ export type Ctor = new (...args: any[]) => any; +/** Serializes a handler's return value into an HTTP response envelope. */ export type TransformerFn = (value: unknown) => { status?: number; headers?: Record; body: string }; -export interface ProviderMeta { provides: string; needs: string[]; optional: boolean; export: boolean } -export interface StepMeta { provides: string; needs: string[]; optional: boolean; export: boolean } +/** Metadata attached by `@Provider`: what it provides, what it needs, and its visibility. */ +export interface ProviderMeta { + provides: string; + needs: string[]; + optional: boolean; + export: boolean; +} +/** Metadata attached by `@Step`: what it provides, what it needs, and its visibility. */ +export interface StepMeta { + provides: string; + needs: string[]; + optional: boolean; + export: boolean; +} +/** HTTP verbs supported by the route decorators. */ export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; +/** Wire transport a route responds with. */ export type Transport = 'buffer' | 'sse' | 'ndjson' | 'negotiate' | 'ws'; -export interface RouteMeta { method: HttpMethod; path: string; handlerName: string; transport: Transport; export: boolean; duplicates?: 'array' | 'last' } +/** Metadata attached by a route decorator to a single handler method. */ +export interface RouteMeta { + method: HttpMethod; + path: string; + handlerName: string; + transport: Transport; + export: boolean; + duplicates?: 'array' | 'last'; +} +/** Options accepted by the `@Module` decorator. */ export interface ModuleOptions { - mountpoint: string; providers?: Ctor[]; steps?: Ctor[]; controllers?: Ctor[]; + mountpoint: string; + providers?: Ctor[]; + steps?: Ctor[]; + controllers?: Ctor[]; } const K = { @@ -21,22 +49,47 @@ const K = { transformer: Symbol('gt:transformer'), }; -export function Provider(opts: { provides: string; needs?: string[]; optional?: boolean; export?: boolean }): ClassDecorator { +/** Marks a class as a provider: a lazily-built dependency addressable by its `provides` key. */ +export function Provider(opts: { + provides: string; + needs?: string[]; + optional?: boolean; + export?: boolean; +}): ClassDecorator { return (target) => { - const meta: ProviderMeta = { provides: opts.provides, needs: opts.needs ?? [], optional: opts.optional ?? false, export: opts.export ?? false }; + const meta: ProviderMeta = { + provides: opts.provides, + needs: opts.needs ?? [], + optional: opts.optional ?? false, + export: opts.export ?? false, + }; Reflect.defineMetadata(K.provider, meta, target); }; } -export function Step(opts: { provides: string; needs?: string[]; optional?: boolean; export?: boolean }): ClassDecorator { +/** Marks a class as a step: a per-request unit that runs in dependency order and contributes to the context. */ +export function Step(opts: { + provides: string; + needs?: string[]; + optional?: boolean; + export?: boolean; +}): ClassDecorator { return (target) => { - const meta: StepMeta = { provides: opts.provides, needs: opts.needs ?? [], optional: opts.optional ?? false, export: opts.export ?? false }; + const meta: StepMeta = { + provides: opts.provides, + needs: opts.needs ?? [], + optional: opts.optional ?? false, + export: opts.export ?? false, + }; Reflect.defineMetadata(K.step, meta, target); }; } +/** Sets the shared path prefix for every route declared on the decorated controller. */ export function Route(prefix: string): ClassDecorator { - return (target) => { Reflect.defineMetadata(K.routePrefix, prefix, target); }; + return (target) => { + Reflect.defineMetadata(K.routePrefix, prefix, target); + }; } function routeDecorator(method: HttpMethod, transport: Transport) { @@ -44,48 +97,77 @@ function routeDecorator(method: HttpMethod, transport: Transport) { (target, propertyKey) => { const ctor = target.constructor; const routes = (Reflect.getMetadata(K.routes, ctor) as RouteMeta[]) ?? []; - routes.push({ method, path, handlerName: String(propertyKey), transport, export: opts?.export ?? false, duplicates: opts?.duplicates }); + routes.push({ + method, + path, + handlerName: String(propertyKey), + transport, + export: opts?.export ?? false, + duplicates: opts?.duplicates, + }); Reflect.defineMetadata(K.routes, routes, ctor); }; } +/** Declares a buffered `GET` route. */ export const Get = routeDecorator('GET', 'buffer'); +/** Declares a buffered `POST` route. */ export const Post = routeDecorator('POST', 'buffer'); +/** Declares a buffered `PUT` route. */ export const Put = routeDecorator('PUT', 'buffer'); +/** Declares a buffered `PATCH` route. */ export const Patch = routeDecorator('PATCH', 'buffer'); +/** Declares a buffered `DELETE` route. */ export const Delete = routeDecorator('DELETE', 'buffer'); +/** Declares a `GET` route streamed as Server-Sent Events. */ export const Sse = routeDecorator('GET', 'sse'); +/** Declares a `GET` route whose transport is content-negotiated at request time. */ export const Stream = routeDecorator('GET', 'negotiate'); +/** Declares a `GET` route upgraded to a WebSocket. */ export const Ws = routeDecorator('GET', 'ws'); +/** Attaches a response transformer to a handler method. */ export function Transformer(fn: TransformerFn): MethodDecorator { return (target, propertyKey) => { Reflect.defineMetadata(K.transformer, fn, target.constructor, String(propertyKey)); }; } +/** Marks a class as a module and records its providers, steps, controllers, and mountpoint. */ export function Module(opts: ModuleOptions): ClassDecorator { - return (target) => { Reflect.defineMetadata(K.module, opts, target); }; + return (target) => { + Reflect.defineMetadata(K.module, opts, target); + }; } +/** Reads the `@Provider` metadata off a class, if any. */ export function getProviderMeta(cls: Ctor): ProviderMeta | undefined { return Reflect.getMetadata(K.provider, cls); } + +/** Reads the `@Step` metadata off a class, if any. */ export function getStepMeta(cls: Ctor): StepMeta | undefined { return Reflect.getMetadata(K.step, cls); } + +/** Reads the `@Module` metadata off a class, if any. */ export function getModuleMeta(cls: Ctor): ModuleOptions | undefined { return Reflect.getMetadata(K.module, cls); } + +/** Reads the response transformer registered for a handler method, if any. */ export function getTransformer(cls: Ctor, methodName: string): TransformerFn | undefined { return Reflect.getMetadata(K.transformer, cls, methodName); } + +/** Returns every route on a controller with its path resolved against the class prefix. */ export function getRoutes(cls: Ctor): RouteMeta[] { const prefix: string = Reflect.getMetadata(K.routePrefix, cls) ?? ''; const routes: RouteMeta[] = Reflect.getMetadata(K.routes, cls) ?? []; - return routes.map((r) => ({ ...r, path: joinPath(prefix, r.path) })); + return routes.map((route) => ({ ...route, path: joinPath(prefix, route.path) })); } -export function joinPath(a: string, b: string): string { - return `${a.replace(/\/$/, '')}/${b.replace(/^\//, '')}`.replace(/\/+/g, '/'); +/** Joins two path segments with exactly one slash, collapsing any duplicates. */ +export function joinPath(base: string, segment: string): string { + return `${base.replace(/\/$/, '')}/${segment.replace(/^\//, '')}`.replace(/\/+/g, '/'); } diff --git a/src/multipart.ts b/src/multipart.ts index 02fad20..3e03cab 100644 --- a/src/multipart.ts +++ b/src/multipart.ts @@ -1,122 +1,130 @@ -// src/multipart.ts — pure, binary-safe multipart/form-data parser. No server deps. -export interface UploadedFile { filename: string; contentType: string; data: Buffer; size: number } +// src/multipart.ts — multipart/form-data parsing on top of the optional `busboy` peer dependency. +import { Readable } from 'stream'; +import { HttpError } from './signals'; + +/** A single uploaded file part decoded from a multipart body. */ +export interface UploadedFile { + filename: string; + contentType: string; + data: Buffer; + size: number; +} + +/** Decoded multipart body: text fields and file uploads, keyed by part name. */ export interface MultipartBody { fields: Record; files: Record; } -export interface MultipartOpts { maxParts: number; duplicates: 'array' | 'last' } -const CRLF = Buffer.from('\r\n'); +/** Parser limits and duplicate-key policy for {@link parseMultipart}. */ +export interface MultipartOpts { + maxParts: number; + duplicates: 'array' | 'last'; +} -// boundary token from a Content-Type value; supports quoted form. +/** + * Extracts the boundary token from a Content-Type value (supports the quoted form). + * @returns The boundary, or undefined when absent. + */ export function extractBoundary(contentType: string): string | undefined { - const m = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(contentType); - const b = (m?.[1] ?? m?.[2])?.trim(); - return b || undefined; + const match = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(contentType); + const boundary = (match?.[1] ?? match?.[2])?.trim(); + return boundary || undefined; } -// order-independent, quoted-or-unquoted param lookup within a header value. -// The `(?:^|[;\s])` prefix anchors the key to a param boundary so `name=` does NOT -// match the tail of `filename=`, and `filename=` does not match `filename*=`. -function param(header: string, key: string): string | undefined { - const q = new RegExp(`(?:^|[;\\s])${key}="([^"]*)"`, 'i').exec(header); - if (q) return q[1]; - const u = new RegExp(`(?:^|[;\\s])${key}=([^";]+)`, 'i').exec(header); - return u ? u[1].trim() : undefined; -} - -function addField(fields: MultipartBody['fields'], name: string, value: string, dup: 'array' | 'last'): void { - if (dup === 'array') { - const ex = fields[name]; - if (Array.isArray(ex)) ex.push(value); +function addField(fields: MultipartBody['fields'], name: string, value: string, duplicates: 'array' | 'last'): void { + if (duplicates === 'array') { + const existing = fields[name]; + if (Array.isArray(existing)) existing.push(value); else fields[name] = [value]; } else { fields[name] = value; // last-wins } } -// Reusable accumulator for any iterable of [key, value] pairs (e.g. URLSearchParams) -// so urlencoded bodies collapse duplicates with the exact same policy as multipart fields. +/** + * Collapses an iterable of [key, value] pairs (e.g. URLSearchParams) into an object, + * applying the same duplicate-key policy as multipart fields so urlencoded bodies behave identically. + */ export function collapseDuplicates( - pairs: Iterable<[string, string]>, dup: 'array' | 'last', + pairs: Iterable<[string, string]>, + duplicates: 'array' | 'last', ): Record { const out: Record = {}; - for (const [k, v] of pairs) addField(out, k, v, dup); + for (const [key, value] of pairs) addField(out, key, value, duplicates); return out; } function addFile(files: MultipartBody['files'], name: string, file: UploadedFile): void { - const ex = files[name]; - if (ex === undefined) files[name] = file; - else if (Array.isArray(ex)) ex.push(file); - else files[name] = [ex, file]; + const existing = files[name]; + if (existing === undefined) files[name] = file; + else if (Array.isArray(existing)) existing.push(file); + else files[name] = [existing, file]; } -// Find the next REAL delimiter at/after `from`: a `\r\n--boundary` occurrence that is -// followed by `\r\n` (a part) or `--` (the terminator). This skips false hits where the -// exact `\r\n--boundary` byte sequence appears INSIDE a file body — the data-integrity case. -function findDelim(buf: Buffer, delim: Buffer, from: number): number { - let i = buf.indexOf(delim, from); - while (i !== -1) { - const a = i + delim.length; - if ((buf[a] === 0x0d && buf[a + 1] === 0x0a) || (buf[a] === 0x2d && buf[a + 1] === 0x2d)) return i; - i = buf.indexOf(delim, i + delim.length); // false hit inside a body — keep searching +/** Lazily loads the optional `busboy` peer dependency, or null when it is not installed. */ +function loadBusboy(): ((cfg: unknown) => NodeJS.WritableStream & NodeJS.EventEmitter) | null { + try { + // `busboy` is an OPTIONAL peer dependency: only multipart uploads need it, so it is + // lazy-required and its absence surfaces as a clear 501 rather than a load-time crash. + // eslint-disable-next-line @typescript-eslint/no-require-imports + return require('busboy'); + } catch { + return null; } - return -1; } -export function parseMultipart(raw: Buffer, boundary: string, opts: MultipartOpts): MultipartBody { - const fields: MultipartBody['fields'] = {}; - const files: MultipartBody['files'] = {}; - const delim = Buffer.concat([CRLF, Buffer.from(`--${boundary}`)]); // \r\n--boundary - // Normalize: prepend CRLF so the FIRST boundary (which a browser sends with no - // leading CRLF) is also preceded by the delimiter and isn't dropped as preamble. - const buf = Buffer.concat([CRLF, raw]); +/** + * Parses a raw multipart/form-data buffer into decoded fields and files, using `busboy`. + * @param raw The full (already size-capped) request body. + * @param boundary The boundary token (see {@link extractBoundary}). + * @throws HttpError 501 when the optional `busboy` peer dependency is not installed. + * @throws Error 'Invalid multipart body' on malformed input or when `maxParts` is exceeded. + */ +export function parseMultipart(raw: Buffer, boundary: string, opts: MultipartOpts): Promise { + const busboy = loadBusboy(); - let pos = findDelim(buf, delim, 0); - if (pos === -1) throw new Error('Invalid multipart body'); - let count = 0; - while (true) { - let start = pos + delim.length; - // terminator "--" immediately after the boundary → done - if (buf[start] === 0x2d && buf[start + 1] === 0x2d) break; - // skip the CRLF that ends the boundary line - if (buf[start] === 0x0d && buf[start + 1] === 0x0a) start += 2; - const next = findDelim(buf, delim, start); - if (next === -1) throw new Error('Invalid multipart body'); - if (++count > opts.maxParts) throw new Error('Invalid multipart body'); - const part = buf.subarray(start, next); - const sep = part.indexOf('\r\n\r\n'); - if (sep === -1) throw new Error('Invalid multipart body'); - const headerText = part.subarray(0, sep).toString('utf8'); - const partBody = part.subarray(sep + 4); + if (!busboy) { + throw new HttpError(501, 'multipart/form-data requires the optional "busboy" peer dependency — run `npm i busboy`'); + } - let disposition = ''; - let contentType = ''; - for (const line of headerText.split('\r\n')) { - const c = line.indexOf(':'); - if (c === -1) continue; - const k = line.slice(0, c).trim().toLowerCase(); - const v = line.slice(c + 1).trim(); - if (k === 'content-disposition') disposition = v; - else if (k === 'content-type') contentType = v; - } + return new Promise((resolve, reject) => { + const body: MultipartBody = { fields: {}, files: {} }; + const fail = () => reject(new Error('Invalid multipart body')); + let bb: NodeJS.WritableStream & NodeJS.EventEmitter; - const name = param(disposition, 'name'); - if (name === undefined) throw new Error('Invalid multipart body'); - const filename = param(disposition, 'filename'); - if (filename !== undefined) { - if (filename === '' && partBody.length === 0) { pos = next; continue; } // unselected file input - addFile(files, name, { - filename, - contentType: contentType || 'application/octet-stream', - data: Buffer.from(partBody), // copy out of the shared buffer - size: partBody.length, + try { + bb = busboy({ + headers: { 'content-type': `multipart/form-data; boundary=${boundary}` }, + limits: { parts: opts.maxParts }, }); - } else { - addField(fields, name, partBody.toString('utf8'), opts.duplicates); + } catch { + return fail(); } - pos = next; - } - return { fields, files }; + + bb.on('field', (name: string, value: string) => addField(body.fields, name, value, opts.duplicates)); + + bb.on('file', (name: string, stream: Readable, info: { filename?: string; mimeType?: string }) => { + const chunks: Buffer[] = []; + stream.on('data', (chunk: Buffer) => chunks.push(chunk)); + stream.on('close', () => { + const data = Buffer.concat(chunks); + const filename = info.filename ?? ''; + if (filename === '' && data.length === 0) return; // unselected file input + + addFile(body.files, name, { + filename, + contentType: info.mimeType || 'application/octet-stream', + data, + size: data.length, + }); + }); + }); + + bb.on('partsLimit', fail); // more parts than maxParts → treat as malformed (matches prior behavior) + bb.on('error', fail); + bb.on('close', () => resolve(body)); + + Readable.from(raw).pipe(bb); + }); } diff --git a/src/params.ts b/src/params.ts index a431de3..495bca9 100644 --- a/src/params.ts +++ b/src/params.ts @@ -3,12 +3,22 @@ import type { Ctor } from './metadata'; import { isStandardSchema, type StandardSchemaV1 } from './standard-schema'; import { ValidationError } from './signals'; +/** Parsed URL query string as flat key/value pairs. */ export type Query = Record; +/** Incoming request headers; a header may repeat, hence the array variant. */ export type Headers = Record; +/** Per-request bag that accumulates values produced by steps and providers. */ export type Context = Record; type ArgSource = 'ctx' | 'needs' | 'params' | 'query' | 'body' | 'headers' | 'inbound' | 'abort'; -export interface ArgSpec { index: number; source: ArgSource; key?: string; keys?: string[]; schema?: StandardSchemaV1 } +/** Describes how a single handler parameter is sourced and (optionally) validated. */ +export interface ArgSpec { + index: number; + source: ArgSource; + key?: string; + keys?: string[]; + schema?: StandardSchemaV1; +} const ARGS = Symbol('gt:args'); @@ -30,73 +40,94 @@ function envelope(source: ArgSource) { else if (typeof arg === 'string') spec.key = arg; else if (isStandardSchema(arg)) spec.schema = arg; else if (arg !== undefined) throw new Error(`@${source}: expected a Standard Schema or a string/array key`); + if (schema !== undefined) { if (!isStandardSchema(schema)) throw new Error(`@${source}: second argument must be a Standard Schema`); spec.schema = schema; } + record(target, methodKey, spec); }; } +/** Inject a route path parameter; pass a key to pick one, or a schema/array to shape it. */ export const param = envelope('params'); +/** Inject a query-string value; pass a key to pick one, or a schema/array to shape it. */ export const query = envelope('query'); +/** Inject the request body; pass a schema to validate it. */ export const body = envelope('body'); +/** Inject request headers; pass a key to pick one, an array to pick several, or no arg for the whole bag. */ export const headers = envelope('headers'); +/** Inject a single request header by name (singular alias of {@link headers}); accepts a schema to validate it. */ +export const header = envelope('headers'); +/** Inject a value produced upstream by a step or provider, addressed by key. */ export function needs(key: string): ParameterDecorator { return (target, methodKey, index) => record(target, methodKey, { index, source: 'needs', key }); } +/** Inject the whole request context bag. */ export function ctx(): ParameterDecorator { return (target, methodKey, index) => record(target, methodKey, { index, source: 'ctx' }); } +/** Inject the inbound stream (for streaming/upload handlers). */ export function inbound(): ParameterDecorator { return (target, methodKey, index) => record(target, methodKey, { index, source: 'inbound' }); } +/** Inject the request's abort signal. */ export function abort(): ParameterDecorator { return (target, methodKey, index) => record(target, methodKey, { index, source: 'abort' }); } +/** Read the recorded parameter specs for a handler method, ordered by parameter index. */ export function getArgs(cls: Ctor, methodName: string): ArgSpec[] { const map: Record = Reflect.getMetadata(ARGS, cls) ?? {}; return [...(map[methodName] ?? [])].sort((a, b) => a.index - b.index); } +/** Extract the `@needs` keys a handler depends on, for dependency resolution. */ export function getHandlerNeeds(specs: ArgSpec[]): string[] { - return specs.filter((s) => s.source === 'needs' && s.key).map((s) => s.key as string); + return specs.filter((spec) => spec.source === 'needs' && spec.key).map((spec) => spec.key as string); } +/** Build the positional argument array for a handler by sourcing and validating each spec. */ export async function resolveArgs(specs: ArgSpec[], context: Context): Promise { if (specs.length === 0) return []; - const max = Math.max(...specs.map((s) => s.index)); - const args: unknown[] = new Array(max + 1).fill(undefined); - for (const s of specs) { - let value = resolveOne(s, context); - if (s.schema) { - const result = await s.schema['~standard'].validate(value); - if (result.issues) throw new ValidationError([...result.issues], s.source); + const maxIndex = Math.max(...specs.map((spec) => spec.index)); + const args: unknown[] = new Array(maxIndex + 1).fill(undefined); + + for (const spec of specs) { + let value = resolveOne(spec, context); + + if (spec.schema) { + const result = await spec.schema['~standard'].validate(value); + if (result.issues) throw new ValidationError([...result.issues], spec.source); value = result.value; } - args[s.index] = value; + + args[spec.index] = value; } + return args; } -function resolveOne(s: ArgSpec, context: Context): unknown { - if (s.source === 'ctx') return context; - if (s.source === 'needs') return context[s.key as string]; - if (s.source === 'inbound') return context.inbound; - if (s.source === 'abort') return context.abort; - const bag = context[s.source]; +function resolveOne(spec: ArgSpec, context: Context): unknown { + if (spec.source === 'ctx') return context; + if (spec.source === 'needs') return context[spec.key as string]; + if (spec.source === 'inbound') return context.inbound; + if (spec.source === 'abort') return context.abort; + const bag = context[spec.source]; if (typeof bag !== 'object' || bag === null) return bag; // can't pick from a non-object; return as-is - const record = bag as Record; - if (s.keys) { - const out: Record = {}; - for (const k of s.keys) out[k] = record[k]; - return out; + const values = bag as Record; + + if (spec.keys) { + const picked: Record = {}; + for (const key of spec.keys) picked[key] = values[key]; + return picked; } - if (s.key !== undefined) return record[s.key]; - return record; + + if (spec.key !== undefined) return values[spec.key]; + return values; } diff --git a/src/pipeline.ts b/src/pipeline.ts index e719b1a..d2ec969 100644 --- a/src/pipeline.ts +++ b/src/pipeline.ts @@ -3,15 +3,35 @@ import { errorToResponse } from './transformers'; import { isAsyncIterable } from './channel'; import type { TransformerFn } from './metadata'; -export interface PipelineStep { name: string; origin: string; run: (ctx: any) => any } -export interface ResponseShape { status: number; headers: Record; body: string } -export interface StreamResult { stream: AsyncIterable } +/** A single step in a request pipeline: a named unit whose `run` merges its output into the shared context. */ +export interface PipelineStep { + name: string; + origin: string; + run: (ctx: any) => any; +} +/** A fully materialized HTTP response produced by a transformer. */ +export interface ResponseShape { + status: number; + headers: Record; + body: string; +} +/** A streaming response; the async iterable is written to the socket and bypasses the transformer. */ +export interface StreamResult { + stream: AsyncIterable; +} +/** The outcome of {@link runPipeline}: either a buffered response or a stream. */ export type PipelineResult = ResponseShape | StreamResult; -export function isStreamResult(r: PipelineResult): r is StreamResult { - return 'stream' in r; +/** Type guard narrowing a {@link PipelineResult} to a {@link StreamResult}. */ +export function isStreamResult(result: PipelineResult): result is StreamResult { + return 'stream' in result; } +/** + * Run `steps` in order over a context seeded from `seed`, then invoke `handler`. + * An async-iterable handler result becomes a stream; anything else is run through `transformer`. + * Errors are caught, emitted on `bus`, and converted to an error response. + */ export async function runPipeline(args: { steps: PipelineStep[]; handler: (ctx: any) => unknown; @@ -20,18 +40,21 @@ export async function runPipeline(args: { bus: Bus; }): Promise { const { steps, handler, transformer, seed, bus } = args; - let ctx: any = { ...seed }; + // context is intentionally `any`: each step merges arbitrary keys into the accumulator + let context: any = { ...seed }; + try { - for (const s of steps) { - bus.emit('request:step:enter', { name: s.name, scope: s.origin }); - const out = await s.run(ctx); - ctx = { ...ctx, ...out }; - bus.emit('request:step:leave', { name: s.name, scope: s.origin }); + for (const step of steps) { + 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(ctx); - if (isAsyncIterable(result)) return { stream: result }; // stream path: transformer bypassed - const r = transformer(result); - return { status: r.status ?? 200, headers: r.headers ?? {}, body: r.body }; + + const result = await handler(context); + if (isAsyncIterable(result)) return { stream: result }; // stream path: transformer bypassed + const transformed = transformer(result); + return { status: transformed.status ?? 200, headers: transformed.headers ?? {}, body: transformed.body }; } catch (error) { bus.emit('request:step:error', { name: 'pipeline', error }); return errorToResponse(error); diff --git a/src/plugin.ts b/src/plugin.ts index d0c25d8..2a0eb6f 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -1,5 +1,6 @@ import { Bus } from './bus'; +/** A step or provider a plugin contributes to the graph. */ export interface ScopeNode { kind: 'step' | 'provider'; name: string; @@ -8,10 +9,19 @@ export interface ScopeNode { run: (ctx: any) => any; } -export interface ScopeApi { add(node: ScopeNode): void } -export interface PluginApi { bus: { on: Bus['on'] }; scope: ScopeApi } +/** The narrow surface a plugin uses to register nodes into the host graph. */ +export interface ScopeApi { + add(node: ScopeNode): void; +} +/** The capabilities handed to a plugin: event subscription and node registration only. */ +export interface PluginApi { + bus: { on: Bus['on'] }; + scope: ScopeApi; +} +/** A plugin: a function that wires itself up through the provided PluginApi. */ export type Plugin = (api: PluginApi) => void; +/** Runs a plugin against a restricted API, then emits `plugin:mounted`. */ export function mountPlugin(plugin: Plugin, bus: Bus, scope: ScopeApi): void { // Hand the plugin ONLY on() and add(). No emit, no other scope. Isolation is structural. const api: PluginApi = { bus: { on: bus.on.bind(bus) }, scope }; diff --git a/src/rooms.ts b/src/rooms.ts index 7eee41b..aa5b5a3 100644 --- a/src/rooms.ts +++ b/src/rooms.ts @@ -1,11 +1,21 @@ import { channel, type Channel } from './channel'; +/** Registry of named broadcast channels, lazily created and shared by name. */ export class Rooms { private readonly hubs = new Map>(); + /** Returns the channel for `name`, creating it on first access. */ room(name: string): Channel { let hub = this.hubs.get(name); - if (!hub) { hub = channel(); this.hubs.set(name, hub); } + + if (!hub) { + hub = channel(); + this.hubs.set(name, hub); + } + return hub as unknown as Channel; } - names(): string[] { return [...this.hubs.keys()]; } + /** Lists the names of all rooms created so far. */ + names(): string[] { + return [...this.hubs.keys()]; + } } diff --git a/src/security.ts b/src/security.ts index 18c58b8..c48023d 100644 --- a/src/security.ts +++ b/src/security.ts @@ -1,6 +1,14 @@ // src/security.ts — pure header computation, no server deps -export interface TlsOptions { key: Buffer | string; cert: Buffer | string; ca?: Buffer | string; passphrase?: string } +/** TLS material for an HTTPS server. */ +export interface TlsOptions { + key: Buffer | string; + cert: Buffer | string; + ca?: Buffer | string; + passphrase?: string; +} + +/** CORS policy. `origins` may be a literal, list, `'*'`, or a predicate. */ export interface CorsOptions { origins: string | string[] | '*' | ((origin: string) => boolean); methods?: string[]; @@ -10,6 +18,7 @@ export interface CorsOptions { maxAge?: number; } +/** Security header policy. Each field toggles or configures one response header. */ export interface SecurityOptions { hsts?: boolean | { maxAge?: number; includeSubDomains?: boolean; preload?: boolean }; frameOptions?: 'SAMEORIGIN' | 'DENY' | false; @@ -23,32 +32,47 @@ type Headers = Record; const HSTS_DEFAULT_MAXAGE = 15552000; // 180 days // scheme "://" host [":" port], or literal "null". Rejects control chars/whitespace. +// Control-char ranges (\x00-\x1f\x7f) are intentional: reject control chars in Origin headers. +// eslint-disable-next-line no-control-regex const ORIGIN_RE = /^(?:null|[a-z][a-z0-9+.-]*:\/\/[^\s/?#\x00-\x1f\x7f]+)$/i; -export function isValidOrigin(o: string): boolean { return ORIGIN_RE.test(o); } +/** True if `origin` is a well-formed Origin header value (scheme://host or literal `null`). */ +export function isValidOrigin(origin: string): boolean { + return ORIGIN_RE.test(origin); +} + +/** Append `add` to a `Vary` header value, case-insensitively deduplicated. */ export function mergeVary(existing: string | undefined, add: string): string { - const parts = (existing ? existing.split(',').map((s) => s.trim()).filter(Boolean) : []); - if (!parts.some((p) => p.toLowerCase() === add.toLowerCase())) parts.push(add); + const parts = existing + ? existing + .split(',') + .map((segment) => segment.trim()) + .filter(Boolean) + : []; + if (!parts.some((part) => part.toLowerCase() === add.toLowerCase())) parts.push(add); return parts.join(', '); } +/** Build security response headers (HSTS, frame options, CSP, etc.). `secure` gates HSTS. */ export function buildSecurityHeaders(opts: boolean | SecurityOptions, secure: boolean): Headers { if (opts === false) return {}; - const o: SecurityOptions = opts === true ? {} : opts; - const h: Headers = {}; - if (o.noSniff !== false) h['x-content-type-options'] = 'nosniff'; - if (o.frameOptions !== false) h['x-frame-options'] = o.frameOptions ?? 'SAMEORIGIN'; - if (o.referrerPolicy !== false) h['referrer-policy'] = o.referrerPolicy ?? 'no-referrer'; - if (o.dnsPrefetchControl !== false) h['x-dns-prefetch-control'] = 'off'; - if (o.csp) h['content-security-policy'] = o.csp; - if (secure && o.hsts !== false) { - const hs = o.hsts && o.hsts !== true ? o.hsts : {}; - let v = `max-age=${hs.maxAge ?? HSTS_DEFAULT_MAXAGE}`; - if (hs.includeSubDomains) v += '; includeSubDomains'; - if (hs.preload) v += '; preload'; - h['strict-transport-security'] = v; + const options: SecurityOptions = opts === true ? {} : opts; + const headers: Headers = {}; + if (options.noSniff !== false) headers['x-content-type-options'] = 'nosniff'; + if (options.frameOptions !== false) headers['x-frame-options'] = options.frameOptions ?? 'SAMEORIGIN'; + if (options.referrerPolicy !== false) headers['referrer-policy'] = options.referrerPolicy ?? 'no-referrer'; + if (options.dnsPrefetchControl !== false) headers['x-dns-prefetch-control'] = 'off'; + if (options.csp) headers['content-security-policy'] = options.csp; + + if (secure && options.hsts !== false) { + const hsts = options.hsts && options.hsts !== true ? options.hsts : {}; + let value = `max-age=${hsts.maxAge ?? HSTS_DEFAULT_MAXAGE}`; + if (hsts.includeSubDomains) value += '; includeSubDomains'; + if (hsts.preload) value += '; preload'; + headers['strict-transport-security'] = value; } - return h; + + return headers; } function originAllowed(spec: CorsOptions['origins'], origin: string): boolean { @@ -58,36 +82,46 @@ function originAllowed(spec: CorsOptions['origins'], origin: string): boolean { return spec === origin; } -// req: minimal shape { headers: { origin? } } -export function resolveCors(opts: CorsOptions, req: { headers: Record }): Headers { - const h: Headers = {}; - const raw = req.headers['origin']; - const origin = Array.isArray(raw) ? raw[0] : raw; - if (!origin || !isValidOrigin(origin) || !originAllowed(opts.origins, origin)) return h; +/** Compute CORS response headers for a request. Returns `{}` when the origin is not allowed. */ +export function resolveCors( + opts: CorsOptions, + req: { headers: Record }, +): Headers { + const headers: Headers = {}; + const rawOrigin = req.headers['origin']; + const origin = Array.isArray(rawOrigin) ? rawOrigin[0] : rawOrigin; + if (!origin || !isValidOrigin(origin) || !originAllowed(opts.origins, origin)) return headers; // credentials => never '*'; echo concrete origin. Also echo when allowlist is dynamic. if (opts.credentials) { - h['access-control-allow-origin'] = origin; - h['access-control-allow-credentials'] = 'true'; - h['vary'] = mergeVary(h['vary'], 'Origin'); + headers['access-control-allow-origin'] = origin; + headers['access-control-allow-credentials'] = 'true'; + headers['vary'] = mergeVary(headers['vary'], 'Origin'); } else if (opts.origins === '*') { - h['access-control-allow-origin'] = '*'; + headers['access-control-allow-origin'] = '*'; } else { - h['access-control-allow-origin'] = origin; - h['vary'] = mergeVary(h['vary'], 'Origin'); + headers['access-control-allow-origin'] = origin; + headers['vary'] = mergeVary(headers['vary'], 'Origin'); } - if (opts.exposedHeaders?.length) h['access-control-expose-headers'] = opts.exposedHeaders.join(', '); - return h; + + if (opts.exposedHeaders?.length) headers['access-control-expose-headers'] = opts.exposedHeaders.join(', '); + return headers; } -// Preflight-specific headers (methods/allowed-headers/max-age). Call only for OPTIONS+ACRM. -export function corsPreflightHeaders(opts: CorsOptions, req: { headers: Record }): Headers { - const h = resolveCors(opts, req); - if (!h['access-control-allow-origin']) return h; // origin not allowed → bare 204 - h['access-control-allow-methods'] = (opts.methods ?? ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']).join(', '); - const reqHdrs = req.headers['access-control-request-headers']; - h['access-control-allow-headers'] = opts.allowedHeaders?.join(', ') - ?? (Array.isArray(reqHdrs) ? reqHdrs.join(', ') : reqHdrs ?? '*'); - if (opts.maxAge != null) h['access-control-max-age'] = String(opts.maxAge); - return h; +/** Preflight-specific headers (methods/allowed-headers/max-age). Call only for OPTIONS+ACRM. */ +export function corsPreflightHeaders( + opts: CorsOptions, + req: { headers: Record }, +): Headers { + const headers = resolveCors(opts, req); + if (!headers['access-control-allow-origin']) return headers; // origin not allowed → bare 204 + headers['access-control-allow-methods'] = (opts.methods ?? ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']).join( + ', ', + ); + const requestedHeaders = req.headers['access-control-request-headers']; + headers['access-control-allow-headers'] = + opts.allowedHeaders?.join(', ') ?? + (Array.isArray(requestedHeaders) ? requestedHeaders.join(', ') : (requestedHeaders ?? '*')); + if (opts.maxAge != null) headers['access-control-max-age'] = String(opts.maxAge); + return headers; } diff --git a/src/signals.ts b/src/signals.ts index 3b47c24..e7556bb 100644 --- a/src/signals.ts +++ b/src/signals.ts @@ -1,34 +1,56 @@ import type { StandardIssue } from './standard-schema'; +/** Error carrying an HTTP status code and optional response body. Base of all signals. */ export class HttpError extends Error { - constructor(readonly status: number, message?: string, readonly body?: unknown) { + constructor( + readonly status: number, + message?: string, + readonly body?: unknown, + ) { super(message ?? `HTTP ${status}`); this.name = new.target.name; } } +/** 401 Unauthorized. */ export class Unauthorized extends HttpError { - constructor(message?: string) { super(401, message); } + constructor(message?: string) { + super(401, message); + } } +/** 404 Not Found. */ export class NotFound extends HttpError { - constructor(message?: string) { super(404, message); } + constructor(message?: string) { + super(404, message); + } } +/** 304 Not Modified. */ export class NotModified extends HttpError { - constructor() { super(304); } + constructor() { + super(304); + } } +/** 302 redirect to `location`. */ export class Redirect extends HttpError { - constructor(readonly location: string) { super(302); } + constructor(readonly location: string) { + super(302); + } } +/** 422 raised when request input fails Standard Schema validation. */ export class ValidationError extends HttpError { - constructor(public issues: StandardIssue[], public source: string) { + constructor( + public issues: StandardIssue[], + public source: string, + ) { super(422, 'Validation failed'); } } -export function isHttpError(e: unknown): e is HttpError { - return e instanceof HttpError; +/** Type guard: true if `error` is an {@link HttpError}. */ +export function isHttpError(error: unknown): error is HttpError { + return error instanceof HttpError; } diff --git a/src/standard-schema.ts b/src/standard-schema.ts index dde28c1..c899c84 100644 --- a/src/standard-schema.ts +++ b/src/standard-schema.ts @@ -1,4 +1,6 @@ // src/standard-schema.ts — vendored Standard Schema (~standard) types + helpers. No imports. + +/** Standard Schema v1 interface (spec.standardschema.dev): a validator under the `~standard` key. */ export interface StandardSchemaV1 { readonly '~standard': { readonly version: 1; @@ -8,27 +10,31 @@ export interface StandardSchemaV1 { }; } +/** Validation outcome: either a parsed `value` or a list of `issues`. */ export type StandardResult = - | { readonly value: T; readonly issues?: undefined } - | { readonly issues: ReadonlyArray }; + { readonly value: T; readonly issues?: undefined } | { readonly issues: ReadonlyArray }; +/** A single validation issue with a message and optional path to the offending field. */ export interface StandardIssue { readonly message: string; readonly path?: ReadonlyArray; } -export function isStandardSchema(x: unknown): x is StandardSchemaV1 { +/** Type guard: true if `value` implements Standard Schema v1 (has a callable `~standard.validate`). */ +export function isStandardSchema(value: unknown): value is StandardSchemaV1 { return ( - typeof x === 'object' && x !== null && - '~standard' in x && - typeof (x as { ['~standard']?: { validate?: unknown } })['~standard']?.validate === 'function' + typeof value === 'object' && + value !== null && + '~standard' in value && + typeof (value as { ['~standard']?: { validate?: unknown } })['~standard']?.validate === 'function' ); } +/** Render an issue's path as a dotted string (e.g. `user.email`); empty if pathless. */ export function flattenPath(issue: StandardIssue): string { if (!issue.path) return ''; return issue.path - .map((seg) => (typeof seg === 'object' && seg !== null && 'key' in seg ? seg.key : seg)) - .map((k) => String(k)) + .map((segment) => (typeof segment === 'object' && segment !== null && 'key' in segment ? segment.key : segment)) + .map((key) => String(key)) .join('.'); } diff --git a/src/transformers.ts b/src/transformers.ts index 57c5989..e7aaf5a 100644 --- a/src/transformers.ts +++ b/src/transformers.ts @@ -2,29 +2,33 @@ import { isHttpError, Redirect, ValidationError } from './signals'; import type { TransformerFn } from './metadata'; import { flattenPath } from './standard-schema'; +/** Default transformer: serialize a handler's return value as a JSON `200` response. */ export const JsonTransformer: TransformerFn = (value) => ({ status: 200, headers: { 'content-type': 'application/json' }, body: JSON.stringify(value), }); -export function errorToResponse(e: unknown): { status: number; headers: Record; body: string } { - if (e instanceof ValidationError) { +/** Map a thrown value to a JSON error response (422 for validation, HttpError status, else 500). */ +export function errorToResponse(error: unknown): { status: number; headers: Record; body: string } { + if (error instanceof ValidationError) { return { status: 422, headers: { 'content-type': 'application/json' }, body: JSON.stringify({ error: 'Validation failed', - source: e.source, - issues: e.issues.map((i) => ({ path: flattenPath(i), message: i.message })), + source: error.source, + issues: error.issues.map((issue) => ({ path: flattenPath(issue), message: issue.message })), }), }; } - if (isHttpError(e)) { + + if (isHttpError(error)) { const headers: Record = { 'content-type': 'application/json' }; - if (e instanceof Redirect) headers.location = e.location; - return { status: e.status, headers, body: JSON.stringify({ error: e.message }) }; + if (error instanceof Redirect) headers.location = error.location; + return { status: error.status, headers, body: JSON.stringify({ error: error.message }) }; } + return { status: 500, headers: { 'content-type': 'application/json' }, diff --git a/test/app.test.ts b/test/app.test.ts index 6ed9190..616c996 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -72,8 +72,12 @@ test('optional provider failure warns but does not abort boot', async () => { class SysModule {} const app = createApp({ modules: [SysModule] }); + expect(app.degraded()).toEqual([]); // nothing degraded until boot runs const server = await app.listen(0); // must NOT throw expect(warn).toHaveBeenCalledWith(expect.stringContaining("optional provider 'cache' failed")); + // boot ends with a summary of everything running degraded, and it is queryable on the app + expect(warn).toHaveBeenCalledWith(expect.stringContaining('started with 1 degraded optional provider(s): cache')); + expect(app.degraded()).toEqual(['cache']); server.close(); warn.mockRestore(); }); diff --git a/test/mesh/integration.test.ts b/test/mesh/integration.test.ts index 8f6ee37..98bbf37 100644 --- a/test/mesh/integration.test.ts +++ b/test/mesh/integration.test.ts @@ -25,12 +25,12 @@ class TeacupModule {} describe('mesh skeleton integration', () => { it('teacup resolves remote app-scope + request-scope into a local handler', async () => { - const teapot = createApp({ modules: [TeapotModule], 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 url = `ws://127.0.0.1:${tPort}/__mesh__/control`; - const teacup = createApp({ modules: [TeacupModule], mesh: { teapots: [{ url, secret: SECRET }] } }); + const teacup = createApp({ modules: [TeacupModule], experimental: true, mesh: { teapots: [{ url, secret: SECRET }] } }); const cServer = await teacup.listen(0); const cPort = (cServer.address() as any).port; @@ -40,8 +40,12 @@ describe('mesh skeleton integration', () => { tServer.close(); cServer.close(); }); + it('mesh is gated behind experimental: true', () => { + expect(() => createApp({ modules: [TeapotModule], mesh: { secret: SECRET } })).toThrow(/alpha feature/); + }); + it('teapot still serves its own local route (regression)', async () => { - const app = createApp({ modules: [TeapotModule], mesh: { secret: SECRET } }); + const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); const s = await app.listen(0); const p = (s.address() as any).port; const res = await fetch(`http://127.0.0.1:${p}/api/remote/ping`); expect(await res.json()).toEqual({ pong: true }); @@ -49,9 +53,9 @@ describe('mesh skeleton integration', () => { }); it('rejects a bad secret (teacup boot fails)', async () => { - const teapot = createApp({ modules: [TeapotModule], 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 teacup = createApp({ modules: [TeacupModule], mesh: { teapots: [{ url: `ws://127.0.0.1:${tPort}/__mesh__/control`, secret: 'WRONG' }], timeoutMs: 800 } }); + const teacup = createApp({ modules: [TeacupModule], experimental: true, mesh: { teapots: [{ url: `ws://127.0.0.1:${tPort}/__mesh__/control`, secret: 'WRONG' }], timeoutMs: 800 } }); await expect(teacup.listen(0)).rejects.toThrow(); tServer.close(); }); diff --git a/test/mesh/teacup.test.ts b/test/mesh/teacup.test.ts index fa46063..81f026c 100644 --- a/test/mesh/teacup.test.ts +++ b/test/mesh/teacup.test.ts @@ -11,7 +11,7 @@ const fakeLink = (calls: any[]): Link => ({ describe('teacup buildRemote', () => { it('makes a provider node (app) and a step node (request) with RPC runners returning merge objects', async () => { const calls: any[] = []; - const { providers, steps } = buildRemote(fakeLink(calls), 'ws://t'); + const { providers, steps } = buildRemote(fakeLink(calls)); expect(providers.map((p) => p.name)).toEqual(['config']); expect(steps.map((s) => s.name)).toEqual(['auth']); expect(await providers[0].run({})).toEqual({ config: { url: 'db://x' } }); @@ -22,7 +22,7 @@ describe('teacup buildRemote', () => { it('makes a proxy route entry with method+pattern', async () => { const calls: any[] = []; - const { routes } = buildRemote(fakeLink(calls), 'ws://t'); + const { routes } = buildRemote(fakeLink(calls)); expect(routes[0]).toMatchObject({ method: 'GET', pattern: '/u/:id' }); }); diff --git a/test/multipart.test.ts b/test/multipart.test.ts index e90366c..fa92033 100644 --- a/test/multipart.test.ts +++ b/test/multipart.test.ts @@ -3,10 +3,7 @@ import { parseMultipart, extractBoundary } from '../src/multipart'; const B = 'X-BOUND'; function body(parts: string[]): Buffer { - return Buffer.concat([ - ...parts.map((p) => Buffer.from(`--${B}\r\n${p}\r\n`)), - Buffer.from(`--${B}--\r\n`), - ]); + return Buffer.concat([...parts.map((p) => Buffer.from(`--${B}\r\n${p}\r\n`)), Buffer.from(`--${B}--\r\n`)]); } const field = (name: string, val: string) => `Content-Disposition: form-data; name="${name}"\r\n\r\n${val}`; const file = (name: string, fn: string, ct: string, data: string) => @@ -22,61 +19,67 @@ describe('extractBoundary', () => { }); describe('parseMultipart', () => { - it('single text field is NOT lost (first-part off-by-one guard)', () => { - const r = parseMultipart(body([field('title', 'hello')]), B, opts); + it('single text field is decoded', async () => { + const r = await parseMultipart(body([field('title', 'hello')]), B, opts); expect(r.fields.title).toBe('hello'); }); - it('multiple distinct fields', () => { - const r = parseMultipart(body([field('a', '1'), field('b', '2')]), B, opts); + + it('multiple distinct fields', async () => { + const r = await parseMultipart(body([field('a', '1'), field('b', '2')]), B, opts); expect(r.fields).toEqual({ a: '1', b: '2' }); }); - it("duplicates 'last' vs 'array'", () => { + + it("duplicates 'last' vs 'array'", async () => { const b = body([field('t', 'x'), field('t', 'y')]); - expect(parseMultipart(b, B, { maxParts: 1000, duplicates: 'last' }).fields.t).toBe('y'); - expect(parseMultipart(b, B, { maxParts: 1000, duplicates: 'array' }).fields.t).toEqual(['x', 'y']); + expect((await parseMultipart(b, B, { maxParts: 1000, duplicates: 'last' })).fields.t).toBe('y'); + expect((await parseMultipart(b, B, { maxParts: 1000, duplicates: 'array' })).fields.t).toEqual(['x', 'y']); }); - it('single file: metadata + exact bytes incl. embedded CRLF and boundary-like text', () => { - const payload = 'ab\r\n--X-BOUNDnope\r\ncd'; - const r = parseMultipart(body([file('doc', 'a.txt', 'text/plain', payload)]), B, opts); + + it('single file: metadata + exact bytes incl. embedded CRLF and dashes', async () => { + // A real boundary is a random token that never appears in content; this exercises CRLF + `--` runs. + const payload = 'ab\r\ncd\r\n--decoy--\r\nef'; + const r = await parseMultipart(body([file('doc', 'a.txt', 'text/plain', payload)]), B, opts); const f = r.files.doc as any; expect(f.filename).toBe('a.txt'); expect(f.contentType).toBe('text/plain'); expect(f.size).toBe(Buffer.byteLength(payload)); expect(f.data.toString()).toBe(payload); }); - it('multiple files same name → array', () => { - const r = parseMultipart(body([file('f', '1', 'text/plain', 'a'), file('f', '2', 'text/plain', 'b')]), B, opts); + + it('multiple files same name → array', async () => { + const r = await parseMultipart( + body([file('f', '1', 'text/plain', 'a'), file('f', '2', 'text/plain', 'b')]), + B, + opts, + ); expect(Array.isArray(r.files.f)).toBe(true); expect((r.files.f as any).length).toBe(2); }); - it('mixed fields + files', () => { - const r = parseMultipart(body([field('name', 'joe'), file('avatar', 'p.png', 'image/png', 'PNG')]), B, opts); + + it('mixed fields + files', async () => { + const r = await parseMultipart(body([field('name', 'joe'), file('avatar', 'p.png', 'image/png', 'PNG')]), B, opts); expect(r.fields.name).toBe('joe'); expect((r.files.avatar as any).filename).toBe('p.png'); }); - it('case-insensitive headers + filename-before-name (order independent)', () => { + + it('case-insensitive headers + filename-before-name (order independent)', async () => { const part = `content-disposition: form-data; filename="z.bin"; name="up"\r\ncontent-type: application/octet-stream\r\n\r\nDATA`; - const r = parseMultipart(body([part]), B, opts); + const r = await parseMultipart(body([part]), B, opts); expect((r.files.up as any).filename).toBe('z.bin'); }); - it('filename="" with empty body is skipped', () => { + + it('filename="" with empty body is skipped', async () => { const part = `Content-Disposition: form-data; name="up"; filename=""\r\n\r\n`; - const r = parseMultipart(body([part]), B, opts); + const r = await parseMultipart(body([part]), B, opts); expect(r.files.up).toBeUndefined(); }); - it('malformed → throws: no boundary present', () => { - expect(() => parseMultipart(Buffer.from('garbage'), B, opts)).toThrow(); - }); - it('malformed → throws: part without name', () => { - const part = `Content-Disposition: form-data\r\n\r\nx`; - expect(() => parseMultipart(body([part]), B, opts)).toThrow(); - }); - it('malformed → throws: part with no header/body separator', () => { - const raw = Buffer.from(`--${B}\r\nContent-Disposition: form-data; name="a"\r\n--${B}--\r\n`); - expect(() => parseMultipart(raw, B, opts)).toThrow(); - }); - it('parts over maxParts → throws', () => { + + it('more parts than maxParts → rejects', async () => { const b = body([field('a', '1'), field('b', '2'), field('c', '3')]); - expect(() => parseMultipart(b, B, { maxParts: 2, duplicates: 'last' })).toThrow(); + await expect(parseMultipart(b, B, { maxParts: 2, duplicates: 'last' })).rejects.toThrow(); + }); + + it('malformed input with no matching boundary → rejects', async () => { + await expect(parseMultipart(Buffer.from('garbage'), B, opts)).rejects.toThrow(); }); }); diff --git a/test/params.test.ts b/test/params.test.ts index 7de01ec..4dd1b7b 100644 --- a/test/params.test.ts +++ b/test/params.test.ts @@ -1,6 +1,19 @@ import 'reflect-metadata'; import { expect, test, describe, it } from 'vitest'; -import { needs, ctx, param, query, body, inbound, abort, getArgs, getHandlerNeeds, resolveArgs } from '../src/params'; +import { + needs, + ctx, + param, + query, + body, + headers, + header, + inbound, + abort, + getArgs, + getHandlerNeeds, + resolveArgs, +} from '../src/params'; import { ValidationError } from '../src/signals'; class Ctl { @@ -10,7 +23,9 @@ class Ctl { @query() _q: unknown, @query(['a', 'b']) _sub: unknown, @ctx() _c: unknown, - ) { return null; } + ) { + return null; + } } test('getArgs returns specs sorted by parameter index', () => { @@ -43,13 +58,21 @@ test('resolveArgs builds positional args from context', async () => { }); test('a handler with no arg decorators resolves to no args', async () => { - class Bare { ping() { return 1; } } + class Bare { + ping() { + return 1; + } + } expect(await resolveArgs(getArgs(Bare, 'ping'), {})).toEqual([]); }); describe('@inbound / @abort', () => { it('resolves inbound and abort from reserved context keys, not as bags', async () => { - class Ctl { handle(@inbound() inc: AsyncIterable, @abort() sig: AbortSignal) { return [inc, sig]; } } + class Ctl { + handle(@inbound() inc: AsyncIterable, @abort() sig: AbortSignal) { + return [inc, sig]; + } + } const specs = getArgs(Ctl, 'handle'); const ac = new AbortController(); const inc = (async function* () {})(); @@ -59,14 +82,47 @@ describe('@inbound / @abort', () => { }); it('inbound/abort do not count as graph needs', () => { - class Ctl { handle(@inbound() _i: AsyncIterable, @abort() _a: AbortSignal) {} } + class Ctl { + handle(@inbound() _i: AsyncIterable, @abort() _a: AbortSignal) {} + } expect(getHandlerNeeds(getArgs(Ctl, 'handle'))).toEqual([]); }); }); +describe('@headers / @header', () => { + const reqHeaders = { authorization: 'Bearer t0ken', 'x-trace': 'abc', 'x-count': '5' }; + + it('@header(name) and @headers(name) both pick a single header', async () => { + class Ctl { + handle(@header('authorization') _auth: string, @headers('x-trace') _trace: string) {} + } + const args = await resolveArgs(getArgs(Ctl, 'handle'), { headers: reqHeaders }); + expect(args[0]).toBe('Bearer t0ken'); + expect(args[1]).toBe('abc'); + }); + + it('@headers() returns the whole bag and @headers([...]) picks several', async () => { + class Ctl { + handle(@headers() _all: unknown, @headers(['authorization', 'x-trace']) _some: unknown) {} + } + const args = await resolveArgs(getArgs(Ctl, 'handle'), { headers: reqHeaders }); + expect(args[0]).toEqual(reqHeaders); + expect(args[1]).toEqual({ authorization: 'Bearer t0ken', 'x-trace': 'abc' }); + }); + + it('@header(name, schema) validates the picked header', async () => { + class Ctl { + handle(@header('x-count', numFromStr) _count: number) {} + } + const args = await resolveArgs(getArgs(Ctl, 'handle'), { headers: reqHeaders }); + expect(args[0]).toBe(5); + }); +}); + const numFromStr = { '~standard': { - version: 1 as const, vendor: 'test', + version: 1 as const, + vendor: 'test', validate: (v: unknown) => { const n = Number(v); return Number.isNaN(n) ? { issues: [{ message: 'not a number', path: ['n'] }] } : { value: n }; @@ -79,7 +135,9 @@ const asyncSchema = { describe('resolveArgs validation', () => { it('valid: substitutes the parsed/coerced value; ctx source untouched', async () => { - class C { m(@query(numFromStr) _q: number) {} } + class C { + m(@query(numFromStr) _q: number) {} + } const specs = getArgs(C, 'm'); const ctx: any = { query: '42' }; const args = await resolveArgs(specs, ctx); @@ -87,29 +145,45 @@ describe('resolveArgs validation', () => { expect(ctx.query).toBe('42'); }); it('invalid: throws ValidationError with source', async () => { - class C { m(@body(numFromStr) _b: number) {} } + class C { + m(@body(numFromStr) _b: number) {} + } const specs = getArgs(C, 'm'); await expect(resolveArgs(specs, { body: 'nope' })).rejects.toBeInstanceOf(ValidationError); - await resolveArgs(specs, { body: 'nope' }).catch((e) => { expect(e.source).toBe('body'); expect(e.issues[0].message).toBe('not a number'); }); + await resolveArgs(specs, { body: 'nope' }).catch((e) => { + expect(e.source).toBe('body'); + expect(e.issues[0].message).toBe('not a number'); + }); }); it('async schema is awaited', async () => { - class C { m(@body(asyncSchema) _b: string) {} } + class C { + m(@body(asyncSchema) _b: string) {} + } const args = await resolveArgs(getArgs(C, 'm'), { body: 'x' }); expect(args[0]).toBe('async:x'); }); it('@param(name, schema) validates the named param (slot-2 schema)', async () => { - class C { m(@param('id', numFromStr) _id: number) {} } + class C { + m(@param('id', numFromStr) _id: number) {} + } const args = await resolveArgs(getArgs(C, 'm'), { params: { id: '7' } }); expect(args[0]).toBe(7); }); it('non-schema decorators unchanged: @body("key"), @body(), @query(["a","b"])', async () => { - class C { m(@body('x') _x: any, @body() _b: any, @query(['a', 'b']) _q: any) {} } + class C { + m(@body('x') _x: any, @body() _b: any, @query(['a', 'b']) _q: any) {} + } const args = await resolveArgs(getArgs(C, 'm'), { body: { x: 1, y: 2 }, query: { a: 'A', b: 'B', c: 'C' } }); expect(args[0]).toBe(1); expect(args[1]).toEqual({ x: 1, y: 2 }); expect(args[2]).toEqual({ a: 'A', b: 'B' }); }); it('decoration-time guard: a non-schema object throws', () => { - expect(() => { class C { m(@body({} as any) _b: any) {} } return C; }).toThrow(); + expect(() => { + class C { + m(@body({} as any) _b: any) {} + } + return C; + }).toThrow(); }); }); diff --git a/test/router.test.ts b/test/router.test.ts new file mode 100644 index 0000000..8211960 --- /dev/null +++ b/test/router.test.ts @@ -0,0 +1,52 @@ +import { describe, it, expect } from 'vitest'; +import { matchPattern, matchRoute, allowedMethods } from '../src/http/router'; +import type { RouteDef } from '../src/http/types'; + +const route = (method: string, pattern: string): RouteDef => ({ + method, + pattern, + transport: 'buffer', + handler: async () => ({ status: 200, headers: {}, body: '' }), +}); + +describe('matchPattern', () => { + it('matches static and :param segments, decoding params', () => { + expect(matchPattern('/users/:id', '/users/a%20b')).toEqual({ id: 'a b' }); + expect(matchPattern('/users/:id', '/users')).toBeUndefined(); + expect(matchPattern('/users', '/users/1')).toBeUndefined(); + }); + + it(':name* captures the rest of the path, slashes included', () => { + expect(matchPattern('/files/:path*', '/files/img/2026/logo.png')).toEqual({ path: 'img/2026/logo.png' }); + expect(matchPattern('/files/:path*', '/files/a%2Fb')).toEqual({ path: 'a/b' }); + }); + + it(':name* matches zero remaining segments as an empty string', () => { + expect(matchPattern('/files/:path*', '/files')).toEqual({ path: '' }); + }); +}); + +describe('matchRoute precedence', () => { + it('static beats :param beats catch-all regardless of registration order', () => { + const routes = [route('GET', '/a/:rest*'), route('GET', '/a/:id'), route('GET', '/a/b')]; + expect(matchRoute(routes, 'GET', '/a/b')?.def.pattern).toBe('/a/b'); + expect(matchRoute(routes, 'GET', '/a/x')?.def.pattern).toBe('/a/:id'); + expect(matchRoute(routes, 'GET', '/a/x/y')?.def.pattern).toBe('/a/:rest*'); + }); + + it('returns undefined when no pattern matches the path', () => { + expect(matchRoute([route('GET', '/a')], 'GET', '/b')).toBeUndefined(); + }); + + it('does not match a route registered under a different method', () => { + expect(matchRoute([route('POST', '/a')], 'GET', '/a')).toBeUndefined(); + }); +}); + +describe('allowedMethods (405 support)', () => { + it('lists distinct methods whose pattern matches the path', () => { + const routes = [route('GET', '/a'), route('POST', '/a'), route('GET', '/b')]; + expect(allowedMethods(routes, '/a').sort()).toEqual(['GET', 'POST']); + expect(allowedMethods(routes, '/nope')).toEqual([]); + }); +}); diff --git a/test/transport-security.test.ts b/test/transport-security.test.ts index 7f880d9..3228f5a 100644 --- a/test/transport-security.test.ts +++ b/test/transport-security.test.ts @@ -187,7 +187,7 @@ describe('CORS', () => { expect(r.headers.get('access-control-allow-credentials')).toBe('true'); }); - it('disallowed origin → no allow-origin; bare OPTIONS (no ACRM) falls through to 404', async () => { + it('disallowed origin → no allow-origin; bare OPTIONS (no ACRM) → 405 Allow for an existing path', async () => { @Route('/') class C { @Get('/x') x() { return { ok: 1 }; } } @Module({ mountpoint: '/', controllers: [C] }) class CMod {} app = createApp({ modules: [CMod], cors: { origins: 'https://a.com' } }); @@ -195,8 +195,11 @@ describe('CORS', () => { const port = (server.address() as any).port; 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(); - const bare = await fetch(`http://127.0.0.1:${port}/x`, { method: 'OPTIONS' }); // no ACRM - expect(bare.status).toBe(404); + // A bare OPTIONS (no Access-Control-Request-Method) isn't a CORS preflight; the path exists + // under GET, so the router answers 405 with an Allow header rather than 404. + const bare = await fetch(`http://127.0.0.1:${port}/x`, { method: 'OPTIONS' }); + expect(bare.status).toBe(405); + expect(bare.headers.get('allow')).toContain('GET'); }); it("merges a handler's Title-Case Vary with CORS's Origin", async () => { From 654c0563fc47b600c5fb1889a6545a3f6c48f344 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Tue, 7 Jul 2026 12:02:17 -0500 Subject: [PATCH 076/139] docs: honest README + quickstart, and a Starlight documentation site MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bring the README in line with what shipped and fill the gaps a technical reader comparing frameworks needs: the busboy peer dep and dual build, a Routing section with its limits, an explicit "bring your own auth" scope note, why legacy decorators is a design choice (not laziness), and CalVer beta versioning. Add a full Astro Starlight docs site under website/ — getting started, concepts, per-feature guides, and an API reference — migrated from the tested quickstart so the examples stay accurate. Signed-off-by: Diego Resendez --- README.md | 45 +- docs/quickstart.md | 8 +- website/astro.config.mjs | 53 + website/package-lock.json | 6866 +++++++++++++++++ website/package.json | 15 + website/src/content.config.ts | 7 + website/src/content/docs/concepts/flow.md | 24 + .../src/content/docs/concepts/the-graph.md | 47 + website/src/content/docs/getting-started.md | 84 + website/src/content/docs/guides/arguments.md | 148 + .../docs/guides/dependency-injection.md | 146 + .../src/content/docs/guides/introspection.md | 55 + website/src/content/docs/guides/mesh.md | 67 + website/src/content/docs/guides/plugins.md | 58 + website/src/content/docs/guides/routing.md | 64 + website/src/content/docs/guides/security.md | 101 + website/src/content/docs/guides/streaming.md | 114 + website/src/content/docs/guides/testing.md | 33 + website/src/content/docs/guides/uploads.md | 64 + website/src/content/docs/guides/validation.md | 84 + website/src/content/docs/index.mdx | 41 + .../src/content/docs/reference/createapp.md | 70 + .../src/content/docs/reference/decorators.md | 83 + website/tsconfig.json | 5 + 24 files changed, 8275 insertions(+), 7 deletions(-) create mode 100644 website/astro.config.mjs create mode 100644 website/package-lock.json create mode 100644 website/package.json create mode 100644 website/src/content.config.ts create mode 100644 website/src/content/docs/concepts/flow.md create mode 100644 website/src/content/docs/concepts/the-graph.md create mode 100644 website/src/content/docs/getting-started.md create mode 100644 website/src/content/docs/guides/arguments.md create mode 100644 website/src/content/docs/guides/dependency-injection.md create mode 100644 website/src/content/docs/guides/introspection.md create mode 100644 website/src/content/docs/guides/mesh.md create mode 100644 website/src/content/docs/guides/plugins.md create mode 100644 website/src/content/docs/guides/routing.md create mode 100644 website/src/content/docs/guides/security.md create mode 100644 website/src/content/docs/guides/streaming.md create mode 100644 website/src/content/docs/guides/testing.md create mode 100644 website/src/content/docs/guides/uploads.md create mode 100644 website/src/content/docs/guides/validation.md create mode 100644 website/src/content/docs/index.mdx create mode 100644 website/src/content/docs/reference/createapp.md create mode 100644 website/src/content/docs/reference/decorators.md create mode 100644 website/tsconfig.json diff --git a/README.md b/README.md index d7079d1..307be60 100644 --- a/README.md +++ b/README.md @@ -2,10 +2,13 @@ > A calm, type-safe HTTP framework for Node. Your API is an explicit **dependency graph** you can see, slice, and trust — not a mutable bag threaded through positional middleware. -`@green-tea/core` — **beta**, RC-track. One runtime dependency: `reflect-metadata` (`ws` is an optional peer, only for WebSocket/mesh). +`@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 npm install @green-tea/core reflect-metadata +# optional, only if you use them: +npm install ws # WebSocket routes (@Ws) and mesh +npm install busboy # multipart/form-data file uploads ``` --- @@ -77,9 +80,10 @@ Beta shipped the parts a real API needs, without growing the runtime dependency - **Secure by default.** `nosniff`, `X-Frame-Options`, `Referrer-Policy`, HSTS-when-secure — on every response, opt-out with one flag. - **CORS** with a guarded preflight and the credentials-never-`*` rule enforced for you. - **Validation via [Standard Schema](https://standardschema.dev).** `@body(schema)` accepts zod, valibot, or arktype — you bring the validator, the core stays zero-dep. Invalid input → `422` with per-field issues; the parsed value reaches your handler typed. -- **Real body parsing.** JSON, urlencoded, and `multipart/form-data` file uploads (`@body()` → `{ fields, files }`), 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. - **Graceful shutdown.** `app.close()` drains in-flight requests, closes live streams and mesh links. - **Testable by construction.** `createApp({ overrides: { db: fakeDb } })` swaps any node in one line. +- **Dual ESM + CommonJS.** Ships both builds behind an `exports` map — `import` and `require` both resolve, with matching type declarations. ## Benchmarks @@ -103,7 +107,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 | | **Cross-service calls** | HTTP client / gRPC by hand | HTTP client / gRPC | Microservices transport + message patterns | — | **`@needs('x')` resolves on another node** | | **Plugin can break your pipeline?** | yes (deletes your body parser) | encapsulated, but hooks are global | interceptor order matters | yes | **no** — plugins only `bus.on` + `scope.add` | -| **Runtime deps** | minimal | minimal | heavy (rxjs, reflect-metadata, …) | Express + InversifyJS | **`reflect-metadata` only** (`ws` optional) | +| **Runtime deps** | minimal | minimal | heavy (rxjs, reflect-metadata, …) | Express + InversifyJS | **`reflect-metadata` only** (`ws`, `busboy` optional) | ### Read it as a story @@ -170,18 +174,45 @@ The handler signature declares exactly what it wants — in any order, nothing m | `@param(...)` | route params | `()` · `('id')` · `('id', schema)` | | `@query(...)` | parsed query string | `()` · `('q')` · `(['a','b'])` · `(schema)` | | `@body(...)` | parsed body (JSON / urlencoded / multipart) | `()` · `('field')` · `(schema)` | -| `@headers(...)` | request headers | `()` · `('authorization')` · `(schema)` | +| `@headers(...)` | request headers (whole bag or picked) | `()` · `('authorization')` · `(['a','b'])` · `(schema)` | +| `@header('name')` | one request header (singular alias of `@headers`) | `('x-trace')` · `('x-count', schema)` | `@needs` keys are validated at boot: nothing provides the key → `createApp` throws with a clear error instead of serving `undefined`. Pass a Standard Schema (`@body(User)`) and the value is validated, coerced, and typed before your handler sees it. +> **Optional providers degrade, they don't crash.** A provider marked `optional: true` that throws on boot does **not** abort startup — it is left unregistered and logged. On `listen()` the app prints a one-line summary of what's running degraded, and the list is queryable via `app.degraded()`. Routes that actually need a degraded provider fail at request time, not at boot. This is deliberate (graceful degradation); wire an alert off `app.degraded()` or the `boot:provider:fail` bus event in production so a degraded start is never silent. + +## Routing + +Patterns match by segment: static, `:param` (one segment), and a trailing `:name*` **catch-all** that captures the rest of the path — slashes included — into `params.name`. When more than one route matches, the **most specific wins** (static ▸ `:param` ▸ catch-all), independent of registration order. A path that exists under a *different* method returns **`405` with an `Allow` header**, not `404`. + +```typescript +@Get('/files/:path*') // /files/img/2026/logo.png → params.path = "img/2026/logo.png" +``` + +**Not yet** (post-beta, on the roadmap): regex / typed param constraints like `:id(\d+)`, and route matching is a linear scan — fine for typical route tables, but a radix-tree matcher for very large ones isn't built. + ## Two layers 1. **Typed functional core (`flow`)** — `flow().step(...).step(...).handle(...)`; step outputs accumulate into the context type (`Acc & Out`). This is where the compile-time guarantee lives. 2. **Declarative decorator layer** — `@Provider/@Step/@Module/@Route/@Get/@Transformer` + argument decorators. Emits runtime metadata, builds and topologically sorts the graph, validates at boot. +## Why legacy decorators + +green-tea uses **legacy** (experimental) decorators — you set `experimentalDecorators: true` in your `tsconfig`. This is a design decision, not inertia. + +The framework's argument injection (`@param`, `@query`, `@body`, `@header`, `@needs`, `@ctx`, `@inbound`, `@abort`) relies on **parameter decorators** — and the TC39 standard decorators proposal (Stage 3) deliberately does **not** include them. There is no standards-track way to decorate a parameter today, so a handler like `handler(@param('id') id: string)` is only expressible with legacy decorators. + +"Stage 3" also means *not finalized*: the proposal can still change before engines ship it. We track it, and if parameter injection ever gets a viable standard path we'll revisit. Until then, legacy decorators are the right tool for this API — not a shortcut. (We don't rely on `emitDecoratorMetadata`/`design:type` reflection; argument positions are recorded explicitly, so this is the only legacy surface we depend on.) + ## Honest scope -green-tea is **beta**, on the road to a release candidate. Express and Fastify have a decade of ecosystem; NestJS has enterprise tooling and a huge plugin catalog. green-tea's mesh is a walking skeleton — distributed DI works, but discovery, load-balancing, and failover are not built yet. Pick green-tea for the model and the ergonomics, not the ecosystem — *yet*. +green-tea is **beta**, on the road to a release candidate. Express and Fastify have a decade of ecosystem; NestJS has enterprise tooling and a huge plugin catalog. Pick green-tea for the model and the ergonomics, not the ecosystem — *yet*. + +**Bring your own auth (and friends).** green-tea ships transport security — TLS/wss, secure-by-default headers, CORS — but **not** authentication, authorization, rate-limiting, CSRF, or sessions. You compose those as steps and plugins (the `Authenticate` step in the quick look is the pattern). Unlike Express/Fastify, there is no off-the-shelf plugin ecosystem for them yet. + +**Node only.** Runs on Node ≥ 18. Deno / Bun / edge runtimes (over web-standard `Request`/`Response`) are on the roadmap, not built — only `src/http/` is runtime-specific today. + +**mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet. ## Docs & development @@ -207,7 +238,9 @@ npm run bench # regenerate BENCHMARKS.md ## Versioning -green-tea uses **calendar versioning**: `YY.MM.PATCH` (e.g. `26.07.0` = the first release cut in July 2026, patch 0). A version tells you *when* it shipped; breaking changes are called out in the [CHANGELOG](./CHANGELOG.md). +green-tea uses **calendar versioning**: `YY.MM.PATCH` (e.g. `26.07.0` = the first release cut in July 2026, patch 0). 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.07.0-beta.0`) and publish under the npm `beta` dist-tag — so a plain `npm install @green-tea/core` won't pick one up until the first stable calendar release. The API can still change between betas. ## License diff --git a/docs/quickstart.md b/docs/quickstart.md index edd04ca..2077037 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -165,6 +165,9 @@ bounded buffer (`channel({ buffer: 100 })`, drop-oldest). 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 @@ -180,7 +183,7 @@ class Svc { @Get('/ping', { export: true }) ping() { return { pong: true }; } } @Module({ mountpoint: '/api', providers: [Config], steps: [Auth], controllers: [Svc] }) class TeapotModule {} -const teapot = createApp({ modules: [TeapotModule], mesh: { secret: 'shh' } }); +const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'shh' } }); await teapot.listen(3002); ``` @@ -199,6 +202,7 @@ class TeacupModule {} const teacup = createApp({ modules: [TeacupModule], + experimental: true, mesh: { teapots: [{ url: 'ws://A-host:3002/__mesh__/control', secret: 'shh' }] }, }); await teacup.listen(3003); @@ -309,6 +313,8 @@ to the WebSocket handshake (101/upgrade) response. ## 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: diff --git a/website/astro.config.mjs b/website/astro.config.mjs new file mode 100644 index 0000000..ad5f45a --- /dev/null +++ b/website/astro.config.mjs @@ -0,0 +1,53 @@ +import { defineConfig } from 'astro/config'; +import starlight from '@astrojs/starlight'; + +// Docs site for @green-tea/core. Content lives in src/content/docs/**. +export default defineConfig({ + site: 'https://green-tea.dev', + integrations: [ + starlight({ + title: 'green-tea', + description: 'A calm, type-safe HTTP framework for Node — your API is an explicit dependency graph.', + tableOfContents: { minHeadingLevel: 2, maxHeadingLevel: 3 }, + sidebar: [ + { + label: 'Start here', + items: [ + { label: 'Introduction', link: '/' }, + { label: 'Getting started', slug: 'getting-started' }, + ], + }, + { + label: 'Concepts', + items: [ + { label: 'The dependency graph', slug: 'concepts/the-graph' }, + { label: 'The typed flow core', slug: 'concepts/flow' }, + ], + }, + { + label: 'Guides', + items: [ + { label: 'Routing', slug: 'guides/routing' }, + { label: 'Dependency injection', slug: 'guides/dependency-injection' }, + { label: 'Argument decorators', slug: 'guides/arguments' }, + { label: 'Validation', slug: 'guides/validation' }, + { label: 'Streaming & real-time', slug: 'guides/streaming' }, + { label: 'File uploads', slug: 'guides/uploads' }, + { label: 'Transport security', slug: 'guides/security' }, + { label: 'Plugins & observability', slug: 'guides/plugins' }, + { label: 'Graph introspection', slug: 'guides/introspection' }, + { label: 'Testing', slug: 'guides/testing' }, + { label: 'Mesh (alpha)', slug: 'guides/mesh', badge: { text: 'alpha', variant: 'caution' } }, + ], + }, + { + label: 'Reference', + items: [ + { label: 'Decorators', slug: 'reference/decorators' }, + { label: 'createApp options', slug: 'reference/createapp' }, + ], + }, + ], + }), + ], +}); diff --git a/website/package-lock.json b/website/package-lock.json new file mode 100644 index 0000000..25266d2 --- /dev/null +++ b/website/package-lock.json @@ -0,0 +1,6866 @@ +{ + "name": "green-tea-docs", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "green-tea-docs", + "dependencies": { + "@astrojs/starlight": "^0.41.3", + "astro": "^7.0.6", + "sharp": "^0.35.3" + } + }, + "node_modules/@astrojs/compiler-binding": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@astrojs/compiler-binding/-/compiler-binding-0.3.0.tgz", + "integrity": "sha512-zlsOT5COD9hRwplJCgQhS21unxON5AKirf0vgt1ijXwuseYIaZdm2ZOpF8fsz+DY9EyXx+I/ukxtg7uoBep68A==", + "license": "MIT", + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@astrojs/compiler-binding-darwin-arm64": "0.3.0", + "@astrojs/compiler-binding-darwin-x64": "0.3.0", + "@astrojs/compiler-binding-linux-arm64-gnu": "0.3.0", + "@astrojs/compiler-binding-linux-arm64-musl": "0.3.0", + "@astrojs/compiler-binding-linux-x64-gnu": "0.3.0", + "@astrojs/compiler-binding-linux-x64-musl": "0.3.0", + "@astrojs/compiler-binding-wasm32-wasi": "0.3.0", + "@astrojs/compiler-binding-win32-arm64-msvc": "0.3.0", + "@astrojs/compiler-binding-win32-x64-msvc": "0.3.0" + } + }, + "node_modules/@astrojs/compiler-binding-darwin-arm64": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-darwin-arm64/-/compiler-binding-darwin-arm64-0.3.0.tgz", + "integrity": "sha512-3n0uu+uJpnCq8b4JFi3uGDsIisAvHctxSmH+cIO9Gbei1H1Y1QXaYboXyiWJugUmprr3OEYP7+LdodzpVFzLMQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@astrojs/compiler-binding-darwin-x64": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-darwin-x64/-/compiler-binding-darwin-x64-0.3.0.tgz", + "integrity": "sha512-scxNGKjOBydMo1QR4LtK0FMgh7ubQomJDv953nz2msQFkPKke/0FpPv/cQM0T/kuZdReZQFU8Oz3iOrP/6WHEg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@astrojs/compiler-binding-linux-arm64-gnu": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-arm64-gnu/-/compiler-binding-linux-arm64-gnu-0.3.0.tgz", + "integrity": "sha512-NZrWLolVUANmrnl0zrFK/Sx5Sock1gEUT49ALfMTTCA5Ya2ec/BoJXMIg4KgE+wZcrdXJ8e+WyEhM7YLk/FJkA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@astrojs/compiler-binding-linux-arm64-musl": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-arm64-musl/-/compiler-binding-linux-arm64-musl-0.3.0.tgz", + "integrity": "sha512-PjwRmKgMFDsFhg82g0poXlIY8Qn3fMA3hXjaR0coJWJzTJsRH9ATU0j2ocigjtU1h3vL/yR7yLUxGj/lTCq73g==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@astrojs/compiler-binding-linux-x64-gnu": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-x64-gnu/-/compiler-binding-linux-x64-gnu-0.3.0.tgz", + "integrity": "sha512-Dr69VJYlnSfyL8gzELW6S4mE41P7TDPn1IKjwMnjdZ7+dxgJI50oMLFSk1LVe26bHmWB3ktuh8fDVK1THI9e9A==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@astrojs/compiler-binding-linux-x64-musl": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-x64-musl/-/compiler-binding-linux-x64-musl-0.3.0.tgz", + "integrity": "sha512-AEt+bRw8PfImCcyRH1lpXVB8CdmQ1K/wPo5u99iec4/U/XdNvQZ715YVuNzIJpbJXelgQeZ5H2+Ea7XwRyWY5g==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@astrojs/compiler-binding-wasm32-wasi": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-wasm32-wasi/-/compiler-binding-wasm32-wasi-0.3.0.tgz", + "integrity": "sha512-U80tA1j8V6LjhiTZzVCtG4E8hrNVVNXDGV5fCgJ94q8FU9CPH+XwdDDhLzBybfWhKfyItXmQiZNRPTiPCYTpVg==", + "cpu": [ + "wasm32" + ], + "license": "MIT", + "optional": true, + "dependencies": { + "@napi-rs/wasm-runtime": "^1.1.6" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@astrojs/compiler-binding-win32-arm64-msvc": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-win32-arm64-msvc/-/compiler-binding-win32-arm64-msvc-0.3.0.tgz", + "integrity": "sha512-CpY1RII2r1XMpOUVD1VR/F2wtuRsiOCkFULS10Khyj8/DFZMtxVuUCAWGw+CW2Ka0h6eP3Xc1CA+glFlvXMPxA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@astrojs/compiler-binding-win32-x64-msvc": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-win32-x64-msvc/-/compiler-binding-win32-x64-msvc-0.3.0.tgz", + "integrity": "sha512-qmFbs769oeeGrRebAnCW7aBk8m71vf85W/dX/jddfx5Z06/w0wf7TZCfJPOX1Fld2t+4N+iXzfGEJG+zJQ+bzg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@astrojs/compiler-rs": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@astrojs/compiler-rs/-/compiler-rs-0.3.0.tgz", + "integrity": "sha512-J2qEVHtIDjEM9TxwmwuebOGmZNwhKu/dR7P7qBpnJKGmBBX0vdweQ/4cEXhj8fBbWVUB5V12xWChri3CgKNULQ==", + "license": "MIT", + "dependencies": { + "@astrojs/compiler-binding": "0.3.0" + }, + "engines": { + "node": ">=22.12.0" + } + }, + "node_modules/@astrojs/internal-helpers": { + "version": "0.10.1", + "resolved": "https://registry.npmjs.org/@astrojs/internal-helpers/-/internal-helpers-0.10.1.tgz", + "integrity": "sha512-5phcroT/vmOOrYuuAxtkbPixy5hePtlz9i8K4OeDv3dNK6/UQRuXPOSRTxIOBbUY5Sonw2UaxjbuVc43Mcir6Q==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.4", + "@types/mdast": "^4.0.4", + "js-yaml": "^4.1.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/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/markdown-satteri": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/@astrojs/markdown-satteri/-/markdown-satteri-0.3.3.tgz", + "integrity": "sha512-Lje33Ittd8UQGgbIIWQvhPkj5X5c4b1sZnZWX3JQV/AWpfbuQGxVi2ONt6+ScydcwfR4egilslEWyczMclrJ1g==", + "license": "MIT", + "dependencies": { + "@astrojs/internal-helpers": "0.10.1", + "@astrojs/prism": "4.0.2", + "github-slugger": "^2.0.0", + "satteri": "^0.9.1" + } + }, + "node_modules/@astrojs/mdx": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@astrojs/mdx/-/mdx-7.0.2.tgz", + "integrity": "sha512-l+sJY5U1KkGZUdr+bIL4Y6BefeS549qoSHVSkUSs6A9INwdCND+/0+vN0NroPBXwl5Vcg5u78t7VQRsJjePxbw==", + "license": "MIT", + "dependencies": { + "@astrojs/internal-helpers": "0.10.1", + "@astrojs/markdown-remark": "7.2.1", + "@mdx-js/mdx": "^3.1.1", + "acorn": "^8.16.0", + "es-module-lexer": "^2.0.0", + "estree-util-visit": "^2.0.0", + "hast-util-to-html": "^9.0.5", + "piccolore": "^0.1.3", + "rehype-raw": "^7.0.0", + "remark-gfm": "^4.0.1", + "remark-smartypants": "^3.0.2", + "source-map": "^0.7.6", + "unist-util-visit": "^5.1.0", + "vfile": "^6.0.3" + }, + "engines": { + "node": ">=22.12.0" + }, + "peerDependencies": { + "@astrojs/markdown-satteri": "^0.3.1", + "astro": "^7.0.0" + }, + "peerDependenciesMeta": { + "@astrojs/markdown-satteri": { + "optional": true + } + } + }, + "node_modules/@astrojs/prism": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@astrojs/prism/-/prism-4.0.2.tgz", + "integrity": "sha512-KTivpmnz6lDsC6o9H4+DNm2SrE/GHzw8cNAvEJwAvUT+eoaEnn/4NtbDNfRRaxaJHdp15gf+tfHAWiXR4wB3BA==", + "license": "MIT", + "dependencies": { + "prismjs": "^1.30.0" + }, + "engines": { + "node": ">=22.12.0" + } + }, + "node_modules/@astrojs/sitemap": { + "version": "3.7.3", + "resolved": "https://registry.npmjs.org/@astrojs/sitemap/-/sitemap-3.7.3.tgz", + "integrity": "sha512-f8euLVsyeAmAkSm/1M2Kb8sL8byQmfgbvBNaHFItCheTj/IpiJYSEWVcqDHZ/yEHxiS7+w87mQkzwZaPHmk5GA==", + "license": "MIT", + "dependencies": { + "sitemap": "^9.0.0", + "stream-replace-string": "^2.0.0", + "zod": "^4.3.6" + } + }, + "node_modules/@astrojs/starlight": { + "version": "0.41.3", + "resolved": "https://registry.npmjs.org/@astrojs/starlight/-/starlight-0.41.3.tgz", + "integrity": "sha512-8xsG6UpK581TJmtOc7/pnxHKEbP16rV06VLWaVa7FOyE/VEwnaHOsLtL+miifCEfuiuv0Wn+j8u3JSluRQesMQ==", + "license": "MIT", + "dependencies": { + "@astrojs/markdown-satteri": "^0.3.2", + "@astrojs/mdx": "^7.0.0", + "@astrojs/sitemap": "^3.7.2", + "@pagefind/default-ui": "^1.3.0", + "@types/hast": "^3.0.4", + "@types/js-yaml": "^4.0.9", + "@types/mdast": "^4.0.4", + "astro-expressive-code": "^0.44.0", + "bcp-47": "^2.1.0", + "hast-util-from-html": "^2.0.3", + "hast-util-select": "^6.0.4", + "hast-util-to-string": "^3.0.1", + "hastscript": "^9.0.1", + "i18next": "^26.0.7", + "js-yaml": "^4.1.1", + "klona": "^2.0.6", + "magic-string": "^0.30.21", + "mdast-util-directive": "^3.1.0", + "mdast-util-to-markdown": "^2.1.2", + "mdast-util-to-string": "^4.0.0", + "pagefind": "^1.5.2", + "rehype": "^13.0.2", + "rehype-format": "^5.0.1", + "remark-directive": "^4.0.0", + "satteri": "^0.9.1", + "ultrahtml": "^1.6.0", + "unified": "^11.0.5", + "unist-util-visit": "^5.1.0", + "vfile": "^6.0.3" + }, + "peerDependencies": { + "@astrojs/markdown-remark": "^7.2.0", + "astro": "^7.0.2" + }, + "peerDependenciesMeta": { + "@astrojs/markdown-remark": { + "optional": true + } + } + }, + "node_modules/@astrojs/telemetry": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/@astrojs/telemetry/-/telemetry-3.3.2.tgz", + "integrity": "sha512-j8DNruA8ors99Al39RYZPJK4DC1bKkoNm93mAMuBhY9TCNC4R8n1q7ovFnJ5qhGh5Lsh7pa1gpQVpYpsJPeTHQ==", + "license": "MIT", + "dependencies": { + "ci-info": "^4.4.0", + "dset": "^3.1.4", + "is-docker": "^4.0.0", + "is-wsl": "^3.1.1", + "which-pm-runs": "^1.1.0" + }, + "engines": { + "node": "18.20.8 || ^20.3.0 || >=22.0.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", + "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.7.tgz", + "integrity": "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg==", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.7" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.7.tgz", + "integrity": "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==", + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@bruits/satteri-darwin-arm64": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/@bruits/satteri-darwin-arm64/-/satteri-darwin-arm64-0.9.4.tgz", + "integrity": "sha512-W3MSUkr2mZRR8Stoe+lqNAyzQzRuFMU8WffV9IvFSxTok0LGWR0ZZQPLELU4QTRiUbhL2Y4VUP9vV7pj8rHjgg==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@bruits/satteri-darwin-x64": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/@bruits/satteri-darwin-x64/-/satteri-darwin-x64-0.9.4.tgz", + "integrity": "sha512-DXOuuaE1lsv7mpk2mOvGrzqoEWEvOIZEO/fXVa7zfM23Iob+CBjBkRAMwpHA4pmZ3j6Gj7WJzPKw0kQ7w741AQ==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@bruits/satteri-linux-arm64-gnu": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/@bruits/satteri-linux-arm64-gnu/-/satteri-linux-arm64-gnu-0.9.4.tgz", + "integrity": "sha512-gJxU9rGGoqIznSEgEzpjxkry24jeHuMpoo1tCIAhHYh7WaD3j5F8zt3jmHxEaN1Uwa+K5+wFgIR2uIGOnMzEmw==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@bruits/satteri-linux-arm64-musl": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/@bruits/satteri-linux-arm64-musl/-/satteri-linux-arm64-musl-0.9.4.tgz", + "integrity": "sha512-Wjzu9hmmAbfmDkBfPI1VdZygJtYz9uYZQnkEyrXi6S2JFi+2pXQ1A5irj38bqm0IZmWcTbk0cVG4NZnPdtVNJA==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@bruits/satteri-linux-x64-gnu": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/@bruits/satteri-linux-x64-gnu/-/satteri-linux-x64-gnu-0.9.4.tgz", + "integrity": "sha512-MR1Q+wMx65FQlbSV7cRqWW87Knp0zkoaIV55Dt+xZl028wJABXEPEEmG3670SLq7lVZvcGIDwCgSg2kCYxvRwA==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@bruits/satteri-linux-x64-musl": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/@bruits/satteri-linux-x64-musl/-/satteri-linux-x64-musl-0.9.4.tgz", + "integrity": "sha512-T4gxhXve3zyNAZesrXAd/rDZOGRkbfFIUFld4TGsw6BsjoIteCcDji6IMqeXyaWEVSykY2X8Eid2hr6aXGYAaw==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@bruits/satteri-wasm32-wasi": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/@bruits/satteri-wasm32-wasi/-/satteri-wasm32-wasi-0.9.4.tgz", + "integrity": "sha512-/CEG8LUlpaBEnhFnYVn0UnlHFLs51UhrkJBUPDUXLzkadzAcnR88iRA/nOl7Zwhjb4WhfBV4p3P5qeOJMtH0iA==", + "cpu": [ + "wasm32" + ], + "optional": true, + "dependencies": { + "@emnapi/core": "1.11.1", + "@emnapi/runtime": "1.11.1", + "@napi-rs/wasm-runtime": "^1.1.6" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@bruits/satteri-wasm32-wasi/node_modules/@emnapi/core": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.1.tgz", + "integrity": "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.2", + "tslib": "^2.4.0" + } + }, + "node_modules/@bruits/satteri-wasm32-wasi/node_modules/@emnapi/runtime": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.1.tgz", + "integrity": "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@bruits/satteri-win32-arm64-msvc": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/@bruits/satteri-win32-arm64-msvc/-/satteri-win32-arm64-msvc-0.9.4.tgz", + "integrity": "sha512-E1ZPQbgCtFKiU7pFYVndynvY7ne4coeVDUgnVThErSFlJ2ceQCBZrfRTD1lzrIDy63Bbqo+g/cZY9duw+JYjIw==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@bruits/satteri-win32-x64-msvc": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/@bruits/satteri-win32-x64-msvc/-/satteri-win32-x64-msvc-0.9.4.tgz", + "integrity": "sha512-5I7SiarsNdAUuhJb50CXJPTwr/ECVrBoU+fymoLjChK5fW//+srhY4lstcNTzgFRtQSYfVtm4OQZz16CVMeTeA==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@capsizecss/unpack": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@capsizecss/unpack/-/unpack-4.0.1.tgz", + "integrity": "sha512-CuNiSqg7+e1cO/GjffyMOm5Tt2jUF9CWHHnvQ/UkqvtkGfHdgwEC0wpmq7fkN3gxwpRnrAN0WzO3vREKmNolMQ==", + "license": "MIT", + "dependencies": { + "fontkitten": "^1.0.3" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@clack/core": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/@clack/core/-/core-1.4.3.tgz", + "integrity": "sha512-/kr3UWNtdJfxZtPgDqUOmG2pvwlmcLGheex5yiZKdwbzZJxhV+HMNR9QNmyY5cGwTNV6LrR7Jtp+KjhUAP1qBQ==", + "license": "MIT", + "dependencies": { + "fast-wrap-ansi": "^0.2.0", + "sisteransi": "^1.0.5" + }, + "engines": { + "node": ">= 20.12.0" + } + }, + "node_modules/@clack/prompts": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@clack/prompts/-/prompts-1.7.0.tgz", + "integrity": "sha512-y7/yvZ2TPAnR9+jnc00klvNNLkJiXFFrQA/hlLCcxA9a2A4zQIOimyFQ9XfwYKiGD1fb5GY8vbKIIgO8d5Tb2A==", + "license": "MIT", + "dependencies": { + "@clack/core": "1.4.3", + "fast-string-width": "^3.0.2", + "fast-wrap-ansi": "^0.2.0", + "sisteransi": "^1.0.5" + }, + "engines": { + "node": ">= 20.12.0" + } + }, + "node_modules/@ctrl/tinycolor": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@ctrl/tinycolor/-/tinycolor-4.2.0.tgz", + "integrity": "sha512-kzyuwOAQnXJNLS9PSyrk0CWk35nWJW/zl/6KvnTBMFK65gm7U1/Z5BqjxeapjZCIhQcM/DsrEmcbRwDyXyXK4A==", + "license": "MIT", + "engines": { + "node": ">=14" + } + }, + "node_modules/@emnapi/core": { + "version": "1.11.2", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.2.tgz", + "integrity": "sha512-TC8MkTuZUtcTSiFeuC0ksCh9QIJ5+F21MvZ4Wn4ORfYaFJ/0dsiudv5tVkejgwZlwQ39jL9WWDe2lz8x0WglOA==", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.2", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.11.2", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.2.tgz", + "integrity": "sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.2.tgz", + "integrity": "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz", + "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz", + "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz", + "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz", + "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz", + "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz", + "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz", + "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz", + "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz", + "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz", + "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz", + "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz", + "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==", + "cpu": [ + "loong64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz", + "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==", + "cpu": [ + "mips64el" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz", + "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz", + "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz", + "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==", + "cpu": [ + "s390x" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz", + "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz", + "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz", + "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz", + "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz", + "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz", + "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz", + "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz", + "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz", + "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz", + "integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@expressive-code/core": { + "version": "0.44.0", + "resolved": "https://registry.npmjs.org/@expressive-code/core/-/core-0.44.0.tgz", + "integrity": "sha512-xgiF2P6tYUbrhi3+x0S8xHZWT1t3Bvb3U91tAtRbLb9HLejLvYc5GZUqKICKLaUN4iSGhhNJu2fM/aH8e5yCMg==", + "license": "MIT", + "dependencies": { + "@ctrl/tinycolor": "^4.0.4", + "hast-util-select": "^6.0.2", + "hast-util-to-html": "^9.0.1", + "hast-util-to-text": "^4.0.1", + "hastscript": "^9.0.0", + "postcss": "^8.4.38", + "postcss-nested": "^6.0.1", + "unist-util-visit": "^5.0.0", + "unist-util-visit-parents": "^6.0.1" + } + }, + "node_modules/@expressive-code/plugin-frames": { + "version": "0.44.0", + "resolved": "https://registry.npmjs.org/@expressive-code/plugin-frames/-/plugin-frames-0.44.0.tgz", + "integrity": "sha512-V6M6+zVc1GzqCvXkQHc2m5rcFOIVzJgMq5gnfrMnVf2gwtj/sg4H93c1f/mGeqHycubwkHFUDyParAOiGeDZeA==", + "license": "MIT", + "dependencies": { + "@expressive-code/core": "^0.44.0" + } + }, + "node_modules/@expressive-code/plugin-shiki": { + "version": "0.44.0", + "resolved": "https://registry.npmjs.org/@expressive-code/plugin-shiki/-/plugin-shiki-0.44.0.tgz", + "integrity": "sha512-RZsdaqlbGqyAQKuoX4myQXxjmiE2l5KBpJ/gKPh62tCdIdpWyjbzVqSo8+5XsezZxkfi8AJ/J6EUaBTPROFX/Q==", + "license": "MIT", + "dependencies": { + "@expressive-code/core": "^0.44.0", + "shiki": "^4.0.2" + } + }, + "node_modules/@expressive-code/plugin-text-markers": { + "version": "0.44.0", + "resolved": "https://registry.npmjs.org/@expressive-code/plugin-text-markers/-/plugin-text-markers-0.44.0.tgz", + "integrity": "sha512-0/m3A5b+lz2upyNq+wzZ1S69HRoJmyFs5LsR42lVZ9pmGRlBiSBYQpvqlji4DBj1+Riamxc0AvcCr5kuzOQeWA==", + "license": "MIT", + "dependencies": { + "@expressive-code/core": "^0.44.0" + } + }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.35.3", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.3.tgz", + "integrity": "sha512-RMnFX7YQsMoh7lWfcM4NEHHymBX/rLuKNPVM84XE9ONPcaSCDgE7CHIHpSgPcO2xcRthgBy1HfNO319mwhIAkg==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.3.2" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.35.3", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.3.tgz", + "integrity": "sha512-Xo+5uFBtLN0BKqieTxiFzFPQAUlBbbH5iBKyRX/z1JrbnYsHTfKJnUfL8+p2TPXr1pXqao4eeL4Rl144uDpK9w==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.3.2" + } + }, + "node_modules/@img/sharp-freebsd-wasm32": { + "version": "0.35.3", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.3.tgz", + "integrity": "sha512-lUxcqWIj2wMQ9BrwNjngcr1gWUr5xgaGThBRqPPalIC2n67Cqj1uPh8NnA/ZhAg8hUbKl+kVHKwgUIwe6ZYPrg==", + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "dependencies": { + "@img/sharp-wasm32": "0.35.3" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.2.tgz", + "integrity": "sha512-9J6ypZFpQBj4YnePGoq/S38w6nz+vqg5WZLrLGY4YuSemdMq47GMLBPO42MzwdGwpg/agZ7xzZcFHa48xlywfg==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.2.tgz", + "integrity": "sha512-m2pW1n6cns9VaubNwsZ+c3CRYjxNQWgJ5gPlnL1nbBcpkBvFm6SCFN5o0psFHI8w9n11NKhFkeEDns98tiqbEw==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.2.tgz", + "integrity": "sha512-1eMLzy92I4J6rmi4mAT8yC3HxOtniyGELlzGbNMLLeqe052ahFQ0h6LFq+lh5DsDIdYViIDst08abvSbcEdLXQ==", + "cpu": [ + "arm" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.2.tgz", + "integrity": "sha512-dqVSFynCox4C/J8kT16V7SIFAns0IjgLwkvYT7p8LQVmJ5OS5b6tI9IGflxTeuBS//zXeFIUbwt5dwxyZ17cnA==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.2.tgz", + "integrity": "sha512-3z0NHDxD6n5I9gc05U1eW1AyRm+Gznzq3naMrthPNqE6oYykcogW0l/jfpJdjYnuNl8R7yI9pNbE1XiUeyq0Aw==", + "cpu": [ + "ppc64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.2.tgz", + "integrity": "sha512-bsb4rI+NldGOsXuej2r8OdSS8+zXDVaCWxyWrcv6kneTOlgAHtZABRzBBCwdsPiD90J4myNJuHpg6kA20ImW/w==", + "cpu": [ + "riscv64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.2.tgz", + "integrity": "sha512-/ABshyj8gCpyIrNXnHn4LorDJ0HHm1VhXPBlxZ8zAtfVPAaSafXPGn+sUSIRiwaSBy0mmFjSjiXI5mkcwdChKQ==", + "cpu": [ + "s390x" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.2.tgz", + "integrity": "sha512-ITPEtgffGJ0S6G9dRyw/366tJQqFRcHWPHhC+Stpg3Z8AEMrDrTr2lhdz4f/Y/HMbRh//7Z5mBzEpVdi62Oc3w==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.2.tgz", + "integrity": "sha512-zE9EdiUzUmg5mDT5a1rk5fYJ6GWPloTwWBYDS14naqHsL+EaMpDj1AWnpLgh3u0YCORv2Tt50wrcrpYqkP97Kw==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.2.tgz", + "integrity": "sha512-m0lrLiUt+lBYnCFr8qV/65yMR4E/c7/wf78I5eKTdkEakFAlZ9QlzEM3QIhhAwVeUhLAHLcCq7a7Vszq/oFNZQ==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.35.3", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.3.tgz", + "integrity": "sha512-affVWCTLooy8TSxbDx2qkzuDeaWLNVBA+P//FNBirHsXpP2fuBhk5AuboYUnrDnzoXes8GFjpTx0SBFOCRg+FA==", + "cpu": [ + "arm" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.3.2" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.35.3", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.3.tgz", + "integrity": "sha512-QgKDspHPnrU+GQ55XPhGwyhC8acLVOOSyAvo1oVfFmrIXLkDNmGWzAfDZ4xK8oSA1qBQrALcHX0G5UZni/SuFQ==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.3.2" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.35.3", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.3.tgz", + "integrity": "sha512-sMd8rDxmpLOwv/7N44klFjOD5DUO7FLdjiXDI0hoxYaf7Ar262dQIEkosE98bps+5HPLtp/EvNqeqQtOycP/IA==", + "cpu": [ + "ppc64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.3.2" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.35.3", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.3.tgz", + "integrity": "sha512-0Eob78yjlYPfL5vMNWAW55l3R9Y6BQS/gOfe0ZcP9mEz9ohhKSt4im1hayiknXgf8AWrFqMvJcKIdmLmEe7yeQ==", + "cpu": [ + "riscv64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.3.2" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.35.3", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.3.tgz", + "integrity": "sha512-KgAxQ0DxpNOq1rG2t5cgTgShJFGSuU7XO45cqC+1NVOuZnP6tlgZRuSYOfNupGkHID0o3cJOsw4DVeJpMovcGw==", + "cpu": [ + "s390x" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.3.2" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.35.3", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.3.tgz", + "integrity": "sha512-8pqvxubL2PGdhlPy6GLqzDYMUjyRmKAwKHYKixpdJYBUK7PJ0C029XdsnpFIdgRZG68fZiGdHVWcKPvtiPB4cA==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.3.2" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.35.3", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.3.tgz", + "integrity": "sha512-Vz0iQjzzcSX3HCbfwFfCSG/9SCIqyO0mH2sXyiHaAYfBk0cRsCWXRyQYX0ovCK/PAQBbTzQ0dsPQHh5MAFL59w==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.3.2" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.35.3", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.3.tgz", + "integrity": "sha512-6O1NPKcDVj9QEdg7Hx549EX8U0rp6yXQERqru6yRN7fGBn32UvIRJUlWnk+8xDCiG76hXVBbX82NZ/ZKr0euIg==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.3.2" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.35.3", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.3.tgz", + "integrity": "sha512-cZ0XkcYGpHZkqW6iCkqTcmUC0CD9DhD5d/qeZlZkfRBn6GnHniZXLUo5+9xw8Iv76YE6LQFN9YNBlKREcCG76w==", + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.11.1" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-webcontainers-wasm32": { + "version": "0.35.3", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.3.tgz", + "integrity": "sha512-2rnq7bX3NzeR2T4YWgz8qiG4h3TSdMe+vN1iQXpJleSJ3SM5zQ8Fy2SyyXAWlbxpEZ2Y+Z4u1BePgJEYbSy80Q==", + "cpu": [ + "wasm32" + ], + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@img/sharp-wasm32": "0.35.3" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.35.3", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.3.tgz", + "integrity": "sha512-4bPwFdMbeC4JQ8L8LOyWp6nsHcboP5fxkp6iPOXz2Vg49R42TuMs2whkJ5OAP4/Ul035qOzy0AecOF9VOscn4w==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.35.3", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.3.tgz", + "integrity": "sha512-r53mXsBN6lFUDiST764SvgwUdHAqM4rPAiDzAmf4fLoB6X/rkfyTrLCg6+g17wJJiCmB3JYgHuUldCWUIRFSXw==", + "cpu": [ + "ia32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.35.3", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.3.tgz", + "integrity": "sha512-D4y1vNeZrIIJCN+uHaWVtH86B+aCrdMYYjicy9pXHvbGZeGYLLSd3wdVuC37FxVXlU1ARsk84eKWfWMXGYEqvA==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "license": "MIT" + }, + "node_modules/@mdx-js/mdx": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@mdx-js/mdx/-/mdx-3.1.1.tgz", + "integrity": "sha512-f6ZO2ifpwAQIpzGWaBQT2TXxPv6z3RBzQKpVftEWN78Vl/YweF1uwussDx8ECAXVtr3Rs89fKyG9YlzUs9DyGQ==", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "@types/estree-jsx": "^1.0.0", + "@types/hast": "^3.0.0", + "@types/mdx": "^2.0.0", + "acorn": "^8.0.0", + "collapse-white-space": "^2.0.0", + "devlop": "^1.0.0", + "estree-util-is-identifier-name": "^3.0.0", + "estree-util-scope": "^1.0.0", + "estree-walker": "^3.0.0", + "hast-util-to-jsx-runtime": "^2.0.0", + "markdown-extensions": "^2.0.0", + "recma-build-jsx": "^1.0.0", + "recma-jsx": "^1.0.0", + "recma-stringify": "^1.0.0", + "rehype-recma": "^1.0.0", + "remark-mdx": "^3.0.0", + "remark-parse": "^11.0.0", + "remark-rehype": "^11.0.0", + "source-map": "^0.7.0", + "unified": "^11.0.0", + "unist-util-position-from-estree": "^2.0.0", + "unist-util-stringify-position": "^4.0.0", + "unist-util-visit": "^5.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.6.tgz", + "integrity": "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==", + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1", + "@emnapi/runtime": "^1.7.1" + } + }, + "node_modules/@oslojs/encoding": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@oslojs/encoding/-/encoding-1.1.0.tgz", + "integrity": "sha512-70wQhgYmndg4GCPxPPxPGevRKqTIJ2Nh4OkiMWmDAVYsTQ+Ta7Sq+rPevXyXGdzr30/qZBnyOalCszoMxlyldQ==", + "license": "MIT" + }, + "node_modules/@oxc-project/types": { + "version": "0.138.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.138.0.tgz", + "integrity": "sha512-1a7ZKmrRTCoN1XMZ4L0PyyqrMnrNlLyPuOkdSX2MZg7IiIGRUyurNhAm73ptDOraoBcIordsIGKNPKUzy3ZmfA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/Boshen" + } + }, + "node_modules/@pagefind/darwin-arm64": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/@pagefind/darwin-arm64/-/darwin-arm64-1.5.2.tgz", + "integrity": "sha512-MXpI+7HsAdPkvJ0gk9xj9g541BCqBZOBbdwj9g6lB5LCj6kSV6nqDSjzcAJwvOsfu0fjwvC8hQU+ecfhp+MpiQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@pagefind/darwin-x64": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/@pagefind/darwin-x64/-/darwin-x64-1.5.2.tgz", + "integrity": "sha512-IojxFWMEJe0RQ7PQ3KXQsPIImNsbpPYpoZ+QUDrL8fAl/O27IX+LVLs74/UzEZy5uA2LD8Nz1AiwKr72vrkZQw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@pagefind/default-ui": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/@pagefind/default-ui/-/default-ui-1.5.2.tgz", + "integrity": "sha512-pm1LMnQg8N2B3n2TnjKlhaFihpz6zTiA4HiGQ6/slKO/+8K9CAU5kcjdSSPgpuk1PMuuN4hxLipUIifnrkl3Sg==", + "license": "MIT" + }, + "node_modules/@pagefind/freebsd-x64": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/@pagefind/freebsd-x64/-/freebsd-x64-1.5.2.tgz", + "integrity": "sha512-7EVzo9+0w+2cbe671BtMj10UlNo83I+HrLVLfRxO731svHRJKUfJ/mo05gU14pe9PCfpKNQT8FS3Xc/oDN6pOA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@pagefind/linux-arm64": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/@pagefind/linux-arm64/-/linux-arm64-1.5.2.tgz", + "integrity": "sha512-Ovt9+K35sqzn8H3ZMXGwls4TD/wMJuvRtShHIsmUQREmaxjrDEX7gHckRCrwYJ4XE1H1p6HkLz3wukrAnsfXQw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@pagefind/linux-x64": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/@pagefind/linux-x64/-/linux-x64-1.5.2.tgz", + "integrity": "sha512-V+tFqHKXhQKq/WqPBD67AFy7scn1/aZID00ws4fSDd+1daSi5UHR9VVlRrOUYKxn3VuFQYRD7lYXdZK1WED1YA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@pagefind/windows-arm64": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/@pagefind/windows-arm64/-/windows-arm64-1.5.2.tgz", + "integrity": "sha512-hN9Nh90fNW61nNRCW9ZyQrAj/mD0eRvmJ8NlTUzkbuW8kIzGJUi3cxjFkEcMZ5h/8FsKWD/VcouZl4yo1F7B6g==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@pagefind/windows-x64": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/@pagefind/windows-x64/-/windows-x64-1.5.2.tgz", + "integrity": "sha512-Fa2Iyw7kaDRzGMfNYNUXNW2zbL5FQVDgSOcbDHdzBrDEdpqOqg8TcZ68F22ol6NJ9IGzvUdmeyZypLW5dyhqsg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.1.4.tgz", + "integrity": "sha512-EZLpf/8y7GXkkra90ML47kzik/GMP3EMcE9bPyHmRfxLC6z9+aW5A8poCsoxjrT5GfEcNAAvWwUHjvP1pUQkfw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.1.4.tgz", + "integrity": "sha512-aUi+HBvmYb7j8krl1+qJgkG8C17fO79gk3c+jPw4S8glRFc1DTija9S3EyaTSQUm5GJXYKDAsugBEhFHH2vYiQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.1.4.tgz", + "integrity": "sha512-F7hHC3gwY11+vByKPRWqwGbeXWVgKmL+pTGCinaEhdihzBV2aQ0fvZOch9cXYUOKuKKq429HeYXOqQLc7wFCEg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.1.4.tgz", + "integrity": "sha512-sI5yw+7s92SK6odiEhD5lKCBlWcpjHS5qyqpVQbZAJ0fIzEUXrmbl3DH2ybR3PZogulNJF+COLtmA8hUfvkCCQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.1.4.tgz", + "integrity": "sha512-mCi0OKgEieFircrtVYmQAFGszRtMnZ6fpZAXrxanXAu7lqZcsK1E1RAaZNG0uKAnxox3B1f4EyQNnoyMfN1vAA==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.1.4.tgz", + "integrity": "sha512-B9Ial3Kv5sh0SHnB1g/QWcUQCEvCF6QKGAl4zXypYj65mVI+B4AhFBwPtSN7pDrJeIx8Z7zdy4ntx+wQABom7w==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.1.4.tgz", + "integrity": "sha512-lZVym0PuHE1KZ22gmFTC15lAkrg9iTszR617oYRB/iPY1A56ywoJzVKOJBKaot5RiikCObmur6pogpse3gRcng==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.1.4.tgz", + "integrity": "sha512-t2DNiLJWNTbnEHyUzTumldML6ET4/g16467LZoDDJ3tSxGvguL5/NyC2lCsNKuyRycg9XeDQF5SSv+TNOhQEXg==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.1.4.tgz", + "integrity": "sha512-0WIRnL1Uw4BvTZRLQt+PVgo6ZKTJadlC2btP+/EOXv2f/DWbY0rEgl+y834mIVwP1FkTlWVTrGGJXf12lru7EQ==", + "cpu": [ + "s390x" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.1.4.tgz", + "integrity": "sha512-JWtGshGfX+oENAKonoNkqEJX+7hC8yfhi9GUyPX1VX4mdh1y5r+ZiJLR5XzAB0aoP6s/PcILsGjKq8O0mm24bw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.1.4.tgz", + "integrity": "sha512-rT6yQcxUuXs4CnbofqwHRRV0iem349rLMYpTjkgQGLjrY4ado/eDzwPZPTCgTOlF6Nkp8NEv70yLMTn6qkWxsQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.1.4.tgz", + "integrity": "sha512-KXMGoboq5cyaCQjDA4GLuRiOwBQ0EyFnJoVViLeZ45/3rFItRODEr+NdsBcVpll40hhNArlm/speWGRvj08LzA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.1.4.tgz", + "integrity": "sha512-5K83rb36oJiY7BCyE9zLZtGcPV4g5wvq+xwdO0XPIwDVZI8cyB/AUjkNXGb92/rnmezEkjMOpgY61rtwjQtFwg==", + "cpu": [ + "wasm32" + ], + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "1.11.1", + "@emnapi/runtime": "1.11.1", + "@napi-rs/wasm-runtime": "^1.1.6" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi/node_modules/@emnapi/core": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.1.tgz", + "integrity": "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.2", + "tslib": "^2.4.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi/node_modules/@emnapi/runtime": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.1.tgz", + "integrity": "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.1.4.tgz", + "integrity": "sha512-PnWBtw3TV5KOg69HQQDR0mnQuyCmSGR2pAB4DC1rPF808fgKeTUMj2EOEyKATpgiuxuR5APQmiDO7PDgEjTFSA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.1.4.tgz", + "integrity": "sha512-M1lpniBePobTfsa7Ks9a199e1akxsXn+GYBUKsEzv3YFzOm1HJAMNwKI3qr0Zq+mxwx9gOZoTdP1yXRYsZUocQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "license": "MIT" + }, + "node_modules/@rollup/pluginutils": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.4.0.tgz", + "integrity": "sha512-MfPp06CjRLfXQ3wY0R8vJDYBy/MvVcc9OulEfR0B8Iv9ko+GCNaRZ+EpJYFl27LhKsZK0o420sYCRHCjfCgeUg==", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "estree-walker": "^2.0.2", + "picomatch": "^4.0.2" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/pluginutils/node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "license": "MIT" + }, + "node_modules/@shikijs/core": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-4.3.1.tgz", + "integrity": "sha512-ANMDxuaPsNMdDC1m4vfvhlDmJweMwkE5XitTwrq2rWHx5jM+dlm4MmHt2PP6t0uejfR77SuhrhJ0zEijIF/uhA==", + "license": "MIT", + "dependencies": { + "@shikijs/primitive": "4.3.1", + "@shikijs/types": "4.3.1", + "@shikijs/vscode-textmate": "^10.0.2", + "@types/hast": "^3.0.4", + "hast-util-to-html": "^9.0.5" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/engine-javascript": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-4.3.1.tgz", + "integrity": "sha512-JBItcnPuYq7jVJdZo/vMj94r+szT7XEjHFX+mvFDGSEIbVAXAGyHAHzhbWzpGOwYidCZrErJLLgn2PVeiokHnQ==", + "license": "MIT", + "dependencies": { + "@shikijs/types": "4.3.1", + "@shikijs/vscode-textmate": "^10.0.2", + "oniguruma-to-es": "^4.3.6" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/engine-oniguruma": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-4.3.1.tgz", + "integrity": "sha512-OXyNMzg0pews+msMj4cHeqT4xiYKKvbnn6VbdAXxfoFl3SSx4fJTc8FadECuc5/H9p3BzhNAoAUXKwAu9rWYhg==", + "license": "MIT", + "dependencies": { + "@shikijs/types": "4.3.1", + "@shikijs/vscode-textmate": "^10.0.2" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/langs": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-4.3.1.tgz", + "integrity": "sha512-m0l9nsDqgBHvbZbk7A0/kXz/impK3uB/c6rAn6Gpg/uPtdZRQ+alsN/17MU5thb68XTj/4DxkZAotrM0GGSpDQ==", + "license": "MIT", + "dependencies": { + "@shikijs/types": "4.3.1" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/primitive": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@shikijs/primitive/-/primitive-4.3.1.tgz", + "integrity": "sha512-CXQRQOYy1leqQ8ceTeJdmXv/bsUY++6QyLpXJ94LZAAYj5X2SKRdc5ipguv4NPyGVKItB2PPwUpRNe0Sjh5S1A==", + "license": "MIT", + "dependencies": { + "@shikijs/types": "4.3.1", + "@shikijs/vscode-textmate": "^10.0.2", + "@types/hast": "^3.0.4" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/themes": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-4.3.1.tgz", + "integrity": "sha512-dgpoJ4WqNi2yTmizQHBJ5zcX6j2lE6icN/0yt4l1kkf16jrY/pwPLoTb1ETsWMz0OBLf9ZNvwmxft+cH+N9qSA==", + "license": "MIT", + "dependencies": { + "@shikijs/types": "4.3.1" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/types": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-4.3.1.tgz", + "integrity": "sha512-CHFxE0jztBIZRHH6gxXE7DXUCFXjReEGxZ/j0rfSLGKZuwp2xBYycEP14875DSa9KLL/6700oxIq6oO6ef9K2g==", + "license": "MIT", + "dependencies": { + "@shikijs/vscode-textmate": "^10.0.2", + "@types/hast": "^3.0.4" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/vscode-textmate": { + "version": "10.0.2", + "resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-10.0.2.tgz", + "integrity": "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==", + "license": "MIT" + }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.3", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.3.tgz", + "integrity": "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@types/debug": { + "version": "4.1.13", + "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.13.tgz", + "integrity": "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==", + "license": "MIT", + "dependencies": { + "@types/ms": "*" + } + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "license": "MIT" + }, + "node_modules/@types/estree-jsx": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@types/estree-jsx/-/estree-jsx-1.0.5.tgz", + "integrity": "sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==", + "license": "MIT", + "dependencies": { + "@types/estree": "*" + } + }, + "node_modules/@types/hast": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz", + "integrity": "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==", + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, + "node_modules/@types/js-yaml": { + "version": "4.0.9", + "resolved": "https://registry.npmjs.org/@types/js-yaml/-/js-yaml-4.0.9.tgz", + "integrity": "sha512-k4MGaQl5TGo/iipqb2UDG2UwjXziSWkh0uysQelTlJpX1qGlpUZYm8PnO4DxG1qBomtJUdYJ6qR6xdIah10JLg==", + "license": "MIT" + }, + "node_modules/@types/mdast": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz", + "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==", + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, + "node_modules/@types/mdx": { + "version": "2.0.14", + "resolved": "https://registry.npmjs.org/@types/mdx/-/mdx-2.0.14.tgz", + "integrity": "sha512-T48PeuJtvLosNTPVhfnIp3i/n3a4g4Bad7YCq5k64D4u7NwDrAotikQ+5+sjtUvBmxCMlbo3dVL+C2dP0rWHzg==", + "license": "MIT" + }, + "node_modules/@types/ms": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz", + "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==", + "license": "MIT" + }, + "node_modules/@types/nlcst": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@types/nlcst/-/nlcst-2.0.3.tgz", + "integrity": "sha512-vSYNSDe6Ix3q+6Z7ri9lyWqgGhJTmzRjZRqyq15N0Z/1/UnVsno9G/N40NBijoYx2seFDIl0+B2mgAb9mezUCA==", + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, + "node_modules/@types/node": { + "version": "24.13.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.2.tgz", + "integrity": "sha512-fRa09kZTgu8o71KFcDjUFuc7F+dEbZYZmkI0mg5YBTRs0yMKjYHsq/c0urDKeDb+D5qVgXOdFcuu+DZPKOITwA==", + "license": "MIT", + "dependencies": { + "undici-types": "~7.18.0" + } + }, + "node_modules/@types/sax": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@types/sax/-/sax-1.2.7.tgz", + "integrity": "sha512-rO73L89PJxeYM3s3pPPjiPgVVcymqU490g0YO5n5By0k2Erzj6tay/4lr1CHAAU4JyOWd1rpQ8bCf6cZfHU96A==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/unist": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", + "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==", + "license": "MIT" + }, + "node_modules/@ungap/structured-clone": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.2.tgz", + "integrity": "sha512-5jsZFwgR5rTdKwidH9Qmat75RKwqfpKlWWB1frDkljN127mwqBu8K0PYo7/hFpF03IEJpfVPpCQDY/eDx3iHvA==", + "license": "ISC" + }, + "node_modules/acorn": { + "version": "8.17.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.17.0.tgz", + "integrity": "sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg==", + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "license": "MIT", + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/am-i-vibing": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/am-i-vibing/-/am-i-vibing-0.4.0.tgz", + "integrity": "sha512-MxT4XZL7pzLHpuvhDKdMaQHMGGkJDLluKBLsbstn+8wv9sWcFT6h+0ve9qkml95amVTZtZV83gQe2hY+ojgHLg==", + "license": "MIT", + "dependencies": { + "process-ancestry": "^0.1.0" + }, + "bin": { + "am-i-vibing": "dist/cli.mjs" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/anymatch/node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/arg": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/arg/-/arg-5.0.2.tgz", + "integrity": "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==", + "license": "MIT" + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "license": "Python-2.0" + }, + "node_modules/aria-query": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.2.tgz", + "integrity": "sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==", + "license": "Apache-2.0", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/array-iterate": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/array-iterate/-/array-iterate-2.0.1.tgz", + "integrity": "sha512-I1jXZMjAgCMmxT4qxXfPXa6SthSoE8h6gkSI9BGGNv8mP8G/v0blc+qFnZu6K42vTOiuME596QaLO0TP3Lk0xg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/astring": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/astring/-/astring-1.9.0.tgz", + "integrity": "sha512-LElXdjswlqjWrPpJFg1Fx4wpkOCxj1TDHlSV4PlaRxHGWko024xICaa97ZkMfs6DRKlCguiAI+rbXv5GWwXIkg==", + "license": "MIT", + "bin": { + "astring": "bin/astring" + } + }, + "node_modules/astro": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/astro/-/astro-7.0.6.tgz", + "integrity": "sha512-Myw0sFia+zs/Y0yqfZEsUYXfDPh3ELcLf1f0Q/qQzVXBh/af1qO62WNT+P89DCcfGVV51nMoQhEfkBYqJmoUOQ==", + "license": "MIT", + "dependencies": { + "@astrojs/compiler-rs": "^0.3.0", + "@astrojs/internal-helpers": "0.10.1", + "@astrojs/markdown-satteri": "0.3.3", + "@astrojs/telemetry": "3.3.2", + "@capsizecss/unpack": "^4.0.0", + "@clack/prompts": "^1.1.0", + "@oslojs/encoding": "^1.1.0", + "@rollup/pluginutils": "^5.3.0", + "am-i-vibing": "^0.4.0", + "aria-query": "^5.3.2", + "axobject-query": "^4.1.0", + "ci-info": "^4.4.0", + "clsx": "^2.1.1", + "common-ancestor-path": "^2.0.0", + "cookie": "^1.1.1", + "devalue": "^5.8.1", + "diff": "^8.0.3", + "dset": "^3.1.4", + "es-module-lexer": "^2.0.0", + "esbuild": "^0.28.0", + "flattie": "^1.1.1", + "fontace": "~0.4.1", + "get-tsconfig": "5.0.0-beta.4", + "github-slugger": "^2.0.0", + "html-escaper": "3.0.3", + "http-cache-semantics": "^4.2.0", + "js-yaml": "^4.1.1", + "jsonc-parser": "^3.3.1", + "magic-string": "^0.30.21", + "magicast": "^0.5.2", + "mrmime": "^2.0.1", + "neotraverse": "^0.6.18", + "obug": "^2.1.1", + "p-limit": "^7.3.0", + "p-queue": "^9.1.0", + "package-manager-detector": "^1.6.0", + "piccolore": "^0.1.3", + "picomatch": "^4.0.4", + "semver": "^7.7.4", + "shiki": "^4.0.2", + "smol-toml": "^1.6.0", + "svgo": "^4.0.1", + "tinyclip": "^0.1.12", + "tinyexec": "^1.0.4", + "tinyglobby": "^0.2.15", + "ultrahtml": "^1.6.0", + "unifont": "~0.7.4", + "unstorage": "^1.17.5", + "vite": "^8.0.13", + "vitefu": "^1.1.2", + "xxhash-wasm": "^1.1.0", + "yargs-parser": "^22.0.0", + "zod": "^4.3.6" + }, + "bin": { + "astro": "bin/astro.mjs" + }, + "engines": { + "node": ">=22.12.0", + "npm": ">=9.6.5", + "pnpm": ">=7.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/astrodotbuild" + }, + "optionalDependencies": { + "sharp": "^0.34.0 || ^0.35.0" + }, + "peerDependencies": { + "@astrojs/markdown-remark": "7.2.1" + }, + "peerDependenciesMeta": { + "@astrojs/markdown-remark": { + "optional": true + } + } + }, + "node_modules/astro-expressive-code": { + "version": "0.44.0", + "resolved": "https://registry.npmjs.org/astro-expressive-code/-/astro-expressive-code-0.44.0.tgz", + "integrity": "sha512-b1wN/ZvbJprzxlGKIpIes2kQrCY5KRLwys2tWbZAZyjGZcW5ZtgneZnBwzNRiBna9/48d4mQl19KLjcRuhO1hw==", + "license": "MIT", + "dependencies": { + "rehype-expressive-code": "^0.44.0", + "url-extras": "^0.1.0" + }, + "peerDependencies": { + "astro": "^4.0.0-beta || ^5.0.0-beta || ^3.3.0 || ^6.0.0-beta || ^7.0.0" + } + }, + "node_modules/axobject-query": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz", + "integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==", + "license": "Apache-2.0", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/bail": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/bail/-/bail-2.0.2.tgz", + "integrity": "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/bcp-47": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/bcp-47/-/bcp-47-2.1.1.tgz", + "integrity": "sha512-KLw+H/gd2p4zly1X7Yh/qziuyae5/w/QFnvTng9eZL5fvszL7Whl3MBoWF8yxL7ksUjBfOD+OxkytiqbBpG+Fw==", + "license": "MIT", + "dependencies": { + "is-alphabetical": "^2.0.0", + "is-alphanumerical": "^2.0.0", + "is-decimal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/bcp-47-match": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/bcp-47-match/-/bcp-47-match-2.0.3.tgz", + "integrity": "sha512-JtTezzbAibu8G0R9op9zb3vcWZd9JF6M0xOYGPn0fNCd7wOpRB1mU2mH9T8gaBGbAAyIIVgB2G7xG0GP98zMAQ==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/boolbase": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", + "integrity": "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==", + "license": "ISC" + }, + "node_modules/ccount": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz", + "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/character-entities": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz", + "integrity": "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/character-entities-html4": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz", + "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/character-entities-legacy": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz", + "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/character-reference-invalid": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/character-reference-invalid/-/character-reference-invalid-2.0.1.tgz", + "integrity": "sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/chokidar": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz", + "integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==", + "license": "MIT", + "dependencies": { + "readdirp": "^5.0.0" + }, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/ci-info": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.4.0.tgz", + "integrity": "sha512-77PSwercCZU2Fc4sX94eF8k8Pxte6JAwL4/ICZLFjJLqegs7kCuAsqqj/70NQF6TvDpgFjkubQB2FW2ZZddvQg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/sibiraj-s" + } + ], + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/clsx": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", + "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/collapse-white-space": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/collapse-white-space/-/collapse-white-space-2.1.0.tgz", + "integrity": "sha512-loKTxY1zCOuG4j9f6EPnuyyYkf58RnhhWTvRoZEokgB+WbdXehfjFviyOVYkqzEWz1Q5kRiZdBYS5SwxbQYwzw==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/comma-separated-tokens": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz", + "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/commander": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-11.1.0.tgz", + "integrity": "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ==", + "license": "MIT", + "engines": { + "node": ">=16" + } + }, + "node_modules/common-ancestor-path": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/common-ancestor-path/-/common-ancestor-path-2.0.0.tgz", + "integrity": "sha512-dnN3ibLeoRf2HNC+OlCiNc5d2zxbLJXOtiZUudNFSXZrNSydxcCsSpRzXwfu7BBWCIfHPw+xTayeBvJCP/D8Ng==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">= 18" + } + }, + "node_modules/cookie": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", + "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/cookie-es": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/cookie-es/-/cookie-es-1.2.3.tgz", + "integrity": "sha512-lXVyvUvrNXblMqzIRrxHb57UUVmqsSWlxqt3XIjCkUP0wDAf6uicO6KMbEgYrMNtEvWgWHwe42CKxPu9MYAnWw==", + "license": "MIT" + }, + "node_modules/crossws": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/crossws/-/crossws-0.3.5.tgz", + "integrity": "sha512-ojKiDvcmByhwa8YYqbQI/hg7MEU0NC03+pSdEq4ZUnZR9xXpwk7E43SMNGkn+JxJGPFtNvQ48+vV2p+P1ml5PA==", + "license": "MIT", + "dependencies": { + "uncrypto": "^0.1.3" + } + }, + "node_modules/css-select": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/css-select/-/css-select-5.2.2.tgz", + "integrity": "sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw==", + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^1.0.0", + "css-what": "^6.1.0", + "domhandler": "^5.0.2", + "domutils": "^3.0.1", + "nth-check": "^2.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/css-selector-parser": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/css-selector-parser/-/css-selector-parser-3.3.0.tgz", + "integrity": "sha512-Y2asgMGFqJKF4fq4xHDSlFYIkeVfRsm69lQC1q9kbEsH5XtnINTMrweLkjYMeaUgiXBy/uvKeO/a1JHTNnmB2g==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/mdevils" + }, + { + "type": "patreon", + "url": "https://patreon.com/mdevils" + } + ], + "license": "MIT" + }, + "node_modules/css-tree": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz", + "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==", + "license": "MIT", + "dependencies": { + "mdn-data": "2.27.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" + } + }, + "node_modules/css-what": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/css-what/-/css-what-6.2.2.tgz", + "integrity": "sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA==", + "license": "BSD-2-Clause", + "engines": { + "node": ">= 6" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/cssesc": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", + "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", + "license": "MIT", + "bin": { + "cssesc": "bin/cssesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/csso": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/csso/-/csso-5.0.5.tgz", + "integrity": "sha512-0LrrStPOdJj+SPCCrGhzryycLjwcgUSHBtxNA8aIDxf0GLsRh1cKYhB00Gd1lDOS4yGH69+SNn13+TWbVHETFQ==", + "license": "MIT", + "dependencies": { + "css-tree": "~2.2.0" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/csso/node_modules/css-tree": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-2.2.1.tgz", + "integrity": "sha512-OA0mILzGc1kCOCSJerOeqDxDQ4HOh+G8NbOJFOTgOCzpw7fCBubk0fEyxp8AgOL/jvLgYA/uV0cMbe43ElF1JA==", + "license": "MIT", + "dependencies": { + "mdn-data": "2.0.28", + "source-map-js": "^1.0.1" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/csso/node_modules/mdn-data": { + "version": "2.0.28", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.0.28.tgz", + "integrity": "sha512-aylIc7Z9y4yzHYAJNuESG3hfhC+0Ibp/MAMiaOZgNv4pmEdFyfZhhhny4MNiAfWdBQ1RQ2mfDWmM1x8SvGyp8g==", + "license": "CC0-1.0" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decode-named-character-reference": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz", + "integrity": "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==", + "license": "MIT", + "dependencies": { + "character-entities": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/defu": { + "version": "6.1.7", + "resolved": "https://registry.npmjs.org/defu/-/defu-6.1.7.tgz", + "integrity": "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==", + "license": "MIT" + }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/destr": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/destr/-/destr-2.0.5.tgz", + "integrity": "sha512-ugFTXCtDZunbzasqBxrK93Ik/DRYsO6S/fedkWEMKqt04xZ4csmnmwGDBAb07QWNaGMAmnTIemsYZCksjATwsA==", + "license": "MIT" + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/devalue": { + "version": "5.8.1", + "resolved": "https://registry.npmjs.org/devalue/-/devalue-5.8.1.tgz", + "integrity": "sha512-4CXDYRBGqN+57wVJkuXBYmpAVUSg3L6JAQa/DFqm238G73E1wuyc/JhGQJzN7vUf/CMphYau2zXbfWzDR5aTEw==", + "license": "MIT" + }, + "node_modules/devlop": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz", + "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==", + "license": "MIT", + "dependencies": { + "dequal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/diff": { + "version": "8.0.4", + "resolved": "https://registry.npmjs.org/diff/-/diff-8.0.4.tgz", + "integrity": "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/direction": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/direction/-/direction-2.0.1.tgz", + "integrity": "sha512-9S6m9Sukh1cZNknO1CWAr2QAWsbKLafQiyM5gZ7VgXHeuaoUwffKN4q6NC4A/Mf9iiPlOXQEKW/Mv/mh9/3YFA==", + "license": "MIT", + "bin": { + "direction": "cli.js" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/dom-serializer": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz", + "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==", + "license": "MIT", + "dependencies": { + "domelementtype": "^2.3.0", + "domhandler": "^5.0.2", + "entities": "^4.2.0" + }, + "funding": { + "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1" + } + }, + "node_modules/dom-serializer/node_modules/entities": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/domelementtype": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", + "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "BSD-2-Clause" + }, + "node_modules/domhandler": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz", + "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==", + "license": "BSD-2-Clause", + "dependencies": { + "domelementtype": "^2.3.0" + }, + "engines": { + "node": ">= 4" + }, + "funding": { + "url": "https://github.com/fb55/domhandler?sponsor=1" + } + }, + "node_modules/domutils": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz", + "integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==", + "license": "BSD-2-Clause", + "dependencies": { + "dom-serializer": "^2.0.0", + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3" + }, + "funding": { + "url": "https://github.com/fb55/domutils?sponsor=1" + } + }, + "node_modules/dset": { + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/dset/-/dset-3.1.4.tgz", + "integrity": "sha512-2QF/g9/zTaPDc3BjNcVTGoBbXBgYfMTTceLaYcFJ/W9kggFUkhxD/hMEeuLKbugyef9SqAx8cpgwlIP/jinUTA==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/entities": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/es-module-lexer": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.0.tgz", + "integrity": "sha512-KLdwQm2NvGLDkQDCGvmiQrhkd0JbMzXthwQAUgWjQuQdBLFa3eiBP5arXZyA+f8x+x7OXgud6bq2rxjGtHV2tw==", + "license": "MIT" + }, + "node_modules/esast-util-from-estree": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/esast-util-from-estree/-/esast-util-from-estree-2.0.0.tgz", + "integrity": "sha512-4CyanoAudUSBAn5K13H4JhsMH6L9ZP7XbLVe/dKybkxMO7eDyLsT8UHl9TRNrU2Gr9nz+FovfSIjuXWJ81uVwQ==", + "license": "MIT", + "dependencies": { + "@types/estree-jsx": "^1.0.0", + "devlop": "^1.0.0", + "estree-util-visit": "^2.0.0", + "unist-util-position-from-estree": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/esast-util-from-js": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/esast-util-from-js/-/esast-util-from-js-2.0.1.tgz", + "integrity": "sha512-8Ja+rNJ0Lt56Pcf3TAmpBZjmx8ZcK5Ts4cAzIOjsjevg9oSXJnl6SUQ2EevU8tv3h6ZLWmoKL5H4fgWvdvfETw==", + "license": "MIT", + "dependencies": { + "@types/estree-jsx": "^1.0.0", + "acorn": "^8.0.0", + "esast-util-from-estree": "^2.0.0", + "vfile-message": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/esbuild": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz", + "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==", + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.1", + "@esbuild/android-arm": "0.28.1", + "@esbuild/android-arm64": "0.28.1", + "@esbuild/android-x64": "0.28.1", + "@esbuild/darwin-arm64": "0.28.1", + "@esbuild/darwin-x64": "0.28.1", + "@esbuild/freebsd-arm64": "0.28.1", + "@esbuild/freebsd-x64": "0.28.1", + "@esbuild/linux-arm": "0.28.1", + "@esbuild/linux-arm64": "0.28.1", + "@esbuild/linux-ia32": "0.28.1", + "@esbuild/linux-loong64": "0.28.1", + "@esbuild/linux-mips64el": "0.28.1", + "@esbuild/linux-ppc64": "0.28.1", + "@esbuild/linux-riscv64": "0.28.1", + "@esbuild/linux-s390x": "0.28.1", + "@esbuild/linux-x64": "0.28.1", + "@esbuild/netbsd-arm64": "0.28.1", + "@esbuild/netbsd-x64": "0.28.1", + "@esbuild/openbsd-arm64": "0.28.1", + "@esbuild/openbsd-x64": "0.28.1", + "@esbuild/openharmony-arm64": "0.28.1", + "@esbuild/sunos-x64": "0.28.1", + "@esbuild/win32-arm64": "0.28.1", + "@esbuild/win32-ia32": "0.28.1", + "@esbuild/win32-x64": "0.28.1" + } + }, + "node_modules/escape-string-regexp": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz", + "integrity": "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/estree-util-attach-comments": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/estree-util-attach-comments/-/estree-util-attach-comments-3.0.0.tgz", + "integrity": "sha512-cKUwm/HUcTDsYh/9FgnuFqpfquUbwIqwKM26BVCGDPVgvaCl/nDCCjUfiLlx6lsEZ3Z4RFxNbOQ60pkaEwFxGw==", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/estree-util-build-jsx": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/estree-util-build-jsx/-/estree-util-build-jsx-3.0.1.tgz", + "integrity": "sha512-8U5eiL6BTrPxp/CHbs2yMgP8ftMhR5ww1eIKoWRMlqvltHF8fZn5LRDvTKuxD3DUn+shRbLGqXemcP51oFCsGQ==", + "license": "MIT", + "dependencies": { + "@types/estree-jsx": "^1.0.0", + "devlop": "^1.0.0", + "estree-util-is-identifier-name": "^3.0.0", + "estree-walker": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/estree-util-is-identifier-name": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/estree-util-is-identifier-name/-/estree-util-is-identifier-name-3.0.0.tgz", + "integrity": "sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/estree-util-scope": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/estree-util-scope/-/estree-util-scope-1.0.0.tgz", + "integrity": "sha512-2CAASclonf+JFWBNJPndcOpA8EMJwa0Q8LUFJEKqXLW6+qBvbFZuF5gItbQOs/umBUkjviCSDCbBwU2cXbmrhQ==", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "devlop": "^1.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/estree-util-to-js": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/estree-util-to-js/-/estree-util-to-js-2.0.0.tgz", + "integrity": "sha512-WDF+xj5rRWmD5tj6bIqRi6CkLIXbbNQUcxQHzGysQzvHmdYG2G7p/Tf0J0gpxGgkeMZNTIjT/AoSvC9Xehcgdg==", + "license": "MIT", + "dependencies": { + "@types/estree-jsx": "^1.0.0", + "astring": "^1.8.0", + "source-map": "^0.7.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/estree-util-visit": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/estree-util-visit/-/estree-util-visit-2.0.0.tgz", + "integrity": "sha512-m5KgiH85xAhhW8Wta0vShLcUvOsh3LLPI2YVwcbio1l7E09NTLL1EyMZFM1OyWowoH0skScNbhOPl4kcBgzTww==", + "license": "MIT", + "dependencies": { + "@types/estree-jsx": "^1.0.0", + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/eventemitter3": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz", + "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==", + "license": "MIT" + }, + "node_modules/expressive-code": { + "version": "0.44.0", + "resolved": "https://registry.npmjs.org/expressive-code/-/expressive-code-0.44.0.tgz", + "integrity": "sha512-JXVWVNCKlLuZLMQH8cOiDUSosT0Bb+elwE/dbAkpwFwDFmyFyWlECoWZIohh2FkIF1iI67TQJ+Ts9k7oNDh2qA==", + "license": "MIT", + "dependencies": { + "@expressive-code/core": "^0.44.0", + "@expressive-code/plugin-frames": "^0.44.0", + "@expressive-code/plugin-shiki": "^0.44.0", + "@expressive-code/plugin-text-markers": "^0.44.0" + } + }, + "node_modules/extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", + "license": "MIT" + }, + "node_modules/fast-string-truncated-width": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/fast-string-truncated-width/-/fast-string-truncated-width-3.0.3.tgz", + "integrity": "sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==", + "license": "MIT" + }, + "node_modules/fast-string-width": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/fast-string-width/-/fast-string-width-3.0.2.tgz", + "integrity": "sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==", + "license": "MIT", + "dependencies": { + "fast-string-truncated-width": "^3.0.2" + } + }, + "node_modules/fast-wrap-ansi": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/fast-wrap-ansi/-/fast-wrap-ansi-0.2.2.tgz", + "integrity": "sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q==", + "license": "MIT", + "dependencies": { + "fast-string-width": "^3.0.2" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/flattie": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/flattie/-/flattie-1.1.1.tgz", + "integrity": "sha512-9UbaD6XdAL97+k/n+N7JwX46K/M6Zc6KcFYskrYL8wbBV/Uyk0CTAMY0VT+qiK5PM7AIc9aTWYtq65U7T+aCNQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/fontace": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/fontace/-/fontace-0.4.1.tgz", + "integrity": "sha512-lDMvbAzSnHmbYMTEld5qdtvNH2/pWpICOqpean9IgC7vUbUJc3k+k5Dokp85CegamqQpFbXf0rAVkbzpyTA8aw==", + "license": "MIT", + "dependencies": { + "fontkitten": "^1.0.2" + } + }, + "node_modules/fontkitten": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/fontkitten/-/fontkitten-1.0.3.tgz", + "integrity": "sha512-Wp1zXWPVUPBmfoa3Cqc9ctaKuzKAV6uLstRqlR56kSjplf5uAce+qeyYym7F+PHbGTk+tCEdkCW6RD7DX/gBZw==", + "license": "MIT", + "dependencies": { + "tiny-inflate": "^1.0.3" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/get-tsconfig": { + "version": "5.0.0-beta.4", + "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-5.0.0-beta.4.tgz", + "integrity": "sha512-7nF7C9fIPFEMHgEMEfgIlO9wDdZ8CyHw27rWciFZfHvHDReIiPhsYuzPRXsfvBCqFy1l8RRyyWV7QLM+ZhUJsQ==", + "license": "MIT", + "dependencies": { + "resolve-pkg-maps": "^1.0.0" + }, + "engines": { + "node": ">=20.20.0" + }, + "funding": { + "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" + } + }, + "node_modules/github-slugger": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/github-slugger/-/github-slugger-2.0.0.tgz", + "integrity": "sha512-IaOQ9puYtjrkq7Y0Ygl9KDZnrf/aiUJYUpVf89y8kyaxbRG7Y1SrX/jaumrv81vc61+kiMempujsM3Yw7w5qcw==", + "license": "ISC" + }, + "node_modules/h3": { + "version": "1.15.11", + "resolved": "https://registry.npmjs.org/h3/-/h3-1.15.11.tgz", + "integrity": "sha512-L3THSe2MPeBwgIZVSH5zLdBBU90TOxarvhK9d04IDY2AmVS8j2Jz2LIWtwsGOU3lu2I5jCN7FNvVfY2+XyF+mg==", + "license": "MIT", + "dependencies": { + "cookie-es": "^1.2.3", + "crossws": "^0.3.5", + "defu": "^6.1.6", + "destr": "^2.0.5", + "iron-webcrypto": "^1.2.1", + "node-mock-http": "^1.0.4", + "radix3": "^1.1.2", + "ufo": "^1.6.3", + "uncrypto": "^0.1.3" + } + }, + "node_modules/hast-util-embedded": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/hast-util-embedded/-/hast-util-embedded-3.0.0.tgz", + "integrity": "sha512-naH8sld4Pe2ep03qqULEtvYr7EjrLK2QHY8KJR6RJkTUjPGObe1vnx585uzem2hGra+s1q08DZZpfgDVYRbaXA==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "hast-util-is-element": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-format": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/hast-util-format/-/hast-util-format-1.1.0.tgz", + "integrity": "sha512-yY1UDz6bC9rDvCWHpx12aIBGRG7krurX0p0Fm6pT547LwDIZZiNr8a+IHDogorAdreULSEzP82Nlv5SZkHZcjA==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "hast-util-embedded": "^3.0.0", + "hast-util-minify-whitespace": "^1.0.0", + "hast-util-phrasing": "^3.0.0", + "hast-util-whitespace": "^3.0.0", + "html-whitespace-sensitive-tag-names": "^3.0.0", + "unist-util-visit-parents": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-from-html": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/hast-util-from-html/-/hast-util-from-html-2.0.3.tgz", + "integrity": "sha512-CUSRHXyKjzHov8yKsQjGOElXy/3EKpyX56ELnkHH34vDVw1N1XSQ1ZcAvTyAPtGqLTuKP/uxM+aLkSPqF/EtMw==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "devlop": "^1.1.0", + "hast-util-from-parse5": "^8.0.0", + "parse5": "^7.0.0", + "vfile": "^6.0.0", + "vfile-message": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-from-parse5": { + "version": "8.0.3", + "resolved": "https://registry.npmjs.org/hast-util-from-parse5/-/hast-util-from-parse5-8.0.3.tgz", + "integrity": "sha512-3kxEVkEKt0zvcZ3hCRYI8rqrgwtlIOFMWkbclACvjlDw8Li9S2hk/d51OI0nr/gIpdMHNepwgOKqZ/sy0Clpyg==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/unist": "^3.0.0", + "devlop": "^1.0.0", + "hastscript": "^9.0.0", + "property-information": "^7.0.0", + "vfile": "^6.0.0", + "vfile-location": "^5.0.0", + "web-namespaces": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-has-property": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/hast-util-has-property/-/hast-util-has-property-3.0.0.tgz", + "integrity": "sha512-MNilsvEKLFpV604hwfhVStK0usFY/QmM5zX16bo7EjnAEGofr5YyI37kzopBlZJkHD4t887i+q/C8/tr5Q94cA==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-is-body-ok-link": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/hast-util-is-body-ok-link/-/hast-util-is-body-ok-link-3.0.1.tgz", + "integrity": "sha512-0qpnzOBLztXHbHQenVB8uNuxTnm/QBFUOmdOSsEn7GnBtyY07+ENTWVFBAnXd/zEgd9/SUG3lRY7hSIBWRgGpQ==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-is-element": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/hast-util-is-element/-/hast-util-is-element-3.0.0.tgz", + "integrity": "sha512-Val9mnv2IWpLbNPqc/pUem+a7Ipj2aHacCwgNfTiK0vJKl0LF+4Ba4+v1oPHFpf3bLYmreq0/l3Gud9S5OH42g==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-minify-whitespace": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/hast-util-minify-whitespace/-/hast-util-minify-whitespace-1.0.1.tgz", + "integrity": "sha512-L96fPOVpnclQE0xzdWb/D12VT5FabA7SnZOUMtL1DbXmYiHJMXZvFkIZfiMmTCNJHUeO2K9UYNXoVyfz+QHuOw==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "hast-util-embedded": "^3.0.0", + "hast-util-is-element": "^3.0.0", + "hast-util-whitespace": "^3.0.0", + "unist-util-is": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-parse-selector": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/hast-util-parse-selector/-/hast-util-parse-selector-4.0.0.tgz", + "integrity": "sha512-wkQCkSYoOGCRKERFWcxMVMOcYE2K1AaNLU8DXS9arxnLOUEWbOXKXiJUNzEpqZ3JOKpnha3jkFrumEjVliDe7A==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-phrasing": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/hast-util-phrasing/-/hast-util-phrasing-3.0.1.tgz", + "integrity": "sha512-6h60VfI3uBQUxHqTyMymMZnEbNl1XmEGtOxxKYL7stY2o601COo62AWAYBQR9lZbYXYSBoxag8UpPRXK+9fqSQ==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "hast-util-embedded": "^3.0.0", + "hast-util-has-property": "^3.0.0", + "hast-util-is-body-ok-link": "^3.0.0", + "hast-util-is-element": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-raw": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/hast-util-raw/-/hast-util-raw-9.1.0.tgz", + "integrity": "sha512-Y8/SBAHkZGoNkpzqqfCldijcuUKh7/su31kEBp67cFY09Wy0mTRgtsLYsiIxMJxlu0f6AA5SUTbDR8K0rxnbUw==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/unist": "^3.0.0", + "@ungap/structured-clone": "^1.0.0", + "hast-util-from-parse5": "^8.0.0", + "hast-util-to-parse5": "^8.0.0", + "html-void-elements": "^3.0.0", + "mdast-util-to-hast": "^13.0.0", + "parse5": "^7.0.0", + "unist-util-position": "^5.0.0", + "unist-util-visit": "^5.0.0", + "vfile": "^6.0.0", + "web-namespaces": "^2.0.0", + "zwitch": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-select": { + "version": "6.0.4", + "resolved": "https://registry.npmjs.org/hast-util-select/-/hast-util-select-6.0.4.tgz", + "integrity": "sha512-RqGS1ZgI0MwxLaKLDxjprynNzINEkRHY2i8ln4DDjgv9ZhcYVIHN9rlpiYsqtFwrgpYU361SyWDQcGNIBVu3lw==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/unist": "^3.0.0", + "bcp-47-match": "^2.0.0", + "comma-separated-tokens": "^2.0.0", + "css-selector-parser": "^3.0.0", + "devlop": "^1.0.0", + "direction": "^2.0.0", + "hast-util-has-property": "^3.0.0", + "hast-util-to-string": "^3.0.0", + "hast-util-whitespace": "^3.0.0", + "nth-check": "^2.0.0", + "property-information": "^7.0.0", + "space-separated-tokens": "^2.0.0", + "unist-util-visit": "^5.0.0", + "zwitch": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-to-estree": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/hast-util-to-estree/-/hast-util-to-estree-3.1.3.tgz", + "integrity": "sha512-48+B/rJWAp0jamNbAAf9M7Uf//UVqAoMmgXhBdxTDJLGKY+LRnZ99qcG+Qjl5HfMpYNzS5v4EAwVEF34LeAj7w==", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "@types/estree-jsx": "^1.0.0", + "@types/hast": "^3.0.0", + "comma-separated-tokens": "^2.0.0", + "devlop": "^1.0.0", + "estree-util-attach-comments": "^3.0.0", + "estree-util-is-identifier-name": "^3.0.0", + "hast-util-whitespace": "^3.0.0", + "mdast-util-mdx-expression": "^2.0.0", + "mdast-util-mdx-jsx": "^3.0.0", + "mdast-util-mdxjs-esm": "^2.0.0", + "property-information": "^7.0.0", + "space-separated-tokens": "^2.0.0", + "style-to-js": "^1.0.0", + "unist-util-position": "^5.0.0", + "zwitch": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-to-html": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.5.tgz", + "integrity": "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/unist": "^3.0.0", + "ccount": "^2.0.0", + "comma-separated-tokens": "^2.0.0", + "hast-util-whitespace": "^3.0.0", + "html-void-elements": "^3.0.0", + "mdast-util-to-hast": "^13.0.0", + "property-information": "^7.0.0", + "space-separated-tokens": "^2.0.0", + "stringify-entities": "^4.0.0", + "zwitch": "^2.0.4" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-to-jsx-runtime": { + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.6.tgz", + "integrity": "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "@types/hast": "^3.0.0", + "@types/unist": "^3.0.0", + "comma-separated-tokens": "^2.0.0", + "devlop": "^1.0.0", + "estree-util-is-identifier-name": "^3.0.0", + "hast-util-whitespace": "^3.0.0", + "mdast-util-mdx-expression": "^2.0.0", + "mdast-util-mdx-jsx": "^3.0.0", + "mdast-util-mdxjs-esm": "^2.0.0", + "property-information": "^7.0.0", + "space-separated-tokens": "^2.0.0", + "style-to-js": "^1.0.0", + "unist-util-position": "^5.0.0", + "vfile-message": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-to-parse5": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/hast-util-to-parse5/-/hast-util-to-parse5-8.0.1.tgz", + "integrity": "sha512-MlWT6Pjt4CG9lFCjiz4BH7l9wmrMkfkJYCxFwKQic8+RTZgWPuWxwAfjJElsXkex7DJjfSJsQIt931ilUgmwdA==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "comma-separated-tokens": "^2.0.0", + "devlop": "^1.0.0", + "property-information": "^7.0.0", + "space-separated-tokens": "^2.0.0", + "web-namespaces": "^2.0.0", + "zwitch": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-to-string": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/hast-util-to-string/-/hast-util-to-string-3.0.1.tgz", + "integrity": "sha512-XelQVTDWvqcl3axRfI0xSeoVKzyIFPwsAGSLIsKdJKQMXDYJS4WYrBNF/8J7RdhIcFI2BOHgAifggsvsxp/3+A==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-to-text": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/hast-util-to-text/-/hast-util-to-text-4.0.2.tgz", + "integrity": "sha512-KK6y/BN8lbaq654j7JgBydev7wuNMcID54lkRav1P0CaE1e47P72AWWPiGKXTJU271ooYzcvTAn/Zt0REnvc7A==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/unist": "^3.0.0", + "hast-util-is-element": "^3.0.0", + "unist-util-find-after": "^5.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-whitespace": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz", + "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hastscript": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/hastscript/-/hastscript-9.0.1.tgz", + "integrity": "sha512-g7df9rMFX/SPi34tyGCyUBREQoKkapwdY/T04Qn9TDWfHhAYt4/I0gMVirzK5wEzeUqIjEB+LXC/ypb7Aqno5w==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "comma-separated-tokens": "^2.0.0", + "hast-util-parse-selector": "^4.0.0", + "property-information": "^7.0.0", + "space-separated-tokens": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/html-escaper": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-3.0.3.tgz", + "integrity": "sha512-RuMffC89BOWQoY0WKGpIhn5gX3iI54O6nRA0yC124NYVtzjmFWBIiFd8M0x+ZdX0P9R4lADg1mgP8C7PxGOWuQ==", + "license": "MIT" + }, + "node_modules/html-void-elements": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/html-void-elements/-/html-void-elements-3.0.0.tgz", + "integrity": "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/html-whitespace-sensitive-tag-names": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/html-whitespace-sensitive-tag-names/-/html-whitespace-sensitive-tag-names-3.0.1.tgz", + "integrity": "sha512-q+310vW8zmymYHALr1da4HyXUQ0zgiIwIicEfotYPWGN0OJVEN/58IJ3A4GBYcEq3LGAZqKb+ugvP0GNB9CEAA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/http-cache-semantics": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.2.0.tgz", + "integrity": "sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==", + "license": "BSD-2-Clause" + }, + "node_modules/i18next": { + "version": "26.3.4", + "resolved": "https://registry.npmjs.org/i18next/-/i18next-26.3.4.tgz", + "integrity": "sha512-pa7m0d7pBDqGHZxljT+WPFeyFgQ7P7SciPPo1tTqYuO0z4sqADYhwnBESmmGp/wEof1inwdls/k8ZgTg8rxFHA==", + "funding": [ + { + "type": "individual", + "url": "https://www.locize.com/i18next" + }, + { + "type": "individual", + "url": "https://www.i18next.com/how-to/faq#i18next-is-awesome.-how-can-i-support-the-project" + }, + { + "type": "individual", + "url": "https://www.locize.com" + } + ], + "license": "MIT", + "peerDependencies": { + "typescript": "^5 || ^6" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/inline-style-parser": { + "version": "0.2.7", + "resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.7.tgz", + "integrity": "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==", + "license": "MIT" + }, + "node_modules/iron-webcrypto": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/iron-webcrypto/-/iron-webcrypto-1.2.1.tgz", + "integrity": "sha512-feOM6FaSr6rEABp/eDfVseKyTMDt+KGpeB35SkVn9Tyn0CqvVsY3EwI0v5i8nMHyJnzCIQf7nsy3p41TPkJZhg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/brc-dd" + } + }, + "node_modules/is-alphabetical": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.1.tgz", + "integrity": "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-alphanumerical": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-2.0.1.tgz", + "integrity": "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==", + "license": "MIT", + "dependencies": { + "is-alphabetical": "^2.0.0", + "is-decimal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-decimal": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-2.0.1.tgz", + "integrity": "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-docker": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-4.0.0.tgz", + "integrity": "sha512-LHE+wROyG/Y/0ZnbktRCoTix2c1RhgWaZraMZ8o1Q7zCh0VSrICJQO5oqIIISrcSBtrXv0o233w1IYwsWCjTzA==", + "license": "MIT", + "bin": { + "is-docker": "cli.js" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-hexadecimal": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-hexadecimal/-/is-hexadecimal-2.0.1.tgz", + "integrity": "sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg==", + "license": "MIT", + "funding": { + "type": "github", + "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": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz", + "integrity": "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "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": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz", + "integrity": "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsonc-parser": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.3.1.tgz", + "integrity": "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==", + "license": "MIT" + }, + "node_modules/klona": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/klona/-/klona-2.0.6.tgz", + "integrity": "sha512-dhG34DXATL5hSxJbIexCft8FChFXtmskoZYnoPWjXQuebWYCNkVeV3KkGegCK9CP1oswI/vQibS2GY7Em/sJJA==", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/lightningcss": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz", + "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==", + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.32.0", + "lightningcss-darwin-arm64": "1.32.0", + "lightningcss-darwin-x64": "1.32.0", + "lightningcss-freebsd-x64": "1.32.0", + "lightningcss-linux-arm-gnueabihf": "1.32.0", + "lightningcss-linux-arm64-gnu": "1.32.0", + "lightningcss-linux-arm64-musl": "1.32.0", + "lightningcss-linux-x64-gnu": "1.32.0", + "lightningcss-linux-x64-musl": "1.32.0", + "lightningcss-win32-arm64-msvc": "1.32.0", + "lightningcss-win32-x64-msvc": "1.32.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz", + "integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz", + "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz", + "integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz", + "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz", + "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==", + "cpu": [ + "arm" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz", + "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz", + "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz", + "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz", + "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz", + "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz", + "integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/longest-streak": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-3.1.0.tgz", + "integrity": "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/lru-cache": { + "version": "11.5.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.1.tgz", + "integrity": "sha512-RPimw/7aMdv2oqRrxKwvZXcPfwBrn/JZ2xYcY9Hus/6LaS3VOAKVWKWgNLCFSiOm1ESXinjsDlidVU7JlnCN2A==", + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/magicast": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.3.tgz", + "integrity": "sha512-pVKE4UdSQ7DvHzivsCIFx2BJn1mHG6KsyrFcaxFx6tONdneEuThrDx0Cj3AMg58KyN4pzYT+LHOotxDQDjNvkw==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.3", + "@babel/types": "^7.29.0", + "source-map-js": "^1.2.1" + } + }, + "node_modules/markdown-extensions": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/markdown-extensions/-/markdown-extensions-2.0.0.tgz", + "integrity": "sha512-o5vL7aDWatOTX8LzaS1WMoaoxIiLRQJuIKKe2wAw6IeULDHaqbiqiggmx+pKvZDb1Sj+pE46Sn1T7lCqfFtg1Q==", + "license": "MIT", + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/markdown-table": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/markdown-table/-/markdown-table-3.0.4.tgz", + "integrity": "sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/mdast-util-definitions": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/mdast-util-definitions/-/mdast-util-definitions-6.0.0.tgz", + "integrity": "sha512-scTllyX6pnYNZH/AIp/0ePz6s4cZtARxImwoPJ7kS42n+MnVsI4XbnG6d4ibehRIldYMWM2LD7ImQblVhUejVQ==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "@types/unist": "^3.0.0", + "unist-util-visit": "^5.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-directive": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mdast-util-directive/-/mdast-util-directive-3.1.0.tgz", + "integrity": "sha512-I3fNFt+DHmpWCYAT7quoM6lHf9wuqtI+oCOfvILnoicNIqjh5E3dEJWiXuYME2gNe8vl1iMQwyUHa7bgFmak6Q==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "@types/unist": "^3.0.0", + "ccount": "^2.0.0", + "devlop": "^1.0.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0", + "parse-entities": "^4.0.0", + "stringify-entities": "^4.0.0", + "unist-util-visit-parents": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-find-and-replace": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mdast-util-find-and-replace/-/mdast-util-find-and-replace-3.0.2.tgz", + "integrity": "sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "escape-string-regexp": "^5.0.0", + "unist-util-is": "^6.0.0", + "unist-util-visit-parents": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-from-markdown": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-2.0.3.tgz", + "integrity": "sha512-W4mAWTvSlKvf8L6J+VN9yLSqQ9AOAAvHuoDAmPkz4dHf553m5gVj2ejadHJhoJmcmxEnOv6Pa8XJhpxE93kb8Q==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "@types/unist": "^3.0.0", + "decode-named-character-reference": "^1.0.0", + "devlop": "^1.0.0", + "mdast-util-to-string": "^4.0.0", + "micromark": "^4.0.0", + "micromark-util-decode-numeric-character-reference": "^2.0.0", + "micromark-util-decode-string": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0", + "unist-util-stringify-position": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-gfm": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mdast-util-gfm/-/mdast-util-gfm-3.1.0.tgz", + "integrity": "sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ==", + "license": "MIT", + "dependencies": { + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-gfm-autolink-literal": "^2.0.0", + "mdast-util-gfm-footnote": "^2.0.0", + "mdast-util-gfm-strikethrough": "^2.0.0", + "mdast-util-gfm-table": "^2.0.0", + "mdast-util-gfm-task-list-item": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-gfm-autolink-literal": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/mdast-util-gfm-autolink-literal/-/mdast-util-gfm-autolink-literal-2.0.1.tgz", + "integrity": "sha512-5HVP2MKaP6L+G6YaxPNjuL0BPrq9orG3TsrZ9YXbA3vDw/ACI4MEsnoDpn6ZNm7GnZgtAcONJyPhOP8tNJQavQ==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "ccount": "^2.0.0", + "devlop": "^1.0.0", + "mdast-util-find-and-replace": "^3.0.0", + "micromark-util-character": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-gfm-footnote": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mdast-util-gfm-footnote/-/mdast-util-gfm-footnote-2.1.0.tgz", + "integrity": "sha512-sqpDWlsHn7Ac9GNZQMeUzPQSMzR6Wv0WKRNvQRg0KqHh02fpTz69Qc1QSseNX29bhz1ROIyNyxExfawVKTm1GQ==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "devlop": "^1.1.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-gfm-strikethrough": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/mdast-util-gfm-strikethrough/-/mdast-util-gfm-strikethrough-2.0.0.tgz", + "integrity": "sha512-mKKb915TF+OC5ptj5bJ7WFRPdYtuHv0yTRxK2tJvi+BDqbkiG7h7u/9SI89nRAYcmap2xHQL9D+QG/6wSrTtXg==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-gfm-table": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/mdast-util-gfm-table/-/mdast-util-gfm-table-2.0.0.tgz", + "integrity": "sha512-78UEvebzz/rJIxLvE7ZtDd/vIQ0RHv+3Mh5DR96p7cS7HsBhYIICDBCu8csTNWNO6tBWfqXPWekRuj2FNOGOZg==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "devlop": "^1.0.0", + "markdown-table": "^3.0.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-gfm-task-list-item": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/mdast-util-gfm-task-list-item/-/mdast-util-gfm-task-list-item-2.0.0.tgz", + "integrity": "sha512-IrtvNvjxC1o06taBAVJznEnkiHxLFTzgonUdy8hzFVeDun0uTjxxrRGVaNFqkU1wJR3RBPEfsxmU6jDWPofrTQ==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "devlop": "^1.0.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-mdx": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mdast-util-mdx/-/mdast-util-mdx-3.0.0.tgz", + "integrity": "sha512-JfbYLAW7XnYTTbUsmpu0kdBUVe+yKVJZBItEjwyYJiDJuZ9w4eeaqks4HQO+R7objWgS2ymV60GYpI14Ug554w==", + "license": "MIT", + "dependencies": { + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-mdx-expression": "^2.0.0", + "mdast-util-mdx-jsx": "^3.0.0", + "mdast-util-mdxjs-esm": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-mdx-expression": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/mdast-util-mdx-expression/-/mdast-util-mdx-expression-2.0.1.tgz", + "integrity": "sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ==", + "license": "MIT", + "dependencies": { + "@types/estree-jsx": "^1.0.0", + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "devlop": "^1.0.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-mdx-jsx": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/mdast-util-mdx-jsx/-/mdast-util-mdx-jsx-3.2.0.tgz", + "integrity": "sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q==", + "license": "MIT", + "dependencies": { + "@types/estree-jsx": "^1.0.0", + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "@types/unist": "^3.0.0", + "ccount": "^2.0.0", + "devlop": "^1.1.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0", + "parse-entities": "^4.0.0", + "stringify-entities": "^4.0.0", + "unist-util-stringify-position": "^4.0.0", + "vfile-message": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-mdxjs-esm": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/mdast-util-mdxjs-esm/-/mdast-util-mdxjs-esm-2.0.1.tgz", + "integrity": "sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg==", + "license": "MIT", + "dependencies": { + "@types/estree-jsx": "^1.0.0", + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "devlop": "^1.0.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-phrasing": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/mdast-util-phrasing/-/mdast-util-phrasing-4.1.0.tgz", + "integrity": "sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "unist-util-is": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-to-hast": { + "version": "13.2.1", + "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.1.tgz", + "integrity": "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "@ungap/structured-clone": "^1.0.0", + "devlop": "^1.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "trim-lines": "^3.0.0", + "unist-util-position": "^5.0.0", + "unist-util-visit": "^5.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-to-markdown": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/mdast-util-to-markdown/-/mdast-util-to-markdown-2.1.2.tgz", + "integrity": "sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "@types/unist": "^3.0.0", + "longest-streak": "^3.0.0", + "mdast-util-phrasing": "^4.0.0", + "mdast-util-to-string": "^4.0.0", + "micromark-util-classify-character": "^2.0.0", + "micromark-util-decode-string": "^2.0.0", + "unist-util-visit": "^5.0.0", + "zwitch": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-to-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/mdast-util-to-string/-/mdast-util-to-string-4.0.0.tgz", + "integrity": "sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdn-data": { + "version": "2.27.1", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz", + "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==", + "license": "CC0-1.0" + }, + "node_modules/micromark": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.2.tgz", + "integrity": "sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "@types/debug": "^4.0.0", + "debug": "^4.0.0", + "decode-named-character-reference": "^1.0.0", + "devlop": "^1.0.0", + "micromark-core-commonmark": "^2.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-chunked": "^2.0.0", + "micromark-util-combine-extensions": "^2.0.0", + "micromark-util-decode-numeric-character-reference": "^2.0.0", + "micromark-util-encode": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0", + "micromark-util-resolve-all": "^2.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "micromark-util-subtokenize": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-core-commonmark": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-2.0.3.tgz", + "integrity": "sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "decode-named-character-reference": "^1.0.0", + "devlop": "^1.0.0", + "micromark-factory-destination": "^2.0.0", + "micromark-factory-label": "^2.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-factory-title": "^2.0.0", + "micromark-factory-whitespace": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-chunked": "^2.0.0", + "micromark-util-classify-character": "^2.0.0", + "micromark-util-html-tag-name": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0", + "micromark-util-resolve-all": "^2.0.0", + "micromark-util-subtokenize": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-extension-directive": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/micromark-extension-directive/-/micromark-extension-directive-4.0.0.tgz", + "integrity": "sha512-/C2nqVmXXmiseSSuCdItCMho7ybwwop6RrrRPk0KbOHW21JKoCldC+8rFOaundDoRBUWBnJJcxeA/Kvi34WQXg==", + "license": "MIT", + "dependencies": { + "devlop": "^1.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-factory-whitespace": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0", + "parse-entities": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-gfm": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm/-/micromark-extension-gfm-3.0.0.tgz", + "integrity": "sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w==", + "license": "MIT", + "dependencies": { + "micromark-extension-gfm-autolink-literal": "^2.0.0", + "micromark-extension-gfm-footnote": "^2.0.0", + "micromark-extension-gfm-strikethrough": "^2.0.0", + "micromark-extension-gfm-table": "^2.0.0", + "micromark-extension-gfm-tagfilter": "^2.0.0", + "micromark-extension-gfm-task-list-item": "^2.0.0", + "micromark-util-combine-extensions": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-gfm-autolink-literal": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm-autolink-literal/-/micromark-extension-gfm-autolink-literal-2.1.0.tgz", + "integrity": "sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==", + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-gfm-footnote": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm-footnote/-/micromark-extension-gfm-footnote-2.1.0.tgz", + "integrity": "sha512-/yPhxI1ntnDNsiHtzLKYnE3vf9JZ6cAisqVDauhp4CEHxlb4uoOTxOCJ+9s51bIB8U1N1FJ1RXOKTIlD5B/gqw==", + "license": "MIT", + "dependencies": { + "devlop": "^1.0.0", + "micromark-core-commonmark": "^2.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-gfm-strikethrough": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm-strikethrough/-/micromark-extension-gfm-strikethrough-2.1.0.tgz", + "integrity": "sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw==", + "license": "MIT", + "dependencies": { + "devlop": "^1.0.0", + "micromark-util-chunked": "^2.0.0", + "micromark-util-classify-character": "^2.0.0", + "micromark-util-resolve-all": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-gfm-table": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm-table/-/micromark-extension-gfm-table-2.1.1.tgz", + "integrity": "sha512-t2OU/dXXioARrC6yWfJ4hqB7rct14e8f7m0cbI5hUmDyyIlwv5vEtooptH8INkbLzOatzKuVbQmAYcbWoyz6Dg==", + "license": "MIT", + "dependencies": { + "devlop": "^1.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-gfm-tagfilter": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm-tagfilter/-/micromark-extension-gfm-tagfilter-2.0.0.tgz", + "integrity": "sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg==", + "license": "MIT", + "dependencies": { + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-gfm-task-list-item": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm-task-list-item/-/micromark-extension-gfm-task-list-item-2.1.0.tgz", + "integrity": "sha512-qIBZhqxqI6fjLDYFTBIa4eivDMnP+OZqsNwmQ3xNLE4Cxwc+zfQEfbs6tzAo2Hjq+bh6q5F+Z8/cksrLFYWQQw==", + "license": "MIT", + "dependencies": { + "devlop": "^1.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-mdx-expression": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/micromark-extension-mdx-expression/-/micromark-extension-mdx-expression-3.0.1.tgz", + "integrity": "sha512-dD/ADLJ1AeMvSAKBwO22zG22N4ybhe7kFIZ3LsDI0GlsNr2A3KYxb0LdC1u5rj4Nw+CHKY0RVdnHX8vj8ejm4Q==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "devlop": "^1.0.0", + "micromark-factory-mdx-expression": "^2.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-events-to-acorn": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-extension-mdx-jsx": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/micromark-extension-mdx-jsx/-/micromark-extension-mdx-jsx-3.0.2.tgz", + "integrity": "sha512-e5+q1DjMh62LZAJOnDraSSbDMvGJ8x3cbjygy2qFEi7HCeUT4BDKCvMozPozcD6WmOt6sVvYDNBKhFSz3kjOVQ==", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "devlop": "^1.0.0", + "estree-util-is-identifier-name": "^3.0.0", + "micromark-factory-mdx-expression": "^2.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-events-to-acorn": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0", + "vfile-message": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-mdx-md": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/micromark-extension-mdx-md/-/micromark-extension-mdx-md-2.0.0.tgz", + "integrity": "sha512-EpAiszsB3blw4Rpba7xTOUptcFeBFi+6PY8VnJ2hhimH+vCQDirWgsMpz7w1XcZE7LVrSAUGb9VJpG9ghlYvYQ==", + "license": "MIT", + "dependencies": { + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-mdxjs": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/micromark-extension-mdxjs/-/micromark-extension-mdxjs-3.0.0.tgz", + "integrity": "sha512-A873fJfhnJ2siZyUrJ31l34Uqwy4xIFmvPY1oj+Ean5PHcPBYzEsvqvWGaWcfEIr11O5Dlw3p2y0tZWpKHDejQ==", + "license": "MIT", + "dependencies": { + "acorn": "^8.0.0", + "acorn-jsx": "^5.0.0", + "micromark-extension-mdx-expression": "^3.0.0", + "micromark-extension-mdx-jsx": "^3.0.0", + "micromark-extension-mdx-md": "^2.0.0", + "micromark-extension-mdxjs-esm": "^3.0.0", + "micromark-util-combine-extensions": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-mdxjs-esm": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/micromark-extension-mdxjs-esm/-/micromark-extension-mdxjs-esm-3.0.0.tgz", + "integrity": "sha512-DJFl4ZqkErRpq/dAPyeWp15tGrcrrJho1hKK5uBS70BCtfrIFg81sqcTVu3Ta+KD1Tk5vAtBNElWxtAa+m8K9A==", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "devlop": "^1.0.0", + "micromark-core-commonmark": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-events-to-acorn": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0", + "unist-util-position-from-estree": "^2.0.0", + "vfile-message": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-factory-destination": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-factory-destination/-/micromark-factory-destination-2.0.1.tgz", + "integrity": "sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-label": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-factory-label/-/micromark-factory-label-2.0.1.tgz", + "integrity": "sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "devlop": "^1.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-mdx-expression": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/micromark-factory-mdx-expression/-/micromark-factory-mdx-expression-2.0.3.tgz", + "integrity": "sha512-kQnEtA3vzucU2BkrIa8/VaSAsP+EJ3CKOvhMuJgOEGg9KDC6OAY6nSnNDVRiVNRqj7Y4SlSzcStaH/5jge8JdQ==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "devlop": "^1.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-events-to-acorn": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0", + "unist-util-position-from-estree": "^2.0.0", + "vfile-message": "^4.0.0" + } + }, + "node_modules/micromark-factory-space": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-factory-space/-/micromark-factory-space-2.0.1.tgz", + "integrity": "sha512-zRkxjtBxxLd2Sc0d+fbnEunsTj46SWXgXciZmHq0kDYGnck/ZSGj9/wULTV95uoeYiK5hRXP2mJ98Uo4cq/LQg==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-title": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-factory-title/-/micromark-factory-title-2.0.1.tgz", + "integrity": "sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-whitespace": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-factory-whitespace/-/micromark-factory-whitespace-2.0.1.tgz", + "integrity": "sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-character": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz", + "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-chunked": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-chunked/-/micromark-util-chunked-2.0.1.tgz", + "integrity": "sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-classify-character": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-classify-character/-/micromark-util-classify-character-2.0.1.tgz", + "integrity": "sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-combine-extensions": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-combine-extensions/-/micromark-util-combine-extensions-2.0.1.tgz", + "integrity": "sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-chunked": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-decode-numeric-character-reference": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/micromark-util-decode-numeric-character-reference/-/micromark-util-decode-numeric-character-reference-2.0.2.tgz", + "integrity": "sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-decode-string": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-decode-string/-/micromark-util-decode-string-2.0.1.tgz", + "integrity": "sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "decode-named-character-reference": "^1.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-decode-numeric-character-reference": "^2.0.0", + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-encode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz", + "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-events-to-acorn": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/micromark-util-events-to-acorn/-/micromark-util-events-to-acorn-2.0.3.tgz", + "integrity": "sha512-jmsiEIiZ1n7X1Rr5k8wVExBQCg5jy4UXVADItHmNk1zkwEVhBuIUKRu3fqv+hs4nxLISi2DQGlqIOGiFxgbfHg==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "@types/unist": "^3.0.0", + "devlop": "^1.0.0", + "estree-util-visit": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0", + "vfile-message": "^4.0.0" + } + }, + "node_modules/micromark-util-html-tag-name": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-html-tag-name/-/micromark-util-html-tag-name-2.0.1.tgz", + "integrity": "sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-normalize-identifier": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-normalize-identifier/-/micromark-util-normalize-identifier-2.0.1.tgz", + "integrity": "sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-resolve-all": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-resolve-all/-/micromark-util-resolve-all-2.0.1.tgz", + "integrity": "sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-sanitize-uri": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz", + "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-encode": "^2.0.0", + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-subtokenize": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/micromark-util-subtokenize/-/micromark-util-subtokenize-2.1.0.tgz", + "integrity": "sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "devlop": "^1.0.0", + "micromark-util-chunked": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-symbol": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz", + "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-types": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.2.tgz", + "integrity": "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/mrmime": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/mrmime/-/mrmime-2.0.1.tgz", + "integrity": "sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.15", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.15.tgz", + "integrity": "sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/neotraverse": { + "version": "0.6.18", + "resolved": "https://registry.npmjs.org/neotraverse/-/neotraverse-0.6.18.tgz", + "integrity": "sha512-Z4SmBUweYa09+o6pG+eASabEpP6QkQ70yHj351pQoEXIs8uHbaU2DWVmzBANKgflPa47A50PtB2+NgRpQvr7vA==", + "license": "MIT", + "engines": { + "node": ">= 10" + } + }, + "node_modules/nlcst-to-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/nlcst-to-string/-/nlcst-to-string-4.0.0.tgz", + "integrity": "sha512-YKLBCcUYKAg0FNlOBT6aI91qFmSiFKiluk655WzPF+DDMA02qIyy8uiRqI8QXtcFpEvll12LpL5MXqEmAZ+dcA==", + "license": "MIT", + "dependencies": { + "@types/nlcst": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/node-fetch-native": { + "version": "1.6.7", + "resolved": "https://registry.npmjs.org/node-fetch-native/-/node-fetch-native-1.6.7.tgz", + "integrity": "sha512-g9yhqoedzIUm0nTnTqAQvueMPVOuIY16bqgAJJC8XOOubYFNwz6IER9qs0Gq2Xd0+CecCKFjtdDTMA4u4xG06Q==", + "license": "MIT" + }, + "node_modules/node-mock-http": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/node-mock-http/-/node-mock-http-1.0.4.tgz", + "integrity": "sha512-8DY+kFsDkNXy1sJglUfuODx1/opAGJGyrTuFqEoN90oRc2Vk0ZbD4K2qmKXBBEhZQzdKHIVfEJpDU8Ak2NJEvQ==", + "license": "MIT" + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/nth-check": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz", + "integrity": "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==", + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^1.0.0" + }, + "funding": { + "url": "https://github.com/fb55/nth-check?sponsor=1" + } + }, + "node_modules/obug": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.3.tgz", + "integrity": "sha512-9miFgM2OFba7hB+pRgvtV84pYTBaoTHohvmIgiRt6dRIzbwEOIaNaP+dIlGs2fNFoB0SeISs0Jz5WFVRid6Xyg==", + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/ofetch": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/ofetch/-/ofetch-1.5.1.tgz", + "integrity": "sha512-2W4oUZlVaqAPAil6FUg/difl6YhqhUR7x2eZY4bQCko22UXg3hptq9KLQdqFClV+Wu85UX7hNtdGTngi/1BxcA==", + "license": "MIT", + "dependencies": { + "destr": "^2.0.5", + "node-fetch-native": "^1.6.7", + "ufo": "^1.6.1" + } + }, + "node_modules/ohash": { + "version": "2.0.11", + "resolved": "https://registry.npmjs.org/ohash/-/ohash-2.0.11.tgz", + "integrity": "sha512-RdR9FQrFwNBNXAr4GixM8YaRZRJ5PUWbKYbE5eOsrwAjJW0q2REGcf79oYPsLyskQCZG1PLN+S/K1V00joZAoQ==", + "license": "MIT" + }, + "node_modules/oniguruma-parser": { + "version": "0.12.2", + "resolved": "https://registry.npmjs.org/oniguruma-parser/-/oniguruma-parser-0.12.2.tgz", + "integrity": "sha512-6HVa5oIrgMC6aA6WF6XyyqbhRPJrKR02L20+2+zpDtO5QAzGHAUGw5TKQvwi5vctNnRHkJYmjAhRVQF2EKdTQw==", + "license": "MIT" + }, + "node_modules/oniguruma-to-es": { + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/oniguruma-to-es/-/oniguruma-to-es-4.3.6.tgz", + "integrity": "sha512-csuQ9x3Yr0cEIs/Zgx/OEt9iBw9vqIunAPQkx19R/fiMq2oGVTgcMqO/V3Ybqefr1TBvosI6jU539ksaBULJyA==", + "license": "MIT", + "dependencies": { + "oniguruma-parser": "^0.12.2", + "regex": "^6.1.0", + "regex-recursion": "^6.0.2" + } + }, + "node_modules/p-limit": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-7.3.0.tgz", + "integrity": "sha512-7cIXg/Z0M5WZRblrsOla88S4wAK+zOQQWeBYfV3qJuJXMr+LnbYjaadrFaS0JILfEDPVqHyKnZ1Z/1d6J9VVUw==", + "license": "MIT", + "dependencies": { + "yocto-queue": "^1.2.1" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-queue": { + "version": "9.3.1", + "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-9.3.1.tgz", + "integrity": "sha512-POWdiIPmsUPGwb4FeQ4OBg46aqmcInSWe45CKDsGHiOBiVQM9chqfQTuqhuTzcg2Vz9faTI65at0KkVyVEiCHw==", + "license": "MIT", + "dependencies": { + "eventemitter3": "^5.0.4", + "p-timeout": "^7.0.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-timeout": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-7.0.1.tgz", + "integrity": "sha512-AxTM2wDGORHGEkPCt8yqxOTMgpfbEHqF51f/5fJCmwFC3C/zNcGT63SymH2ttOAaiIws2zVg4+izQCjrakcwHg==", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/package-manager-detector": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/package-manager-detector/-/package-manager-detector-1.7.0.tgz", + "integrity": "sha512-xg1eHpwYL/D/HEdWw2goFZP6vV0FH7W+PZ5rFkGjdIDLtxq7EkzBUeT3m+lndYCt8wKbmofUu1MUdMCXkCk9ZQ==", + "license": "MIT" + }, + "node_modules/pagefind": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/pagefind/-/pagefind-1.5.2.tgz", + "integrity": "sha512-XTUaK0hXMCu2jszWE584JGQT7y284TmMV9l/HX3rnG5uo3rHI/uHU56XTyyyPFjeWEBxECbAi0CaFDJOONtG0Q==", + "license": "MIT", + "bin": { + "pagefind": "lib/runner/bin.cjs" + }, + "optionalDependencies": { + "@pagefind/darwin-arm64": "1.5.2", + "@pagefind/darwin-x64": "1.5.2", + "@pagefind/freebsd-x64": "1.5.2", + "@pagefind/linux-arm64": "1.5.2", + "@pagefind/linux-x64": "1.5.2", + "@pagefind/windows-arm64": "1.5.2", + "@pagefind/windows-x64": "1.5.2" + } + }, + "node_modules/parse-entities": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/parse-entities/-/parse-entities-4.0.2.tgz", + "integrity": "sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw==", + "license": "MIT", + "dependencies": { + "@types/unist": "^2.0.0", + "character-entities-legacy": "^3.0.0", + "character-reference-invalid": "^2.0.0", + "decode-named-character-reference": "^1.0.0", + "is-alphanumerical": "^2.0.0", + "is-decimal": "^2.0.0", + "is-hexadecimal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/parse-entities/node_modules/@types/unist": { + "version": "2.0.11", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.11.tgz", + "integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==", + "license": "MIT" + }, + "node_modules/parse-latin": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/parse-latin/-/parse-latin-7.0.0.tgz", + "integrity": "sha512-mhHgobPPua5kZ98EF4HWiH167JWBfl4pvAIXXdbaVohtK7a6YBOy56kvhCqduqyo/f3yrHFWmqmiMg/BkBkYYQ==", + "license": "MIT", + "dependencies": { + "@types/nlcst": "^2.0.0", + "@types/unist": "^3.0.0", + "nlcst-to-string": "^4.0.0", + "unist-util-modify-children": "^4.0.0", + "unist-util-visit-children": "^3.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/parse5": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", + "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==", + "license": "MIT", + "dependencies": { + "entities": "^6.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/piccolore": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/piccolore/-/piccolore-0.1.3.tgz", + "integrity": "sha512-o8bTeDWjE086iwKrROaDf31K0qC/BENdm15/uH9usSC/uZjJOKb2YGiVHfLY4GhwsERiPI1jmwI2XrA7ACOxVw==", + "license": "ISC" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz", + "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.16", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.16.tgz", + "integrity": "sha512-vuwillviilfKZsg0VGj5R/YwwcHx4SLsIOI/7K6mQkWx+l5cUHTjj5g0AasTBcyXsbfTgrwsUNmVUb5xVwyPwg==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.12", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-nested": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/postcss-nested/-/postcss-nested-6.2.0.tgz", + "integrity": "sha512-HQbt28KulC5AJzG+cZtj9kvKB93CFCdLvog1WFLf1D+xmMvPGlBstkpTEZfK5+AN9hfJocyBFCNiqyS48bpgzQ==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "postcss-selector-parser": "^6.1.1" + }, + "engines": { + "node": ">=12.0" + }, + "peerDependencies": { + "postcss": "^8.2.14" + } + }, + "node_modules/postcss-selector-parser": { + "version": "6.1.4", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.4.tgz", + "integrity": "sha512-bIoJLOmjCO1S9XdY/DcnR5hJxvrDir1PbGChrzXG3vw0/FOliy/fA3dmdhQ441kah4gKv+TwckGzex6wNS5cnQ==", + "license": "MIT", + "dependencies": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/prismjs": { + "version": "1.30.0", + "resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.30.0.tgz", + "integrity": "sha512-DEvV2ZF2r2/63V+tK8hQvrR2ZGn10srHbXviTlcv7Kpzw8jWiNTqbVgjO3IY8RxrrOUF8VPMQQFysYYYv0YZxw==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/process-ancestry": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/process-ancestry/-/process-ancestry-0.1.0.tgz", + "integrity": "sha512-tGqJW/UnclpYASFcM6Xh8D8l/BMtaQ9+CSG0vlJSJTcdMM4lDRv4c6H0Pdcsfted+bVczdYSfk2fdukg2gQkZg==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/property-information": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.2.0.tgz", + "integrity": "sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/radix3": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/radix3/-/radix3-1.1.2.tgz", + "integrity": "sha512-b484I/7b8rDEdSDKckSSBA8knMpcdsXudlE/LNL639wFoHKwLbEkQFZHWEYwDC0wa0FKUcCY+GAF73Z7wxNVFA==", + "license": "MIT" + }, + "node_modules/readdirp": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-5.0.0.tgz", + "integrity": "sha512-9u/XQ1pvrQtYyMpZe7DXKv2p5CNvyVwzUB6uhLAnQwHMSgKMBR62lc7AHljaeteeHXn11XTAaLLUVZYVZyuRBQ==", + "license": "MIT", + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/recma-build-jsx": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/recma-build-jsx/-/recma-build-jsx-1.0.0.tgz", + "integrity": "sha512-8GtdyqaBcDfva+GUKDr3nev3VpKAhup1+RvkMvUxURHpW7QyIvk9F5wz7Vzo06CEMSilw6uArgRqhpiUcWp8ew==", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "estree-util-build-jsx": "^3.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/recma-jsx": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/recma-jsx/-/recma-jsx-1.0.1.tgz", + "integrity": "sha512-huSIy7VU2Z5OLv6oFLosQGGDqPqdO1iq6bWNAdhzMxSJP7RAso4fCZ1cKu8j9YHCZf3TPrq4dw3okhrylgcd7w==", + "license": "MIT", + "dependencies": { + "acorn-jsx": "^5.0.0", + "estree-util-to-js": "^2.0.0", + "recma-parse": "^1.0.0", + "recma-stringify": "^1.0.0", + "unified": "^11.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + }, + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/recma-parse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/recma-parse/-/recma-parse-1.0.0.tgz", + "integrity": "sha512-OYLsIGBB5Y5wjnSnQW6t3Xg7q3fQ7FWbw/vcXtORTnyaSFscOtABg+7Pnz6YZ6c27fG1/aN8CjfwoUEUIdwqWQ==", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "esast-util-from-js": "^2.0.0", + "unified": "^11.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/recma-stringify": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/recma-stringify/-/recma-stringify-1.0.0.tgz", + "integrity": "sha512-cjwII1MdIIVloKvC9ErQ+OgAtwHBmcZ0Bg4ciz78FtbT8In39aAYbaA7zvxQ61xVMSPE8WxhLwLbhif4Js2C+g==", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "estree-util-to-js": "^2.0.0", + "unified": "^11.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/regex": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/regex/-/regex-6.1.0.tgz", + "integrity": "sha512-6VwtthbV4o/7+OaAF9I5L5V3llLEsoPyq9P1JVXkedTP33c7MfCG0/5NOPcSJn0TzXcG9YUrR0gQSWioew3LDg==", + "license": "MIT", + "dependencies": { + "regex-utilities": "^2.3.0" + } + }, + "node_modules/regex-recursion": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/regex-recursion/-/regex-recursion-6.0.2.tgz", + "integrity": "sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg==", + "license": "MIT", + "dependencies": { + "regex-utilities": "^2.3.0" + } + }, + "node_modules/regex-utilities": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/regex-utilities/-/regex-utilities-2.3.0.tgz", + "integrity": "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng==", + "license": "MIT" + }, + "node_modules/rehype": { + "version": "13.0.2", + "resolved": "https://registry.npmjs.org/rehype/-/rehype-13.0.2.tgz", + "integrity": "sha512-j31mdaRFrwFRUIlxGeuPXXKWQxet52RBQRvCmzl5eCefn/KGbomK5GMHNMsOJf55fgo3qw5tST5neDuarDYR2A==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "rehype-parse": "^9.0.0", + "rehype-stringify": "^10.0.0", + "unified": "^11.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/rehype-expressive-code": { + "version": "0.44.0", + "resolved": "https://registry.npmjs.org/rehype-expressive-code/-/rehype-expressive-code-0.44.0.tgz", + "integrity": "sha512-5r74C5F2sMR3X+QJH8OKWgZBO/cqRw5W1fLT6GVlSfLqepk+4j8tGFkyPqZYWjwntsBHzKPDH2zI68sZ7ScLfA==", + "license": "MIT", + "dependencies": { + "expressive-code": "^0.44.0" + } + }, + "node_modules/rehype-format": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/rehype-format/-/rehype-format-5.0.1.tgz", + "integrity": "sha512-zvmVru9uB0josBVpr946OR8ui7nJEdzZobwLOOqHb/OOD88W0Vk2SqLwoVOj0fM6IPCCO6TaV9CvQvJMWwukFQ==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "hast-util-format": "^1.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/rehype-parse": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/rehype-parse/-/rehype-parse-9.0.1.tgz", + "integrity": "sha512-ksCzCD0Fgfh7trPDxr2rSylbwq9iYDkSn8TCDmEJ49ljEUBxDVCzCHv7QNzZOfODanX4+bWQ4WZqLCRWYLfhag==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "hast-util-from-html": "^2.0.0", + "unified": "^11.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/rehype-raw": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/rehype-raw/-/rehype-raw-7.0.0.tgz", + "integrity": "sha512-/aE8hCfKlQeA8LmyeyQvQF3eBiLRGNlfBJEvWH7ivp9sBqs7TNqBL5X3v157rM4IFETqDnIOO+z5M/biZbo9Ww==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "hast-util-raw": "^9.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/rehype-recma": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/rehype-recma/-/rehype-recma-1.0.0.tgz", + "integrity": "sha512-lqA4rGUf1JmacCNWWZx0Wv1dHqMwxzsDWYMTowuplHF3xH0N/MmrZ/G3BDZnzAkRmxDadujCjaKM2hqYdCBOGw==", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "@types/hast": "^3.0.0", + "hast-util-to-estree": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/rehype-stringify": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/rehype-stringify/-/rehype-stringify-10.0.1.tgz", + "integrity": "sha512-k9ecfXHmIPuFVI61B9DeLPN0qFHfawM6RsuX48hoqlaKSF61RskNjSm1lI8PhBEM0MRdLxVVm4WmTqJQccH9mA==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "hast-util-to-html": "^9.0.0", + "unified": "^11.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/remark-directive": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/remark-directive/-/remark-directive-4.0.0.tgz", + "integrity": "sha512-7sxn4RfF1o3izevPV1DheyGDD6X4c9hrGpfdUpm7uC++dqrnJxIZVkk7CoKqcLm0VUMAuOol7Mno3m6g8cfMuA==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "mdast-util-directive": "^3.0.0", + "micromark-extension-directive": "^4.0.0", + "unified": "^11.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/remark-gfm": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/remark-gfm/-/remark-gfm-4.0.1.tgz", + "integrity": "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "mdast-util-gfm": "^3.0.0", + "micromark-extension-gfm": "^3.0.0", + "remark-parse": "^11.0.0", + "remark-stringify": "^11.0.0", + "unified": "^11.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/remark-mdx": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/remark-mdx/-/remark-mdx-3.1.1.tgz", + "integrity": "sha512-Pjj2IYlUY3+D8x00UJsIOg5BEvfMyeI+2uLPn9VO9Wg4MEtN/VTIq2NEJQfde9PnX15KgtHyl9S0BcTnWrIuWg==", + "license": "MIT", + "dependencies": { + "mdast-util-mdx": "^3.0.0", + "micromark-extension-mdxjs": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/remark-parse": { + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/remark-parse/-/remark-parse-11.0.0.tgz", + "integrity": "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "mdast-util-from-markdown": "^2.0.0", + "micromark-util-types": "^2.0.0", + "unified": "^11.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/remark-rehype": { + "version": "11.1.2", + "resolved": "https://registry.npmjs.org/remark-rehype/-/remark-rehype-11.1.2.tgz", + "integrity": "sha512-Dh7l57ianaEoIpzbp0PC9UKAdCSVklD8E5Rpw7ETfbTl3FqcOOgq5q2LVDhgGCkaBv7p24JXikPdvhhmHvKMsw==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "mdast-util-to-hast": "^13.0.0", + "unified": "^11.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/remark-smartypants": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/remark-smartypants/-/remark-smartypants-3.0.2.tgz", + "integrity": "sha512-ILTWeOriIluwEvPjv67v7Blgrcx+LZOkAUVtKI3putuhlZm84FnqDORNXPPm+HY3NdZOMhyDwZ1E+eZB/Df5dA==", + "license": "MIT", + "dependencies": { + "retext": "^9.0.0", + "retext-smartypants": "^6.0.0", + "unified": "^11.0.4", + "unist-util-visit": "^5.0.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/remark-stringify": { + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/remark-stringify/-/remark-stringify-11.0.0.tgz", + "integrity": "sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "mdast-util-to-markdown": "^2.0.0", + "unified": "^11.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/resolve-pkg-maps": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", + "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==", + "license": "MIT", + "funding": { + "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" + } + }, + "node_modules/retext": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/retext/-/retext-9.0.0.tgz", + "integrity": "sha512-sbMDcpHCNjvlheSgMfEcVrZko3cDzdbe1x/e7G66dFp0Ff7Mldvi2uv6JkJQzdRcvLYE8CA8Oe8siQx8ZOgTcA==", + "license": "MIT", + "dependencies": { + "@types/nlcst": "^2.0.0", + "retext-latin": "^4.0.0", + "retext-stringify": "^4.0.0", + "unified": "^11.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/retext-latin": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/retext-latin/-/retext-latin-4.0.0.tgz", + "integrity": "sha512-hv9woG7Fy0M9IlRQloq/N6atV82NxLGveq+3H2WOi79dtIYWN8OaxogDm77f8YnVXJL2VD3bbqowu5E3EMhBYA==", + "license": "MIT", + "dependencies": { + "@types/nlcst": "^2.0.0", + "parse-latin": "^7.0.0", + "unified": "^11.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/retext-smartypants": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/retext-smartypants/-/retext-smartypants-6.2.0.tgz", + "integrity": "sha512-kk0jOU7+zGv//kfjXEBjdIryL1Acl4i9XNkHxtM7Tm5lFiCog576fjNC9hjoR7LTKQ0DsPWy09JummSsH1uqfQ==", + "license": "MIT", + "dependencies": { + "@types/nlcst": "^2.0.0", + "nlcst-to-string": "^4.0.0", + "unist-util-visit": "^5.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/retext-stringify": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/retext-stringify/-/retext-stringify-4.0.0.tgz", + "integrity": "sha512-rtfN/0o8kL1e+78+uxPTqu1Klt0yPzKuQ2BfWwwfgIUSayyzxpM1PJzkKt4V8803uB9qSy32MvI7Xep9khTpiA==", + "license": "MIT", + "dependencies": { + "@types/nlcst": "^2.0.0", + "nlcst-to-string": "^4.0.0", + "unified": "^11.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/rolldown": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.1.4.tgz", + "integrity": "sha512-IjZYiLxZwpnhwhdBH2ugdTGVSdhCQUmLxLoqyjiL0JxYjyRst+5a0P3xfrTxJ5F638j4Mvvw5FAX5XE6eHpXbA==", + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.138.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm64": "1.1.4", + "@rolldown/binding-darwin-arm64": "1.1.4", + "@rolldown/binding-darwin-x64": "1.1.4", + "@rolldown/binding-freebsd-x64": "1.1.4", + "@rolldown/binding-linux-arm-gnueabihf": "1.1.4", + "@rolldown/binding-linux-arm64-gnu": "1.1.4", + "@rolldown/binding-linux-arm64-musl": "1.1.4", + "@rolldown/binding-linux-ppc64-gnu": "1.1.4", + "@rolldown/binding-linux-s390x-gnu": "1.1.4", + "@rolldown/binding-linux-x64-gnu": "1.1.4", + "@rolldown/binding-linux-x64-musl": "1.1.4", + "@rolldown/binding-openharmony-arm64": "1.1.4", + "@rolldown/binding-wasm32-wasi": "1.1.4", + "@rolldown/binding-win32-arm64-msvc": "1.1.4", + "@rolldown/binding-win32-x64-msvc": "1.1.4" + } + }, + "node_modules/satteri": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/satteri/-/satteri-0.9.4.tgz", + "integrity": "sha512-BKob126Tay84diOZsnVNH/Q/c+3njPJTCad3w5zLKa6j8bVjxskPNHDtxrMwYK4bN/RlqUSdMnPwKY4k65EMOQ==", + "dependencies": { + "@types/estree-jsx": "^1.0.5", + "@types/hast": "^3.0.4", + "@types/mdast": "^4.0.4", + "@types/unist": "^3.0.3" + }, + "optionalDependencies": { + "@bruits/satteri-darwin-arm64": "0.9.4", + "@bruits/satteri-darwin-x64": "0.9.4", + "@bruits/satteri-linux-arm64-gnu": "0.9.4", + "@bruits/satteri-linux-arm64-musl": "0.9.4", + "@bruits/satteri-linux-x64-gnu": "0.9.4", + "@bruits/satteri-linux-x64-musl": "0.9.4", + "@bruits/satteri-wasm32-wasi": "0.9.4", + "@bruits/satteri-win32-arm64-msvc": "0.9.4", + "@bruits/satteri-win32-x64-msvc": "0.9.4" + } + }, + "node_modules/sax": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.6.0.tgz", + "integrity": "sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=11.0.0" + } + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/sharp": { + "version": "0.35.3", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.3.tgz", + "integrity": "sha512-ej0zVHuZGHCiABXcNxeYhpRnPNPAcvbG8RMdBAhDAxLKkCRVSpK3Iyu7qbqw3JMzoj0REeM6f3tJLtVwl0023Q==", + "license": "Apache-2.0", + "dependencies": { + "@img/colour": "^1.1.0", + "detect-libc": "^2.1.2", + "semver": "^7.8.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.35.3", + "@img/sharp-darwin-x64": "0.35.3", + "@img/sharp-freebsd-wasm32": "0.35.3", + "@img/sharp-libvips-darwin-arm64": "1.3.2", + "@img/sharp-libvips-darwin-x64": "1.3.2", + "@img/sharp-libvips-linux-arm": "1.3.2", + "@img/sharp-libvips-linux-arm64": "1.3.2", + "@img/sharp-libvips-linux-ppc64": "1.3.2", + "@img/sharp-libvips-linux-riscv64": "1.3.2", + "@img/sharp-libvips-linux-s390x": "1.3.2", + "@img/sharp-libvips-linux-x64": "1.3.2", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.2", + "@img/sharp-libvips-linuxmusl-x64": "1.3.2", + "@img/sharp-linux-arm": "0.35.3", + "@img/sharp-linux-arm64": "0.35.3", + "@img/sharp-linux-ppc64": "0.35.3", + "@img/sharp-linux-riscv64": "0.35.3", + "@img/sharp-linux-s390x": "0.35.3", + "@img/sharp-linux-x64": "0.35.3", + "@img/sharp-linuxmusl-arm64": "0.35.3", + "@img/sharp-linuxmusl-x64": "0.35.3", + "@img/sharp-webcontainers-wasm32": "0.35.3", + "@img/sharp-win32-arm64": "0.35.3", + "@img/sharp-win32-ia32": "0.35.3", + "@img/sharp-win32-x64": "0.35.3" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/shiki": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/shiki/-/shiki-4.3.1.tgz", + "integrity": "sha512-oR+qDVi2OjX1tmDpyv+3KviX01KzO6Af+0NNnKnsp9491UEGz2YpxTuJboS/6VhYpTdqzmuJBuiTlrAWWJAssw==", + "license": "MIT", + "dependencies": { + "@shikijs/core": "4.3.1", + "@shikijs/engine-javascript": "4.3.1", + "@shikijs/engine-oniguruma": "4.3.1", + "@shikijs/langs": "4.3.1", + "@shikijs/themes": "4.3.1", + "@shikijs/types": "4.3.1", + "@shikijs/vscode-textmate": "^10.0.2", + "@types/hast": "^3.0.4" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/sisteransi": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", + "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", + "license": "MIT" + }, + "node_modules/sitemap": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/sitemap/-/sitemap-9.0.1.tgz", + "integrity": "sha512-S6hzjGJSG3d6if0YoF5kTyeRJvia6FSTBroE5fQ0bu1QNxyJqhhinfUsXi9fH3MgtXODWvwo2BDyQSnhPQ88uQ==", + "license": "MIT", + "dependencies": { + "@types/node": "^24.9.2", + "@types/sax": "^1.2.1", + "arg": "^5.0.0", + "sax": "^1.4.1" + }, + "bin": { + "sitemap": "dist/esm/cli.js" + }, + "engines": { + "node": ">=20.19.5", + "npm": ">=10.8.2" + } + }, + "node_modules/smol-toml": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.7.0.tgz", + "integrity": "sha512-aqVvWoyO21L23mb+drl4RmMXbf6N7FdHjAhTRA9ZBL7apWBgfWC16KjrASI+1p9GAroljyMHj6fK67i0UiTNvQ==", + "license": "BSD-3-Clause", + "engines": { + "node": ">= 18" + }, + "funding": { + "url": "https://github.com/sponsors/cyyynthia" + } + }, + "node_modules/source-map": { + "version": "0.7.6", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.6.tgz", + "integrity": "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==", + "license": "BSD-3-Clause", + "engines": { + "node": ">= 12" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/space-separated-tokens": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz", + "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/stream-replace-string": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/stream-replace-string/-/stream-replace-string-2.0.0.tgz", + "integrity": "sha512-TlnjJ1C0QrmxRNrON00JvaFFlNh5TTG00APw23j74ET7gkQpTASi6/L2fuiav8pzK715HXtUeClpBTw2NPSn6w==", + "license": "MIT" + }, + "node_modules/stringify-entities": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz", + "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==", + "license": "MIT", + "dependencies": { + "character-entities-html4": "^2.0.0", + "character-entities-legacy": "^3.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/style-to-js": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/style-to-js/-/style-to-js-1.1.21.tgz", + "integrity": "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ==", + "license": "MIT", + "dependencies": { + "style-to-object": "1.0.14" + } + }, + "node_modules/style-to-object": { + "version": "1.0.14", + "resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-1.0.14.tgz", + "integrity": "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw==", + "license": "MIT", + "dependencies": { + "inline-style-parser": "0.2.7" + } + }, + "node_modules/svgo": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/svgo/-/svgo-4.0.1.tgz", + "integrity": "sha512-XDpWUOPC6FEibaLzjfe0ucaV0YrOjYotGJO1WpF0Zd+n6ZGEQUsSugaoLq9QkEZtAfQIxT42UChcssDVPP3+/w==", + "license": "MIT", + "dependencies": { + "commander": "^11.1.0", + "css-select": "^5.1.0", + "css-tree": "^3.0.1", + "css-what": "^6.1.0", + "csso": "^5.0.5", + "picocolors": "^1.1.1", + "sax": "^1.5.0" + }, + "bin": { + "svgo": "bin/svgo.js" + }, + "engines": { + "node": ">=16" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/svgo" + } + }, + "node_modules/tiny-inflate": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz", + "integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==", + "license": "MIT" + }, + "node_modules/tinyclip": { + "version": "0.1.15", + "resolved": "https://registry.npmjs.org/tinyclip/-/tinyclip-0.1.15.tgz", + "integrity": "sha512-uo33abH+Ays0xYaDysoBt494Hb3hsEczMpcC0MwFl773pazORx4fmvKhclhR1wonUbB6vvpRsvVMwnhfqeMc+A==", + "license": "MIT", + "engines": { + "node": "^16.14.0 || >= 17.3.0" + } + }, + "node_modules/tinyexec": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.2.4.tgz", + "integrity": "sha512-SHf/r48b7vOrjve9PxJo3MN5v5yuyjHvdUcrQffT3WXMUfnGmHDVbC4k3sHJaJTgZCwpUplIaAo5ANtMyp3YHg==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/trim-lines": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz", + "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/trough": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/trough/-/trough-2.2.0.tgz", + "integrity": "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD", + "optional": true + }, + "node_modules/ufo": { + "version": "1.6.4", + "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.4.tgz", + "integrity": "sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==", + "license": "MIT" + }, + "node_modules/ultrahtml": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/ultrahtml/-/ultrahtml-1.6.0.tgz", + "integrity": "sha512-R9fBn90VTJrqqLDwyMph+HGne8eqY1iPfYhPzZrvKpIfwkWZbcYlfpsb8B9dTvBfpy1/hqAD7Wi8EKfP9e8zdw==", + "license": "MIT" + }, + "node_modules/uncrypto": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/uncrypto/-/uncrypto-0.1.3.tgz", + "integrity": "sha512-Ql87qFHB3s/De2ClA9e0gsnS6zXG27SkTiSJwjCc9MebbfapQfuPzumMIUMi38ezPZVNFcHI9sUIepeQfw8J8Q==", + "license": "MIT" + }, + "node_modules/undici-types": { + "version": "7.18.2", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz", + "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==", + "license": "MIT" + }, + "node_modules/unified": { + "version": "11.0.5", + "resolved": "https://registry.npmjs.org/unified/-/unified-11.0.5.tgz", + "integrity": "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "bail": "^2.0.0", + "devlop": "^1.0.0", + "extend": "^3.0.0", + "is-plain-obj": "^4.0.0", + "trough": "^2.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unifont": { + "version": "0.7.4", + "resolved": "https://registry.npmjs.org/unifont/-/unifont-0.7.4.tgz", + "integrity": "sha512-oHeis4/xl42HUIeHuNZRGEvxj5AaIKR+bHPNegRq5LV1gdc3jundpONbjglKpihmJf+dswygdMJn3eftGIMemg==", + "license": "MIT", + "dependencies": { + "css-tree": "^3.1.0", + "ofetch": "^1.5.1", + "ohash": "^2.0.11" + } + }, + "node_modules/unist-util-find-after": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/unist-util-find-after/-/unist-util-find-after-5.0.0.tgz", + "integrity": "sha512-amQa0Ep2m6hE2g72AugUItjbuM8X8cGQnFoHk0pGfrFeT9GZhzN5SW8nRsiGKK7Aif4CrACPENkA6P/Lw6fHGQ==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-is": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.1.tgz", + "integrity": "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-modify-children": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/unist-util-modify-children/-/unist-util-modify-children-4.0.0.tgz", + "integrity": "sha512-+tdN5fGNddvsQdIzUF3Xx82CU9sMM+fA0dLgR9vOmT0oPT2jH+P1nd5lSqfCfXAw+93NhcXNY2qqvTUtE4cQkw==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "array-iterate": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-position": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-5.0.0.tgz", + "integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-position-from-estree": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/unist-util-position-from-estree/-/unist-util-position-from-estree-2.0.0.tgz", + "integrity": "sha512-KaFVRjoqLyF6YXCbVLNad/eS4+OfPQQn2yOd7zF/h5T/CSL2v8NpN6a5TPvtbXthAGw5nG+PuTtq+DdIZr+cRQ==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-remove-position": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/unist-util-remove-position/-/unist-util-remove-position-5.0.0.tgz", + "integrity": "sha512-Hp5Kh3wLxv0PHj9m2yZhhLt58KzPtEYKQQ4yxfYFEO7EvHwzyDYnduhHnY1mDxoqr7VUwVuHXk9RXKIiYS1N8Q==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-visit": "^5.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-stringify-position": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz", + "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-visit": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.1.0.tgz", + "integrity": "sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0", + "unist-util-visit-parents": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-visit-children": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/unist-util-visit-children/-/unist-util-visit-children-3.0.0.tgz", + "integrity": "sha512-RgmdTfSBOg04sdPcpTSD1jzoNBjt9a80/ZCzp5cI9n1qPzLZWF9YdvWGN2zmTumP1HWhXKdUWexjy/Wy/lJ7tA==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-visit-parents": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz", + "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unstorage": { + "version": "1.17.5", + "resolved": "https://registry.npmjs.org/unstorage/-/unstorage-1.17.5.tgz", + "integrity": "sha512-0i3iqvRfx29hkNntHyQvJTpf5W9dQ9ZadSoRU8+xVlhVtT7jAX57fazYO9EHvcRCfBCyi5YRya7XCDOsbTgkPg==", + "license": "MIT", + "dependencies": { + "anymatch": "^3.1.3", + "chokidar": "^5.0.0", + "destr": "^2.0.5", + "h3": "^1.15.10", + "lru-cache": "^11.2.7", + "node-fetch-native": "^1.6.7", + "ofetch": "^1.5.1", + "ufo": "^1.6.3" + }, + "peerDependencies": { + "@azure/app-configuration": "^1.8.0", + "@azure/cosmos": "^4.2.0", + "@azure/data-tables": "^13.3.0", + "@azure/identity": "^4.6.0", + "@azure/keyvault-secrets": "^4.9.0", + "@azure/storage-blob": "^12.26.0", + "@capacitor/preferences": "^6 || ^7 || ^8", + "@deno/kv": ">=0.9.0", + "@netlify/blobs": "^6.5.0 || ^7.0.0 || ^8.1.0 || ^9.0.0 || ^10.0.0", + "@planetscale/database": "^1.19.0", + "@upstash/redis": "^1.34.3", + "@vercel/blob": ">=0.27.1", + "@vercel/functions": "^2.2.12 || ^3.0.0", + "@vercel/kv": "^1 || ^2 || ^3", + "aws4fetch": "^1.0.20", + "db0": ">=0.2.1", + "idb-keyval": "^6.2.1", + "ioredis": "^5.4.2", + "uploadthing": "^7.4.4" + }, + "peerDependenciesMeta": { + "@azure/app-configuration": { + "optional": true + }, + "@azure/cosmos": { + "optional": true + }, + "@azure/data-tables": { + "optional": true + }, + "@azure/identity": { + "optional": true + }, + "@azure/keyvault-secrets": { + "optional": true + }, + "@azure/storage-blob": { + "optional": true + }, + "@capacitor/preferences": { + "optional": true + }, + "@deno/kv": { + "optional": true + }, + "@netlify/blobs": { + "optional": true + }, + "@planetscale/database": { + "optional": true + }, + "@upstash/redis": { + "optional": true + }, + "@vercel/blob": { + "optional": true + }, + "@vercel/functions": { + "optional": true + }, + "@vercel/kv": { + "optional": true + }, + "aws4fetch": { + "optional": true + }, + "db0": { + "optional": true + }, + "idb-keyval": { + "optional": true + }, + "ioredis": { + "optional": true + }, + "uploadthing": { + "optional": true + } + } + }, + "node_modules/url-extras": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/url-extras/-/url-extras-0.1.0.tgz", + "integrity": "sha512-8tzwTeXFPuX/5PHuCDQE5Dd9Ts4rwoq2t9aIT+HS4iAVpmj5l4Ao7Q+BuuFjvWRqrLswBhQDk8O96ZicgCqQqw==", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/vfile": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz", + "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "vfile-message": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/vfile-location": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/vfile-location/-/vfile-location-5.0.3.tgz", + "integrity": "sha512-5yXvWDEgqeiYiBe1lbxYF7UMAIm/IcopxMHrMQDq3nvKcjPKIhZklUKL+AE7J7uApI4kwe2snsK+eI6UTj9EHg==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/vfile-message": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.3.tgz", + "integrity": "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-stringify-position": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/vite": { + "version": "8.1.3", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.1.3.tgz", + "integrity": "sha512-Ds+gBRbj0lwRO2Y5hwnUBdxSwlAve9LeRyU4sNnAr0ewW0gWF0n5bgXgUzbgZ49MV9BVUAQUFYVcDUcilUExMA==", + "license": "MIT", + "dependencies": { + "lightningcss": "^1.32.0", + "picomatch": "^4.0.4", + "postcss": "^8.5.16", + "rolldown": "~1.1.3", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.3.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vitefu": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/vitefu/-/vitefu-1.1.3.tgz", + "integrity": "sha512-ub4okH7Z5KLjb6hDyjqrGXqWtWvoYdU3IGm/NorpgHncKoLTCfRIbvlhBm7r0YstIaQRYlp4yEbFqDcKSzXSSg==", + "license": "MIT", + "workspaces": [ + "tests/deps/*", + "tests/projects/*", + "tests/projects/workspace/packages/*" + ], + "peerDependencies": { + "vite": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "vite": { + "optional": true + } + } + }, + "node_modules/web-namespaces": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/web-namespaces/-/web-namespaces-2.0.1.tgz", + "integrity": "sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ==", + "license": "MIT", + "funding": { + "type": "github", + "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": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/xxhash-wasm/-/xxhash-wasm-1.1.0.tgz", + "integrity": "sha512-147y/6YNh+tlp6nd/2pWq38i9h6mz/EuQ6njIrmW8D1BS5nCqs0P6DG+m6zTGnNz5I+uhZ0SHxBs9BsPrwcKDA==", + "license": "MIT" + }, + "node_modules/yargs-parser": { + "version": "22.0.0", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz", + "integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==", + "license": "ISC", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=23" + } + }, + "node_modules/yocto-queue": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-1.2.2.tgz", + "integrity": "sha512-4LCcse/U2MHZ63HAJVE+v71o7yOdIe4cZ70Wpf8D/IyjDKYQLV5GD46B+hSTjJsvV5PztjvHoU580EftxjDZFQ==", + "license": "MIT", + "engines": { + "node": ">=12.20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/zod": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz", + "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zwitch": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", + "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + } + } +} diff --git a/website/package.json b/website/package.json new file mode 100644 index 0000000..b7414c3 --- /dev/null +++ b/website/package.json @@ -0,0 +1,15 @@ +{ + "name": "green-tea-docs", + "type": "module", + "private": true, + "scripts": { + "dev": "astro dev", + "build": "astro build", + "preview": "astro preview" + }, + "dependencies": { + "@astrojs/starlight": "^0.41.3", + "astro": "^7.0.6", + "sharp": "^0.35.3" + } +} diff --git a/website/src/content.config.ts b/website/src/content.config.ts new file mode 100644 index 0000000..6a7b7a0 --- /dev/null +++ b/website/src/content.config.ts @@ -0,0 +1,7 @@ +import { defineCollection } from 'astro:content'; +import { docsLoader } from '@astrojs/starlight/loaders'; +import { docsSchema } from '@astrojs/starlight/schema'; + +export const collections = { + docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }), +}; diff --git a/website/src/content/docs/concepts/flow.md b/website/src/content/docs/concepts/flow.md new file mode 100644 index 0000000..5f1b466 --- /dev/null +++ b/website/src/content/docs/concepts/flow.md @@ -0,0 +1,24 @@ +--- +title: The typed flow core +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. + +```typescript +import { flow } from '@green-tea/core'; + +const pipeline = flow() + .step('db', () => ({ find: (id: string) => id })) + .step('user', (ctx) => ctx.db.find('u1')); // referencing a missing 'db' would not compile +``` + +Each `.step(name, fn)` adds its output to the accumulated context **type** (`Acc & Out`). The next step's `ctx` is typed with everything produced so far — so reading `ctx.db` compiles only because a previous step provided `db`. Reference a key nothing produced and it is a **compile error**, not a runtime `undefined`. + +This is the strongest guarantee green-tea offers: the type *is* the dependency contract, checked statically. The decorator layer gives you the same graph with boot-time validation and the ergonomics of classes and decorators; `flow` gives you compile-time proof. + +:::note +`npm run typecheck` in the repo includes a type-level test that asserts this accumulation behaves — a step that reads a missing key is expected to fail compilation. +::: + +See [The dependency graph](/concepts/the-graph/) for how both layers describe the same model. diff --git a/website/src/content/docs/concepts/the-graph.md b/website/src/content/docs/concepts/the-graph.md new file mode 100644 index 0000000..22c1bc7 --- /dev/null +++ b/website/src/content/docs/concepts/the-graph.md @@ -0,0 +1,47 @@ +--- +title: The dependency graph +description: "How green-tea models the request and boot pipeline as an explicit dependency graph." +--- + +Most frameworks make you keep the whole request in your head: which middleware ran, whether `req.user` exists by now, what order things fire in, which plugin quietly deleted your body parser. That bookkeeping is where bugs live. + +green-tea puts the request **on the page**. You declare what each unit **needs** and **produces**; the framework computes the order, checks the wiring, and can print the whole thing. + +## needs / provides + +Every node declares its inputs and outputs: + +- A **provider** produces an app-scope value (a database handle, a config object) — resolved once at boot and cached. +- A **step** reads the request context and merges new keys into it (authentication producing `user`, say) — runs per request. +- A **handler** (a route method) declares, through its argument decorators, exactly which keys it depends on. + +green-tea builds a directed graph from these declarations and **topologically sorts** it. You never write "put this before that" — order is derived from `needs`/`provides`. + +```typescript +@Step({ provides: 'user', needs: ['db', 'req'] }) // user depends on db and req +class Authenticate { /* ... */ } +``` + +## Why it matters + +- **No ordering bugs.** There's no positional `app.use()` sequence to get wrong; the sort is the order. +- **Each route runs only its slice.** A route runs the transitive closure of what its handler `@needs` (plus always-run observer steps) — an auth step doesn't run on a public route. +- **Boot fails loudly.** If a handler needs a key nothing provides, `createApp` throws at boot with a "did you mean…?" hint — you never serve `undefined`. +- **You can read it.** `app.explain(route)` prints the ordered chain with origins; `app.graph()` / `GET /__graph__` render it as a diagram. See [Graph introspection](/guides/introspection/). + +## Two layers + +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`. +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. + +Both describe the same graph; pick the ergonomics you want. + +## Why legacy decorators + +green-tea uses **legacy** (experimental) TypeScript decorators — set `experimentalDecorators: true` in your `tsconfig`. This is a design decision, not inertia. + +The argument-injection API (`@param`, `@query`, `@body`, `@header`, `@needs`, `@ctx`, `@inbound`, `@abort`) relies on **parameter decorators**, and the TC39 standard decorators proposal (Stage 3) deliberately does **not** include them. There is no standards-track way to decorate a parameter today, so `handler(@param('id') id: string)` is only expressible with legacy decorators. + +"Stage 3" also means *not finalized* — the proposal can still change before engines ship it. green-tea tracks it and will revisit if parameter injection ever gets a standard path. It does **not** rely on `emitDecoratorMetadata` / `design:type` reflection — argument positions are recorded explicitly — so this is the only legacy surface it depends on. diff --git a/website/src/content/docs/getting-started.md b/website/src/content/docs/getting-started.md new file mode 100644 index 0000000..70defac --- /dev/null +++ b/website/src/content/docs/getting-started.md @@ -0,0 +1,84 @@ +--- +title: Getting started +description: Install green-tea, configure TypeScript decorators, and build your first graph-based route. +--- + +## Install + +```bash +npm install @green-tea/core reflect-metadata +# optional, only if you use them: +npm install ws # WebSocket routes (@Ws) and mesh +npm install busboy # multipart/form-data file uploads +``` + +green-tea targets **Node ≥ 18** and uses **legacy** TypeScript decorators. Enable them in your `tsconfig.json`: + +```json +{ + "compilerOptions": { + "experimentalDecorators": true, + "target": "es2020", + "moduleResolution": "node" + } +} +``` + +You do **not** need `emitDecoratorMetadata` — green-tea records argument positions explicitly. See [Why legacy decorators](/concepts/the-graph/#why-legacy-decorators) for the rationale. + +## Your first app + +A provider produces a value, a step transforms the request context, and a controller handler declares exactly what it needs: + +```typescript +import { + createApp, Provider, Step, Route, Get, Module, + Unauthorized, needs, param, +} from '@green-tea/core'; + +@Provider({ provides: 'db' }) +class Database { + provide() { + const users = { u1: { id: 'u1', name: 'Diego' } }; + return { db: { find: (token: string) => users[token] ?? null } }; + } +} + +@Step({ provides: 'user', needs: ['db', 'req'] }) +class Authenticate { + run(ctx) { + const user = ctx.db.find(ctx.req.headers['x-token']); + if (!user) throw new Unauthorized('invalid token'); // cut the request + return { user }; // continue + } +} + +@Route('/users') +class UserController { + @Get('/:id') + getUser(@needs('user') user, @param('id') id) { // the signature IS the contract + return { requested: id, you: user }; + } +} + +@Module({ mountpoint: '/api', providers: [Database], steps: [Authenticate], controllers: [UserController] }) +class ApiModule {} + +const app = createApp({ modules: [ApiModule] }); +console.log(app.explain('/api/users/:id')); // auditable: the ordered chain, with origins +app.listen(3000); +``` + +```bash +curl -H 'x-token: u1' http://localhost:3000/api/users/9 +# {"requested":"9","you":{"id":"u1","name":"Diego"}} +``` + +The handler asked for `user` via `@needs('user')`. If nothing in the graph produced `user`, `createApp` would **throw at boot** with a "did you mean…" hint — you never serve `undefined`. + +## Where to next + +- [The dependency graph](/concepts/the-graph/) — the mental model behind everything. +- [Dependency injection](/guides/dependency-injection/) — providers, steps, and modules in depth. +- [Argument decorators](/guides/arguments/) — everything a handler can inject. +- [Streaming & real-time](/guides/streaming/) — SSE, WebSocket, and ndjson from one primitive. diff --git a/website/src/content/docs/guides/arguments.md b/website/src/content/docs/guides/arguments.md new file mode 100644 index 0000000..2ac8081 --- /dev/null +++ b/website/src/content/docs/guides/arguments.md @@ -0,0 +1,148 @@ +--- +title: Argument decorators +description: "Everything a handler can inject with needs, ctx, param, query, body, header, inbound, and abort." +--- + +A handler's signature declares exactly what it wants — in any order, nothing more. Each +parameter decorator injects one thing: a graph-produced value, part of the request envelope, +or a stream handle. Some decorators add a **dependency edge** to the graph (boot-validated); +most just read from the request. + +## The decorators at a glance + +| Decorator | Injects | Adds a graph dependency? | Forms | +|---|---|---|---| +| `@needs('user')` | a value produced by a provider/step (boot-validated) | **yes** | `('key')` | +| `@ctx()` | the whole accumulated context | no | `()` | +| `@param(...)` | route params | no | `()` · `('id')` · `('id', schema)` | +| `@query(...)` | parsed query string | no | `()` · `('q')` · `(['a','b'])` · `(schema)` | +| `@body(...)` | parsed body (JSON / urlencoded / multipart) | no | `()` · `('field')` · `(schema)` | +| `@headers(...)` | request headers (whole bag or picked) | no | `()` · `('authorization')` · `(['a','b'])` · `(schema)` | +| `@header('name')` | one request header (singular alias of `@headers`) | no | `('x-trace')` · `('x-count', schema)` | +| `@inbound()` | the incoming WS message channel | no (WS only) | `()` | +| `@abort()` | an `AbortSignal` that fires on disconnect | no (stream/WS) | `()` | + +## `@needs` — a graph-produced value + +`@needs('token')` injects a value a provider or step produces, and declares a dependency edge +in the graph. Its keys are **validated at boot**: if nothing provides the token, `createApp` +throws with a clear error instead of serving `undefined`. + +```typescript +getUser(@needs('user') user: any, @param('id') id: string) { + return { requested: id, you: user }; +} +``` + +See [Dependency injection](/guides/dependency-injection/) for how `needs`/`provides` build the +graph. + +## `@ctx` — the whole context + +`@ctx()` hands you the entire accumulated context — everything providers and steps have merged +in, plus built-ins. Use it to read values like `ctx.protocol` and `ctx.ip` (populated when +`trustProxy` is on). + +## Envelope decorators — `@param`, `@query`, `@body`, `@headers` + +These read from the parsed request. Each envelope decorator has **three access forms**: + +- `@query()` — the whole object +- `@query('q')` — one key +- `@query(['q','date'])` — a subset + +```typescript +@Get('/:id') +getUser(@param('id') id: string) { /* ... */ } +``` + +- **`@param`** reads route params. It always needs a name to say which param it binds + (`@param('id')`). +- **`@query`** reads the parsed query string. Query values are always strings on the wire — a + schema is often the coercion point (see below). +- **`@body`** reads the parsed body. It handles `application/json`, + `application/x-www-form-urlencoded`, and `multipart/form-data` (see the multipart note). +- **`@headers`** reads request headers — the whole bag (`@headers()`), one key + (`@headers('authorization')`), or a subset (`@headers(['a','b'])`). + +## `@header` — one header, singular alias + +`@header('name')` is the singular alias of `@headers`: it picks exactly one request header. + +```typescript +who(@header('x-trace') trace: string) { /* ... */ } +``` + +It also accepts a schema in slot 2 — `@header('x-count', schema)`. + +## Schema forms — validation & coercion + +`@body`, `@query`, `@headers`, and `@param` accept an optional **Standard Schema** (zod, +valibot, arktype, …). The value the handler receives is the schema's **parsed/coerced output**, +already typed: + +```typescript +create(@body(CreateUser) user: { email: string }) { + return { created: user.email }; +} +``` + +:::note[Access shape (asymmetry)] +`@param('id', Schema)` takes the **key in slot 1** and the schema in slot 2 — `@param` always +needs a name to say which route param it binds. `@body(Schema)`, `@query(Schema)`, and +`@headers(Schema)` take the schema as their **only** argument, validating the whole parsed +object. +::: + +A failing schema short-circuits the request with **422**. See [Validation](/guides/validation/) +for the full contract (fail-fast order, error shape, async schemas, and caveats). + +## Multipart access asymmetry + +A request with `Content-Type: multipart/form-data` makes `@body()` resolve to `{ fields, files }` +instead of a plain object. + +:::caution[Access note] +For multipart, `@body('title')` returns `undefined` — the value lives at `body.fields.title`, +not `body.title`, unlike JSON/urlencoded where `@body('title')` picks the value directly. Use +`@body()` and read `.fields` / `.files`, or key into the envelope itself with `@body('fields')` +/ `@body('files')`. +::: + +```typescript +upload(@body() form: MultipartBody) { + const name = form.fields.name; // string | string[] + const avatar = form.files.avatar; // UploadedFile | UploadedFile[] + return { name, size: Array.isArray(avatar) ? undefined : avatar?.size }; +} +``` + +## Stream decorators — `@inbound` and `@abort` + +These are for streaming handlers: + +- **`@inbound()`** (WS only) gives you the incoming WebSocket message channel — the client's + messages to consume. A `@Ws` handler returns the **outbound** channel. +- **`@abort()`** (stream / WS) hands you an `AbortSignal` that fires on disconnect, so you can + tear down work when the client goes away. + +```typescript +@Ws('/echo') +echo(@inbound() incoming: AsyncIterable) { + const out = channel(); + (async () => { + for await (const msg of incoming) out.push(`echo: ${msg}`); + out.close(); + })(); + return out; +} +``` + +See [Streaming](/guides/streaming/) for SSE, WebSocket duplex, and channels. + +## Where to go next + +- How injected values are produced: [Dependency injection](/guides/dependency-injection/). +- The mental model: [The graph](/concepts/the-graph/). +- Validating and coercing injected values: [Validation](/guides/validation/). +- The full API surface: [Decorator reference](/reference/decorators/). diff --git a/website/src/content/docs/guides/dependency-injection.md b/website/src/content/docs/guides/dependency-injection.md new file mode 100644 index 0000000..e785640 --- /dev/null +++ b/website/src/content/docs/guides/dependency-injection.md @@ -0,0 +1,146 @@ +--- +title: Dependency injection +description: "Providers, steps, and modules, and how values flow through the graph." +--- + +In green-tea the request pipeline is an explicit **dependency graph**. You declare what each +piece needs and produces; the framework computes the order, validates the wiring at boot, and +runs only the slice a route actually depends on. You never write "put this before that." + +There are three building blocks: + +- A **provider** is an app-scope singleton — constructed once, its value memoized for the + lifetime of the app. +- A **step** runs per request and transforms the context. +- A **module** sets a mountpoint and wires providers, steps, and controllers together. + +A handler's **argument decorators are its dependency declaration** — ask for what you want, in +any order. If you `@needs` a token nothing produces, you get a **boot error**, not an +`undefined` at runtime. + +## The full example + +```typescript +import 'reflect-metadata'; +import { createApp, Provider, Step, Route, Get, Module, Unauthorized, needs, param } from '@green-tea/core'; + +@Provider({ provides: 'db' }) +class Database { + provide() { return { db: { find: (id: string) => ({ id, name: 'Diego' }) } }; } +} + +@Step({ provides: 'user', needs: ['db', 'req'] }) +class Authenticate { + run(ctx: any) { + const user = ctx.db.find(ctx.req.headers['x-token']); + if (!user) throw new Unauthorized('bad token'); // throw = short-circuit the pipeline + return { user }; // return = continue, merge into ctx + } +} + +@Route('/users') +class UserController { + @Get('/:id') + getUser(@needs('user') user: any, @param('id') id: string) { + return { requested: id, you: user }; // auto-serialized as JSON + } +} + +@Module({ mountpoint: '/api', providers: [Database], steps: [Authenticate], controllers: [UserController] }) +class ApiModule {} + +const app = createApp({ modules: [ApiModule] }); +await app.listen(3000); +// GET /api/users/9 (header x-token) → { "requested": "9", "you": { "id": "...", "name": "Diego" } } + +await app.close(); // graceful shutdown: drains in-flight requests, closes streams + mesh links +``` + +## `@Provider` — app-scope, memoized + +A provider produces a value once, when the app boots, and reuses it for every request. Its +`provide()` method returns an object whose keys become tokens in the graph — here `db`. + +```typescript +@Provider({ provides: 'db' }) +class Database { + provide() { return { db: { find: (id: string) => ({ id, name: 'Diego' }) } }; } +} +``` + +Because it's app-scope, a provider is the right home for things you build once and share: +database clients, config, connection pools. + +:::note +An optional provider (`optional: true`) that throws on boot does **not** abort startup — it is +left unregistered and logged, and the failure surfaces at request time for routes that need it. +Query the degraded set with `app.degraded()` or listen for the `boot:provider:fail` bus event. +::: + +## `@Step` — request-scope, transforms the context + +A step runs once per request. Its `run(ctx)` receives the accumulated context and either: + +- **returns an object** → the pipeline continues and the object is merged into `ctx`, or +- **throws** → the request short-circuits (here `Unauthorized` becomes a `401`). + +```typescript +@Step({ provides: 'user', needs: ['db', 'req'] }) +class Authenticate { + run(ctx: any) { + const user = ctx.db.find(ctx.req.headers['x-token']); + if (!user) throw new Unauthorized('bad token'); // throw = short-circuit the pipeline + return { user }; // return = continue, merge into ctx + } +} +``` + +This step `provides: 'user'` and `needs: ['db', 'req']` — so green-tea knows the `db` provider +and the built-in `req` must resolve before it runs, and it topologically sorts accordingly. + +## How `needs` / `provides` build the graph + +Every node declares what it **produces** (`provides`) and what it **consumes** (`needs`). The +framework reads those declarations and computes a topological order — you never specify +ordering by hand. A handler's argument decorators extend the same graph: `@needs('user')` on a +parameter is a dependency edge exactly like a step's `needs`. + +Because the graph is explicit, **each route runs only the transitive closure of its handler's +`@needs`** — nothing else. + +:::caution[Per-route execution] +A route that doesn't `@needs('user')` does **not** run the `Authenticate` step. A cross-cutting +*enforcement* step (e.g. auth that throws `401`) only protects routes that actually `@needs` +its token. To run something on **every** route regardless of needs (logging, audit, a global +guard), add it as a **plugin step** via `scope.add({ ..., provides: [] })` — steps that produce +nothing run unconditionally. Don't rely on a token-providing step to guard routes that don't +declare it. +::: + +## `@Module` — mountpoint and wiring + +A module ties everything together: a `mountpoint` prefix for the routes, and the lists of +`providers`, `steps`, and `controllers` that belong to it. + +```typescript +@Module({ mountpoint: '/api', providers: [Database], steps: [Authenticate], controllers: [UserController] }) +class ApiModule {} +``` + +Pass modules to `createApp({ modules: [ApiModule] })` to assemble the app. + +## Boot validation of `@needs` + +The payoff of declaring dependencies is that the wiring is checked before a single request is +served. When you `@needs` a token, green-tea verifies some provider or step actually produces +it. If nothing does, **`createApp` throws with a clear error** instead of letting your handler +receive `undefined`. Boot fails loudly, so you never serve `undefined`. + +## Where to go next + +- New to green-tea? Start with [Getting started](/getting-started/). +- The mental model behind all of this: [The graph](/concepts/the-graph/). +- 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/). diff --git a/website/src/content/docs/guides/introspection.md b/website/src/content/docs/guides/introspection.md new file mode 100644 index 0000000..ebda170 --- /dev/null +++ b/website/src/content/docs/guides/introspection.md @@ -0,0 +1,55 @@ +--- +title: Graph introspection +description: "explain, graph, toMermaid, and the graph endpoint." +--- + +Because the request/boot pipeline is an explicit [dependency graph](/concepts/the-graph/), +you can inspect it directly — visualize the whole thing, or explain exactly which nodes a +single route runs. + +## Visualize with Mermaid + +`app.toMermaid()` renders a flowchart of every node and route. `app.toDOT()` produces the +same graph as Graphviz DOT. + +```typescript +console.log(app.toMermaid()); // flowchart diagram of all nodes and routes +``` + +Enable a live `GET /__graph__` endpoint — it renders an HTML viewer with Mermaid, or the +raw Mermaid source with `Accept: text/plain`: + +```typescript +const app = createApp({ modules: [ApiModule], devGraph: true }); +// GET /__graph__ → HTML viewer +// GET /__graph__ (text/plain) → raw Mermaid source +``` + +:::caution +`devGraph` exposes your graph structure over HTTP. Keep it on in development; leave it off +in production. +::: + +## Explain a route + +`app.explain(route)` returns the exact execution chain for one route — the ordered nodes, +each with its kind, origin, and declared `needs`/`provides`: + +```typescript +const e = app.explain('/api/users/:id'); +// { pattern, method, transport, chain: [{ name, kind, origin, needs, provides }, ...] } +console.log(e.chain.map((n) => `${n.kind}:${n.name}`)); +// → ['provider:db', 'step:user', 'handler:getUser'] +``` + +The chain is the transitive closure of the handler's `@needs` — the same set the framework +actually runs for that route, and nothing more. + +`app.graph()` returns the underlying graph structure programmatically if you'd rather walk +it yourself than render it. + +## Degraded optional providers + +`app.degraded()` returns the names of optional providers that are running in a **degraded** +state — for example, an optional dependency that failed to initialize but didn't abort boot. +Use it as a health signal to surface partial availability. diff --git a/website/src/content/docs/guides/mesh.md b/website/src/content/docs/guides/mesh.md new file mode 100644 index 0000000..fe9bfae --- /dev/null +++ b/website/src/content/docs/guides/mesh.md @@ -0,0 +1,67 @@ +--- +title: Mesh (alpha) +description: "Distributed dependency injection over a secret-gated WebSocket control channel." +--- + +:::caution[Alpha] +Mesh is **alpha** — its API and wire protocol may change between releases, and discovery, load-balancing, and failover are not built. It is gated behind an explicit opt-in: `createApp({ mesh, experimental: true })`, and `createApp` **throws** if you configure `mesh` without `experimental: true`. **Don't ship mesh to production yet.** +::: + +A **teacup** can depend on a token that physically lives on another node — a **teapot**. `@needs('billing')` resolves the same whether `billing` runs in this process or on a remote one. There's no gRPC layer or message-pattern DSL: there's the [graph](/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. + +## Node A — teapot (exposes `config`, `auth`, and a route) + +```typescript +@Provider({ provides: 'config', export: true }) +class Config { provide() { return { config: { region: 'mx', tier: 'pro' } }; } } + +@Step({ provides: 'auth', needs: [], export: true }) +class Auth { run(ctx: any) { return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; } } + +@Route('/svc') +class Svc { @Get('/ping', { export: true }) ping() { return { pong: true }; } } + +@Module({ mountpoint: '/api', providers: [Config], steps: [Auth], controllers: [Svc] }) +class TeapotModule {} + +const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'shh' } }); +await teapot.listen(3002); +``` + +## Node B — teacup (uses `config` + `auth` with no local providers) + +```typescript +@Route('/local') +class LocalCtl { + @Get('/who') + who(@needs('config') config: any, @needs('auth') auth: any) { + return { config, auth }; // both resolved by RPC to the teapot + } +} +@Module({ mountpoint: '/api', controllers: [LocalCtl] }) +class TeacupModule {} + +const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + mesh: { teapots: [{ url: 'ws://A-host:3002/__mesh__/control', secret: 'shh' }] }, +}); +await teacup.listen(3003); +// GET B:3003/api/local/who (x-token: abc) +// → { "config": { "region": "mx", "tier": "pro" }, "auth": { "token": "abc" } } +``` + +## How it resolves + +`@needs('config' | 'auth')` validates at boot because the teapot announced them in its **manifest** on connect. Scope determines the RPC cost: + +- A **provider** export is **app-scope** — resolved once and cached. +- A **step** export is **request-scope** — one RPC per request, carrying the request envelope. + +Remote tokens become synthetic nodes in the local graph with RPC-backed runners, so the rest of the pipeline is unchanged. For non-mesh apps `createApp` stays synchronous; mesh apps defer graph finalization to `listen()` so remote scopes can join first. + +:::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`. +::: diff --git a/website/src/content/docs/guides/plugins.md b/website/src/content/docs/guides/plugins.md new file mode 100644 index 0000000..f3b647a --- /dev/null +++ b/website/src/content/docs/guides/plugins.md @@ -0,0 +1,58 @@ +--- +title: Plugins & observability +description: "Extending the app safely via bus.on and scope.add." +--- + +A plugin is a function that receives the app's API at boot. It gets exactly two +capabilities: **observe** the running system through `bus.on(...)`, and **extend its own +scope** through `scope.add(...)`. That's the whole surface — and it's deliberately narrow. + +```typescript +const logger = (api: any) => { + api.bus.on('request:step:enter', (p: any) => console.log(`→ ${p.name}`)); + api.bus.on('stream:open', (p: any) => console.log(`stream open ${p.name}`)); + api.bus.on('mesh:rpc:error', (p: any) => console.error('mesh rpc failed', p.error)); +}; + +const app = createApp({ modules: [ApiModule], plugins: [logger] }); +``` + +## Isolation is structural + +A plugin can add steps and providers to **its own scope** via `scope.add(...)`. It +**cannot** reorder or delete another scope's steps. The graph — not a policy check — +enforces this: each scope owns its nodes, and a plugin has no handle on anyone else's. +There's no ordering hook to abuse and no step registry to mutate. If you want a plugin to +influence execution, it does so by contributing a node with declared `needs`/`provides`, +and the framework computes where that node lands. + +:::note +Because execution is per-route (a route runs only the transitive closure of its handler's +`@needs`), a plugin step that should run on **every** route must produce nothing — add it +with `provides: []`. A step that produces no token has nothing to gate on, so the framework +runs it unconditionally. See [The graph](/concepts/the-graph/) for how the closure is +computed. +::: + +## Lifecycle & request events + +Subscribe to events on the `Bus` to observe boot, per-request execution, streaming, and +mesh activity without touching the pipeline itself: + +```typescript +api.bus.on('boot:provider:ready', (p: any) => { /* ... */ }); +api.bus.on('request:step:enter', (p: any) => { /* ... */ }); +api.bus.on('request:step:exit', (p: any) => { /* ... */ }); +``` + +The full event vocabulary: + +- `boot:provider:*` — provider lifecycle during boot +- `request:step:*` — a step entering/exiting during a request +- `stream:open | stream:close | stream:error` — SSE/WS stream lifecycle +- `mesh:connect | mesh:disconnect | mesh:rpc:error` — mesh link and RPC activity +- `plugin:mounted` — a plugin finished mounting + +Observation is read-only: handlers see the event payload but can't alter control flow. To +change behavior, contribute a node to your scope — see +[Dependency injection](/guides/dependency-injection/). diff --git a/website/src/content/docs/guides/routing.md b/website/src/content/docs/guides/routing.md new file mode 100644 index 0000000..ea4145f --- /dev/null +++ b/website/src/content/docs/guides/routing.md @@ -0,0 +1,64 @@ +--- +title: Routing +description: "Route patterns, the catch-all, specificity precedence, and 405 handling." +--- + +Routes are declared with method decorators on a `@Route`-prefixed controller. Patterns are matched **by segment**. + +## Method decorators + +| Decorator | Method / transport | +|---|---| +| `@Get` `@Post` `@Put` `@Patch` `@Delete` | buffered HTTP response | +| `@Sse` | server-sent events (`text/event-stream`) | +| `@Ws` | WebSocket duplex | +| `@Stream` | negotiated — SSE / ndjson / WS, picked from the client's `Accept` / `Upgrade` | + +```typescript +@Route('/users') +class Users { + @Get('/:id') get(@param('id') id: string) { /* ... */ } + @Post('/') create(@body() data: unknown) { /* ... */ } +} +``` + +The path a route matches is `joinPath(module.mountpoint, route.path)` — a controller under `@Module({ mountpoint: '/api' })` with `@Route('/users')` + `@Get('/:id')` serves `/api/users/:id`. + +## Pattern segments + +- **Static** — `users` matches exactly. +- **`:param`** — matches exactly one segment; the decoded value lands in `params.name` (`@param('id')`). +- **`:name*` catch-all** — a trailing segment that captures the **rest of the path, slashes included**, into `params.name`. + +```typescript +@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 = ""`). + +## 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. + +```typescript +@Get('/a/b') // wins for /a/b +@Get('/a/:id') // wins for /a/x +@Get('/a/:rest*') // wins for /a/x/y +``` + +## 404 vs 405 + +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 +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 + +The matcher is intentionally small for beta. **Not built** (on the roadmap): + +- 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. diff --git a/website/src/content/docs/guides/security.md b/website/src/content/docs/guides/security.md new file mode 100644 index 0000000..a883a57 --- /dev/null +++ b/website/src/content/docs/guides/security.md @@ -0,0 +1,101 @@ +--- +title: Transport security +description: "TLS and wss, secure-by-default headers, CORS, and trustProxy." +--- + +Four `createApp` options cover TLS, proxying, CORS, and response headers: `tls`, +`trustProxy`, `cors`, and `security`. See the [`createApp` reference](/reference/createapp/) +for the full option list. + +## TLS (native https/wss) + +```typescript +import { readFileSync } from 'fs'; + +const app = createApp({ + modules: [App], + tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') }, +}); +``` + +When `tls` is set the server serves https, and WebSocket upgrades become wss on the same +port — no other changes. + +## `trustProxy` + +```typescript +const app = createApp({ modules: [App], trustProxy: true }); +``` + +Behind a reverse proxy, reads `X-Forwarded-Proto` / `X-Forwarded-For` to populate +`ctx.protocol` (`'http' | 'https'`) and `ctx.ip` (read via `@ctx()`). Off by default — +forwarded headers are ignored (and spoofable) until you opt in. It trusts the immediate hop +unconditionally; there's no CIDR allowlist yet. + +## CORS + +Off unless `origins` is set. + +```typescript +const app = createApp({ + modules: [App], + cors: { origins: 'https://app.example.com', credentials: true }, +}); +``` + +`origins` accepts `string | string[] | '*' | (origin) => boolean`. A preflight `OPTIONS` +request (with `Access-Control-Request-Method`) is auto-answered with 204. + +- With `credentials: true`, the server **never** sends `Access-Control-Allow-Origin: *` — it + echoes the concrete allowed origin (or blocks the request). + +:::caution[Reflect-any foot-gun] +`origins: '*'` together with `credentials: true` reflects *any* origin with credentials +attached. Only combine them if you truly intend an open credentialed API; prefer an explicit +allowlist. +::: + +## `security` (headers, ON by default) + +Applied to every HTTP response. Disable everything with `security: false`, or override +individual headers with an options object. + +| Header | Default | +|---|---| +| `X-Content-Type-Options` | `nosniff` | +| `X-Frame-Options` | `SAMEORIGIN` | +| `Referrer-Policy` | `no-referrer` | +| `X-DNS-Prefetch-Control` | `off` | +| `Strict-Transport-Security` | `max-age=15552000` (180d) — **only when the connection is secure** (native TLS, or `trustProxy` + `X-Forwarded-Proto: https`); no `includeSubDomains`/`preload` | +| `Content-Security-Policy` | not set — pass `security: { csp: "..." }` | + +```typescript +const app = createApp({ modules: [App], security: { csp: "default-src 'self'" } }); +``` + +:::note[Scope caveat] +`security` and `cors` headers apply to HTTP responses; they do **not** apply to the +WebSocket handshake (101/upgrade) response. +::: + +:::caution[TLS + trustProxy] +HSTS is emitted only when the connection is judged secure. With `trustProxy: true` that +judgement trusts the incoming `X-Forwarded-Proto` header — so a client that spoofs +`X-Forwarded-Proto: http` past a permissive proxy can make the server treat the request as +insecure and **suppress the HSTS header**. Only enable `trustProxy` behind a proxy that +strips and sets forwarded headers itself, and terminate TLS where you control that hop. +::: + +## Defaults + +| Option | Default | +|---|---| +| `tls` | off (plain http/ws) | +| `trustProxy` | off | +| `cors` | off (same-origin only) | +| `security` | ON (HSTS only when the connection is secure) | + +## Related + +- [`createApp` reference](/reference/createapp/) — every construction option +- [File uploads / multipart](/guides/uploads/) — request-body handling diff --git a/website/src/content/docs/guides/streaming.md b/website/src/content/docs/guides/streaming.md new file mode 100644 index 0000000..2f6e296 --- /dev/null +++ b/website/src/content/docs/guides/streaming.md @@ -0,0 +1,114 @@ +--- +title: Streaming & real-time +description: "SSE, ndjson, and WebSocket duplex from one AsyncIterable primitive." +--- + +Most stacks treat "push data over time" as a bolt-on: Express reaches for a `ws` or SSE library, Fastify for a plugin, NestJS for a separate **WebSocket Gateway** with its own adapter and decorators. That's a second mental model, a second error surface, glued to your HTTP app. + +green-tea has one model: an **`AsyncIterable`**. A handler that returns a sequence of values over time *is* a stream — the same shape you'd return from any function. You **declare the mode** with a decorator; the framework handles framing, backpressure, cleanup, and disconnects. + +## One primitive, four modes + +| Declare | Direction | Transport | Reach for it when | +|---|---|---|---| +| `@Sse` | server → client | `text/event-stream` | live updates to a browser (`EventSource`) | +| `@Ws` | duplex | WebSocket | chat, collaboration — anything two-way | +| `@Stream` | negotiated | SSE / ndjson / WS, picked from the client's `Accept` / `Upgrade` | one handler, the client chooses | +| *(plain return)* | server → client | SSE or ndjson by `Accept` | programmatic streaming over `fetch` | + +The primitive never changes — it's always an `AsyncIterable`. What changes is **direction and framing**, and you declare which. That's the difference between each iterable green-tea hands you: + +- **`@Sse` / plain return** — you return **one** iterable: the *outbound* stream. Each `yield` becomes an SSE event, or an ndjson line. +- **`@Ws` (duplex)** — **two** iterables. `@inbound()` gives you the client's *incoming* messages to consume; the one you **return** is the *outbound* stream to the client. `@abort()` hands you an `AbortSignal` for teardown. +- **`@Stream`** — you write the handler once; the client's request decides whether it arrives as SSE, ndjson, or a WebSocket. No branching in your code. + +:::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 — 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). + +## 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) { + const out = channel(); + (async () => { + for await (const msg of incoming) out.push(`echo: ${msg}`); + out.close(); + })(); + return out; + } +} +``` + +`channel()` is a multicast `AsyncIterable` with `push` / `close` / `fail` and an optional bounded buffer (`channel({ buffer: 100 })`, drop-oldest). + +:::note[WebSocket needs the `ws` peer] +`@Ws` (and mesh) require the optional [`ws`](https://github.com/websockets/ws) peer dependency — `npm i ws`. SSE, ndjson, and plain HTTP need nothing extra. +::: + +## Fan-out — `channel()` and `rooms` + +Fan-out is a primitive too: `channel()` is a **multicast** `AsyncIterable` (bounded, drop-oldest) so one source feeds many subscribers, and `rooms` are named broadcast hubs — publish once, every connection in the room receives it. + +```typescript +@Route('/live') +class Live { + @Sse('/prices') // one iterable out — each yield is an event + prices() { + return (async function* () { + while (true) { yield { btc: await getPrice() }; await sleep(1000); } + })(); + } + + @Ws('/echo') // duplex — consume @inbound, return the outbound stream + echo(@inbound() incoming: AsyncIterable) { + const out = channel(); + (async () => { for await (const m of incoming) out.push(`echo: ${m}`); out.close(); })(); + return out; + } +} +``` + +Same `@Route`, same handler shape, same `AsyncIterable` — real-time is not a separate framework you also have to learn. + +`rooms` is the built-in shared `Rooms` primitive (one instance app-wide). A typical chat handler pumps the `@inbound()` channel into `rooms.room(name)` and returns that same room as its outbound channel, so every joined socket multicasts to the others. A handshake `@Step` can read `?token=` and throw `Unauthorized` — which closes the socket with code **4401** (`4000 + status`). See [security](/guides/security/) for handshake authentication. + +## The one rule to remember + +``` +return a VALUE → buffered response (transformer → JSON) +return an AsyncIterable → stream (SSE / WS) +``` + +Return a value and you get a buffered JSON response; return an `AsyncIterable` and you get a stream. That's the whole contract. diff --git a/website/src/content/docs/guides/testing.md b/website/src/content/docs/guides/testing.md new file mode 100644 index 0000000..709e5aa --- /dev/null +++ b/website/src/content/docs/guides/testing.md @@ -0,0 +1,33 @@ +--- +title: Testing +description: "Swap any node with createApp overrides for fast, isolated tests." +--- + +Any provider or step is addressable by its **token**, so you can swap it for a test double +at construction time — no monkey-patching, no module rewiring. + +## Override tokens in tests + +Pass `overrides` to `createApp`. Each key is a token; each value is either a plain object +(wrapped as `{ token: value }`) or a function runner: + +```typescript +const app = createApp({ + modules: [ApiModule], + overrides: { + db: { find: () => ({ id: 'test-user' }) }, // plain object — wrapped as { db: value } + user: () => ({ user: { id: 'stub' } }), // function runner + }, +}); +``` + +Overrides replace **only** the named token's runner; the rest of the graph is untouched. The +route still runs its full closure — you've just substituted what one node produces. + +:::note +An override for an unknown token throws. The set of tokens is validated against the real +graph, so a typo'd or stale override is a construction-time error, not a silent no-op. +::: + +This pairs well with [`app.explain(route)`](/guides/introspection/) — explain the chain to +see which tokens a route actually depends on, then override exactly those. diff --git a/website/src/content/docs/guides/uploads.md b/website/src/content/docs/guides/uploads.md new file mode 100644 index 0000000..f5939f0 --- /dev/null +++ b/website/src/content/docs/guides/uploads.md @@ -0,0 +1,64 @@ +--- +title: File uploads +description: "multipart parsing via the optional busboy peer dependency." +--- + +A request with `Content-Type: multipart/form-data` makes `@body()` resolve to `{ fields, files }` instead of a plain object. + +:::caution[multipart needs the optional `busboy` peer] +Multipart parsing uses the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency — install it with `npm i busboy`. A `multipart/form-data` request to a server without busboy installed returns **`501`**. (JSON and urlencoded need nothing extra.) +::: + +```typescript +import { Route, Post, body } from '@green-tea/core'; +import type { MultipartBody } from '@green-tea/core'; + +@Route('/profile') +class ProfileController { + @Post('/avatar') + upload(@body() form: MultipartBody) { + const name = form.fields.name; // string | string[] + const avatar = form.files.avatar; // UploadedFile | UploadedFile[] + return { name, size: Array.isArray(avatar) ? undefined : avatar?.size }; + } +} +``` + +`UploadedFile` is `{ filename, contentType, data: Buffer, size }` — the whole file is buffered in memory, no temp files. + +:::note[Access asymmetry] +For multipart, `@body('title')` returns `undefined` — the value lives at `body.fields.title`, not `body.title`, unlike JSON/urlencoded where `@body('title')` picks the value directly. Use `@body()` and read `.fields`/`.files`, or key into the envelope itself with `@body('fields')` / `@body('files')`. See [arguments](/guides/arguments/) for how `@body()` behaves across content types. +::: + +## Repeated fields — `bodyDuplicates` + +By default, a repeated field name keeps the **last** value (`'last'`, matching urlencoded). Set `bodyDuplicates: 'array'` on `createApp` to accumulate repeats into a `string[]` instead — this applies to **both** urlencoded and multipart text fields: + +```typescript +const app = createApp({ modules: [ApiModule], bodyDuplicates: 'array' }); +``` + +Files under a repeated field name always become an array (`UploadedFile[]`), regardless of `bodyDuplicates`. + +## Per-endpoint override + +```typescript +@Post('/upload', { duplicates: 'array' }) +upload(@body() form: MultipartBody) { /* ... */ } +``` + +Precedence: route `duplicates` → app `bodyDuplicates` → `'last'`. + +## Limits + +Uploaded files are held in memory, so they're bounded by the same `maxBodyBytes` limit as any other request body (over the limit → **413**). `maxParts` (default `1000`) caps the number of multipart parts per request: + +```typescript +const app = createApp({ modules: [ApiModule], limits: { maxParts: 500 } }); +``` + +A malformed multipart body (bad boundary, missing headers, truncated part) → **400**. + +:::note +To validate parsed fields against a schema, pass a Standard Schema to `@body()` — see [validation](/guides/validation/). +::: diff --git a/website/src/content/docs/guides/validation.md b/website/src/content/docs/guides/validation.md new file mode 100644 index 0000000..1927e36 --- /dev/null +++ b/website/src/content/docs/guides/validation.md @@ -0,0 +1,84 @@ +--- +title: Validation +description: "Validate and coerce input with Standard Schema (zod, valibot, arktype)." +--- + +`@body`, `@query`, `@headers`, and `@param` accept an optional **Standard Schema** +(the [`~standard` interface](https://standardschema.dev) shared by zod, valibot, arktype, +and others). green-tea's core has **zero runtime dependency** on any of them — bring +whichever validator you already use. + +```typescript +import { z } from 'zod'; +import { Route, Post, body } from '@green-tea/core'; + +const CreateUser = z.object({ email: z.string().email() }); + +@Route('/users') +class UserController { + @Post('/') + create(@body(CreateUser) user: { email: string }) { + return { created: user.email }; + } +} +``` + +## Parsed value replaces the argument; `ctx` stays raw + +The value the handler receives is the schema's **parsed/coerced output**, not the raw +input — `ctx.body` (via `@ctx()` or a `@needs`-fed step) stays exactly what the transport +parsed. Query strings are always strings on the wire, so a schema is often the coercion +point: + +```typescript +const ListQuery = z.object({ page: z.coerce.number() }); + +@Get('/list') +list(@query(ListQuery) q: { page: number }) { + return { page: q.page, isNum: typeof q.page === 'number' }; // GET /list?page=2 → true +} +``` + +## Where the schema goes (the one asymmetry) + +:::note[Access shape] +`@param('id', Schema)` takes the key in slot 1 and the schema in slot 2 — `@param` always +needs a name to say which route param it binds. `@body(Schema)`, `@query(Schema)`, and +`@headers(Schema)` take the schema as their **only** argument, validating the whole parsed +object (all of `body`/`query`/`headers`). +::: + +See [Argument decorators](/guides/arguments/) for the full slot semantics of each decorator. + +## Failure: 422 with per-field issues + +A failing schema short-circuits the request with **422**: + +```json +{ "error": "Validation failed", "source": "body", "issues": [{ "path": "email", "message": "Invalid email" }] } +``` + +`source` is which envelope failed (`'body' | 'query' | 'params' | 'headers'`); `issues` is +the schema's issues flattened to `{ path, message }` (`path` is dot-joined). + +## Caveats + +- **Fail-fast.** Arguments validate in order; the **first** failing one throws — later args in + the same handler are not checked in that request. +- **Steps see raw input.** Only the resolved handler argument is coerced/validated; a `@Step` + reading the same data via `ctx.body`/`ctx.query`/etc. always sees the untouched value. +- **A throwing schema is a 500, not a 422.** The Standard Schema contract says `validate()` + returns `{ issues }` on failure — it isn't supposed to throw. If it does anyway, that + propagates as an uncaught error (→ 500), since it signals a bug in the schema, not user input. +- **Async schemas are awaited** — `validate()` returning a `Promise` works transparently. + +:::note[Not covered yet] +Response/output validation, validating a `@Step`'s own inputs, and mesh remote-route +validation are all out of scope for this feature. +::: + +## Related + +- [Argument decorators](/guides/arguments/) — every slot decorator and its parsing rules +- [File uploads / multipart](/guides/uploads/) — how multipart bodies are parsed before validation +- [`createApp` reference](/reference/createapp/) — app construction options diff --git a/website/src/content/docs/index.mdx b/website/src/content/docs/index.mdx new file mode 100644 index 0000000..e3be954 --- /dev/null +++ b/website/src/content/docs/index.mdx @@ -0,0 +1,41 @@ +--- +title: green-tea +description: A calm, type-safe HTTP framework for Node — your API is an explicit dependency graph you can see, slice, and trust. +template: splash +hero: + tagline: Your API is an explicit dependency graph you can see, slice, and trust — not a mutable bag threaded through positional middleware. + actions: + - text: Get started + link: /getting-started/ + icon: right-arrow + variant: primary + - text: The idea + link: /concepts/the-graph/ + icon: open-book + variant: minimal +--- + +import { Card, CardGrid } from '@astrojs/starlight/components'; + +## Less to hold in your head + +Most frameworks make you keep the whole request in your head: which middleware ran, whether `req.user` exists by now, what fired in what order. green-tea puts the request **on the page** — you declare what each step _needs_ and _produces_, and the framework computes the order, type-checks the wiring, and can print the whole thing. + + + + Declare `needs`/`provides`; green-tea topologically sorts it. No ordering bugs, no positional guesswork — each route runs only its slice of the graph. + + + In the typed `flow` core, a handler that reads `ctx.user` **fails to compile** if no step produces `user`. "It was undefined in prod" disappears at build time. + + + `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. + + + +:::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. +::: diff --git a/website/src/content/docs/reference/createapp.md b/website/src/content/docs/reference/createapp.md new file mode 100644 index 0000000..518f4ab --- /dev/null +++ b/website/src/content/docs/reference/createapp.md @@ -0,0 +1,70 @@ +--- +title: createApp options +description: "Every option accepted by createApp and every method on the App it returns." +--- + +```typescript +const app = createApp(options); +``` + +## Options + +| Option | Type | Default | Meaning | +|---|---|---|---| +| `modules` | `Ctor[]` | — | the `@Module` classes to wire (required) | +| `plugins` | `Plugin[]` | `[]` | plugins, each limited to `bus.on` + `scope.add` ([plugins](/guides/plugins/)) | +| `limits` | `RequestLimits` | see below | body-size and timeout ceilings | +| `devGraph` | `boolean` | `false` | mount `GET /__graph__` ([introspection](/guides/introspection/)) | +| `overrides` | `Record` | — | swap any node by token ([testing](/guides/testing/)) | +| `tls` | `TlsOptions` | — | serve over https/wss | +| `trustProxy` | `boolean` | `false` | honor `X-Forwarded-*` for `ctx.protocol` / `ctx.ip` | +| `security` | `boolean \| SecurityOptions` | `true` | secure-by-default headers ([security](/guides/security/)) | +| `cors` | `CorsOptions` | — | CORS handling | +| `bodyDuplicates` | `'array' \| 'last'` | `'last'` | policy for repeated form fields | +| `mesh` | `MeshConfig` | — | distributed DI — **requires `experimental: true`** ([mesh](/guides/mesh/)) | +| `experimental` | `boolean` | `false` | opt in to alpha features (currently gates `mesh`) | + +### `RequestLimits` + +| Field | Default | +|---|---| +| `maxBodyBytes` | `1_000_000` (→ `413` when exceeded) | +| `requestTimeoutMs` | `30_000` | +| `headersTimeoutMs` | `10_000` | +| `keepAliveTimeoutMs` | `5_000` | +| `maxParts` | `1000` (multipart) | + +### `TlsOptions` + +`{ key, cert, ca?, passphrase? }` — `key`/`cert` are `Buffer | string`. + +### `CorsOptions` + +`{ origins, methods?, allowedHeaders?, exposedHeaders?, credentials?, maxAge? }`. `origins` is a string, array, `'*'`, or a `(origin) => boolean` predicate. `credentials: true` is never combined with `'*'`. + +### `SecurityOptions` + +`{ hsts?, frameOptions?, referrerPolicy?, noSniff?, dnsPrefetchControl?, csp? }`. HSTS is only emitted on secure connections. `csp` is opt-in. + +### `MeshConfig` + +`{ secret?, teapots?, timeoutMs? }` — `teapots` is `{ url, secret }[]`. See [Mesh](/guides/mesh/). + +## The `App` + +`createApp` returns an `App`: + +| Member | Returns | Notes | +|---|---|---| +| `listen(port)` | `Promise` | boots providers, then serves | +| `close()` | `Promise` | drains in-flight, closes streams + mesh links | +| `inspect(route)` | `InspectLine[]` | the provider/step/handler chain for a route | +| `explain(route)` | `Explain` | the chain annotated with each node's needs/provides | +| `graph()` | `GraphView` | the full node + route graph | +| `toMermaid()` / `toDOT()` | `string` | render the graph | +| `degraded()` | `string[]` | optional providers running degraded (empty until `listen()`) | +| `bus` | `Bus` | lifecycle + request event bus | + +:::note +On mesh apps, `graph` / `explain` / `inspect` / `degraded` are only available **after** `listen()` — the graph is finalized once remote scopes connect. +::: diff --git a/website/src/content/docs/reference/decorators.md b/website/src/content/docs/reference/decorators.md new file mode 100644 index 0000000..5e26430 --- /dev/null +++ b/website/src/content/docs/reference/decorators.md @@ -0,0 +1,83 @@ +--- +title: Decorators +description: "Full reference for every class, method, and argument decorator." +--- + +Every decorator green-tea exports, grouped by where it applies. All require `experimentalDecorators: true` in your `tsconfig` — see [Why legacy decorators](/concepts/the-graph/#why-legacy-decorators). + +## Structure + +### `@Module(options)` + +Marks a class as a module and records what it wires together. + +```typescript +@Module({ + mountpoint: '/api', // path prefix for this module's controllers (required) + providers: [Database], // app-scope @Provider classes + steps: [Authenticate], // request-scope @Step classes + controllers: [UserCtl], // @Route classes +}) +class ApiModule {} +``` + +### `@Route(prefix)` + +Marks a class as a controller; `prefix` is prepended to each route path. + +## Providers & steps + +### `@Provider(options)` + +An app-scope value, built once at boot and cached, addressable by `provides`. + +| Option | Type | Default | Meaning | +|---|---|---|---| +| `provides` | `string` | — | the token this provider produces (required) | +| `needs` | `string[]` | `[]` | tokens it depends on | +| `optional` | `boolean` | `false` | if it throws on boot, degrade instead of aborting ([details](/guides/dependency-injection/)) | +| `export` | `boolean` | `false` | expose over the mesh control channel ([mesh](/guides/mesh/)) | + +### `@Step(options)` + +A request-scope transform that merges keys into the context. Same options as `@Provider`. + +### `@Transformer(fn)` + +Method decorator. Turns a handler's return value into `{ status?, headers?, body }`. `JsonTransformer` is the default. + +## Routes + +Method decorators on a controller. All accept `(path, opts?)` where `opts = { export?: boolean, duplicates?: 'array' | 'last' }`. + +| Decorator | Method | Transport | +|---|---|---| +| `@Get` `@Post` `@Put` `@Patch` `@Delete` | as named | buffered response | +| `@Sse` | GET | `text/event-stream` | +| `@Ws` | GET | WebSocket duplex | +| `@Stream` | GET | negotiated (SSE / ndjson / WS) | + +```typescript +@Get('/ping', { export: true }) // exportable over mesh +@Post('/upload', { duplicates: 'array' }) // repeated form fields → arrays +``` + +See [Routing](/guides/routing/) for pattern matching and [Streaming](/guides/streaming/) for the transports. + +## Arguments + +A handler's signature declares exactly what it wants, in any order. + +| Decorator | Injects | Forms | +|---|---|---| +| `@needs('user')` | a graph-produced value (boot-validated) | `('key')` | +| `@ctx()` | the whole accumulated context | `()` | +| `@param(...)` | route params | `()` · `('id')` · `('id', schema)` | +| `@query(...)` | parsed query string | `()` · `('q')` · `(['a','b'])` · `(schema)` | +| `@body(...)` | parsed body (JSON / urlencoded / multipart) | `()` · `('field')` · `(schema)` | +| `@headers(...)` | request headers (whole bag or picked) | `()` · `('authorization')` · `(['a','b'])` · `(schema)` | +| `@header('name')` | one request header (singular alias of `@headers`) | `('x-trace')` · `('x-count', schema)` | +| `@inbound()` | the incoming message stream (WebSocket) | `()` | +| `@abort()` | the request's `AbortSignal` | `()` | + +Passing a [Standard Schema](/guides/validation/) validates and coerces the value before the handler sees it. Full details in [Argument decorators](/guides/arguments/). diff --git a/website/tsconfig.json b/website/tsconfig.json new file mode 100644 index 0000000..8bf91d3 --- /dev/null +++ b/website/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "astro/tsconfigs/strict", + "include": [".astro/types.d.ts", "**/*"], + "exclude": ["dist"] +} From 7c20d74fe4bc432809c891c4b594077486aaad87 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Tue, 7 Jul 2026 16:04:20 -0500 Subject: [PATCH 077/139] chore(release): publish metadata + normalize version to 26.7.0-beta.0 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add the npm metadata needed to publish the scoped package — `publishConfig.access: "public"` (without it a scoped package publishes private), `engines`, `keywords`, `author` — and a CHANGELOG entry for the first beta. Normalize the version to 26.7.0-beta.0: npm treats versions as semver and strips the month's leading zero, so 26.07.0 publishes as 26.7.0 regardless. Align package.json, the VERSION export, the README, and the smoke test. Signed-off-by: Diego Resendez --- CHANGELOG.md | 38 +++++++++++++++++++++++++++++--------- README.md | 4 ++-- package.json | 21 ++++++++++++++++++++- src/index.ts | 2 +- test/smoke.test.ts | 2 +- 5 files changed, 53 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e4b63b3..71eafdd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,8 +7,12 @@ green-tea uses calendar versioning: `YY.MM.PATCH`. ## [Unreleased] -Beta on the road to a release candidate. No published release yet; the -version below is a placeholder until the API freeze. +_Nothing yet._ + +## [26.7.0-beta.0] - 2026-07-07 + +First public beta, published under the npm `beta` dist-tag. The API may still +change before the stable release. ### Added - **Transport security** — native TLS termination (https/wss), CORS with a @@ -19,10 +23,18 @@ version below is a placeholder until the API freeze. [Standard Schema](https://standardschema.dev) (zod / valibot / arktype); the parsed value is passed to the handler, invalid input returns `422` with per-field issues. Core stays dependency-free. -- **Body parsing** — JSON, `application/x-www-form-urlencoded`, and - `multipart/form-data` file uploads (`@body()` → `{ fields, files }`), with a - configurable repeated-field policy (`bodyDuplicates`, per-route overridable) - and a `maxParts` DoS bound. +- **Body parsing** — JSON and `application/x-www-form-urlencoded` out of the + box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via + the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency + (a multipart request without it returns `501`), with a configurable + repeated-field policy (`bodyDuplicates`, per-route overridable) and a + `maxParts` DoS bound. +- **Routing** — `:name*` catch-all params, specificity-based precedence + (static ▸ `:param` ▸ catch-all, independent of registration order), and + `405 Method Not Allowed` with an `Allow` header when a path exists under a + different method. +- **Argument decorators** — `@needs/@ctx/@param/@query/@body/@headers/@inbound/ + @abort`, plus `@header('name')` as a singular alias of `@headers`. - **Streams** — SSE / ndjson / WebSocket duplex over a multicast `AsyncIterable` channel, with backpressure and cleanup; `rooms` broadcast hubs. - **Graph introspection** — `app.explain(route)`, `app.graph()`, @@ -30,11 +42,19 @@ version below is a placeholder until the API freeze. - **Operational hardening** — request body/size limits (`413`), request and keep-alive timeouts, and `app.close()` graceful shutdown (drains in-flight requests, closes live streams and mesh links). +- **Visible degradation** — optional providers that fail at boot are + summarized on `listen()` and queryable via `app.degraded()`, instead of a + silent warning. - **Testing ergonomics** — `createApp({ overrides })` swaps any provider/step by token in one line. -- **Mesh (walking skeleton)** — `teapot`/`teacup` distributed dependency - injection over a secret-gated WebSocket control channel. Experimental. +- **Mesh (alpha, walking skeleton)** — `teapot`/`teacup` distributed dependency + injection over a secret-gated WebSocket control channel. Gated behind + `experimental: true`; `createApp` throws if `mesh` is configured without it. +- **Packaging** — dual **ESM + CommonJS** builds behind an `exports` map, with + matching type declarations; one runtime dependency (`reflect-metadata`), + `ws` and `busboy` optional peers. - **Benchmarks** — reproducible `npm run bench` harness vs Express 5, Fastify 5, NestJS, and raw `http`; results in [BENCHMARKS.md](./BENCHMARKS.md). -[Unreleased]: https://git.svc.zoit.services/Green-Tea/core/commits/develop +[Unreleased]: https://git.svc.zoit.services/Green-Tea/core/compare/26.7.0-beta.0...develop +[26.7.0-beta.0]: https://git.svc.zoit.services/Green-Tea/core/releases/tag/26.7.0-beta.0 diff --git a/README.md b/README.md index 307be60..8b17bf5 100644 --- a/README.md +++ b/README.md @@ -238,9 +238,9 @@ npm run bench # regenerate BENCHMARKS.md ## Versioning -green-tea uses **calendar versioning**: `YY.MM.PATCH` (e.g. `26.07.0` = the first release cut in July 2026, patch 0). 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.7.0` = the first release cut in July 2026, patch 0). The month is **not** zero-padded — npm treats versions as semver, which forbids leading zeros. A version tells you *when* it shipped, not how many breaking changes preceded it — those are always called out in the [CHANGELOG](./CHANGELOG.md). -**While in beta**, releases carry a `-beta.N` pre-release suffix on the calendar version (e.g. `26.07.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.7.0-beta.0`) and publish under the npm `beta` dist-tag — so a plain `npm install @green-tea/core` won't pick one up until the first stable calendar release. The API can still change between betas. ## License diff --git a/package.json b/package.json index 21565dc..93bc7c0 100644 --- a/package.json +++ b/package.json @@ -1,8 +1,27 @@ { "name": "@green-tea/core", - "version": "26.07.0-beta.0", + "version": "26.7.0-beta.0", "description": "Declarative, type-safe HTTP framework. The pipeline is a graph, not a middleware chain.", "license": "MIT", + "author": "green-tea contributors", + "keywords": [ + "http", + "framework", + "typescript", + "dependency-injection", + "decorators", + "dependency-graph", + "sse", + "websocket", + "streaming", + "node" + ], + "engines": { + "node": ">=18" + }, + "publishConfig": { + "access": "public" + }, "type": "commonjs", "main": "./dist/index.js", "module": "./dist/index.mjs", diff --git a/src/index.ts b/src/index.ts index 162f748..0faac48 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,7 +6,7 @@ import 'reflect-metadata'; /** Package version, replaced at publish time. */ -export const VERSION = '26.07.0-beta.0'; +export const VERSION = '26.7.0-beta.0'; // Application export { createApp } from './app'; diff --git a/test/smoke.test.ts b/test/smoke.test.ts index 4267eb2..d2c91ec 100644 --- a/test/smoke.test.ts +++ b/test/smoke.test.ts @@ -2,5 +2,5 @@ import { expect, test } from 'vitest'; import { VERSION } from '../src/index'; test('package loads and exposes a CalVer VERSION', () => { - expect(VERSION).toMatch(/^\d{2}\.\d{2}\.\d+(-beta\.\d+)?$/); + expect(VERSION).toMatch(/^\d{2}\.\d{1,2}\.\d+(-beta\.\d+)?$/); }); From 2db5de6858b71f32c237875320bb2fada18becd5 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 8 Jul 2026 08:29:17 -0500 Subject: [PATCH 078/139] feat: per-route body limits, custom error rendering, OpenAPI generation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three capabilities that share the same request/route metadata: - **Per-route upload limits** — `@Post('/x', { maxBodyBytes, maxParts })` overrides the server-wide `limits` for one route (falls back to the global default), mirroring the existing per-route `duplicates`. - **Custom error rendering** — `createApp({ onError })` takes over how any error becomes a response (HTML, RFC 7807, content-negotiated), covering the whole surface: handler/step throws, 404, 405, 413, 400. Returns a response or undefined to fall back to the default JSON. Also wires the previously-unused `HttpError` `body` field so `throw new HttpError(409, 'conflict', { code })` renders a structured payload. Default behavior is unchanged when no hook is set. - **OpenAPI 3.1** — `app.openapi(info?)` projects the route graph into a structural spec (paths, methods, path/query/header params, request-body presence, systematic error responses); opt-in `GET /__openapi__` via `devOpenapi`. Body/response schemas stay generic (Standard Schema exposes no JSON Schema) — the full `@Produce` mode is post-beta. Docs: new error-handling and OpenAPI guides, plus reference updates. Signed-off-by: Diego Resendez --- README.md | 3 +- src/app/index.ts | 47 ++- src/app/types.ts | 7 + src/http/server.ts | 51 +-- src/http/types.ts | 4 + src/index.ts | 3 + src/metadata.ts | 9 +- src/openapi.ts | 112 ++++++ src/pipeline.ts | 12 +- src/transformers.ts | 35 +- test/app.test.ts | 333 ++++++++++++++---- test/errors.test.ts | 82 +++++ test/openapi.test.ts | 83 +++++ website/astro.config.mjs | 2 + website/src/content/docs/guides/errors.md | 68 ++++ website/src/content/docs/guides/openapi.md | 41 +++ website/src/content/docs/guides/uploads.md | 9 +- .../src/content/docs/reference/createapp.md | 3 + .../src/content/docs/reference/decorators.md | 7 +- 19 files changed, 811 insertions(+), 100 deletions(-) create mode 100644 src/openapi.ts create mode 100644 test/errors.test.ts create mode 100644 test/openapi.test.ts create mode 100644 website/src/content/docs/guides/errors.md create mode 100644 website/src/content/docs/guides/openapi.md diff --git a/README.md b/README.md index 8b17bf5..beb348a 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ Less to hold in your head. That's the tea. - **The pipeline is a graph, not a chain.** You never write "put this before that." You declare `needs`/`provides` and green-tea topologically sorts it. *Why it matters:* no ordering bugs, no positional guesswork, and each route runs only its slice of the graph (an auth step doesn't run on public routes). - **The type is the contract.** What a handler reads from the context *is* its dependency list. In the typed `flow` core, a handler that reads `ctx.user` **fails to compile** if no step produces `user`. *Why it matters:* whole classes of "it was undefined in prod" disappear at compile time. -- **You can see the request before it runs.** `app.explain('/users/:id')` prints the ordered chain with origins; `app.graph()` / `GET /__graph__` render it as a live diagram. *Why it matters:* onboarding, debugging, and audits are reading, not archaeology. (NestJS puts this 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. - **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. @@ -81,6 +81,7 @@ Beta shipped the parts a real API needs, without growing the runtime dependency - **CORS** with a guarded preflight and the credentials-never-`*` rule enforced for you. - **Validation via [Standard Schema](https://standardschema.dev).** `@body(schema)` accepts zod, valibot, or arktype — you bring the validator, the core stays zero-dep. Invalid input → `422` with per-field issues; the parsed value reaches your handler typed. - **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS. +- **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response. - **Graceful shutdown.** `app.close()` drains in-flight requests, closes live streams and mesh links. - **Testable by construction.** `createApp({ overrides: { db: fakeDb } })` swaps any node in one line. - **Dual ESM + CommonJS.** Ships both builds behind an `exports` map — `import` and `require` both resolve, with matching type declarations. diff --git a/src/app/index.ts b/src/app/index.ts index 4073e14..076742d 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -6,10 +6,11 @@ import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz'; import { runPipeline, PipelineStep } from '../pipeline'; import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http'; import { isAsyncIterable } from '../channel'; -import { JsonTransformer } from '../transformers'; +import { JsonTransformer, type ErrorRenderer } from '../transformers'; import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin'; import { Ctor, getModuleMeta, getProviderMeta, getStepMeta, getRoutes, getTransformer, joinPath } from '../metadata'; import { getArgs, getHandlerNeeds, resolveArgs } from '../params'; +import { buildOpenApi, type OpenApiInfo } from '../openapi'; import { connectLink, type Link } from '../mesh/link'; import { Rooms } from '../rooms'; import type { TlsOptions, SecurityOptions, CorsOptions } from '../security'; @@ -42,6 +43,7 @@ interface PipelineDeps { providedSeed(plan: RoutePlan): Promise>; planSteps(plan: RoutePlan): PipelineStep[]; bus: Bus; + onError?: ErrorRenderer; } /** @@ -55,12 +57,15 @@ export function createApp(opts: { mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; + devOpenapi?: boolean; overrides?: Record; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions; cors?: CorsOptions; bodyDuplicates?: 'array' | 'last'; + /** Render errors your own way (HTML, custom JSON, …); return a response or undefined to fall back to JSON. */ + onError?: ErrorRenderer; /** Opt in to alpha features whose API may still change. Currently gates `mesh`. */ experimental?: boolean; }): App { @@ -100,12 +105,22 @@ export function createApp(opts: { const inspect = (routePath: string): InspectLine[] => inspectRoute(routePlans, routePath, booted); const graph = (): GraphView => buildGraphView(providerNodes, stepNodes, routePlans, booted); const explain = (routePath: string): Explain => explainRoute(routePlans, routePath, booted); + const openapi = (info?: OpenApiInfo) => + buildOpenApi( + routePlans.map((plan) => ({ + method: plan.method, + pattern: plan.pattern, + transport: plan.transport, + args: plan.args, + })), + info, + ); const providedSeed = (plan: RoutePlan) => seedProviders(container, plan); const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan); const listen = async (port: number): Promise => { - const deps: PipelineDeps = { providedSeed, planSteps, bus }; + const deps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError }; // mesh teacup: connect remote teapots, splice their scopes/routes into the graph, then finalize let remoteRoutes: RouteDef[] = []; @@ -137,6 +152,7 @@ export function createApp(opts: { const httpRoutes = buildHttpRoutes(routePlans, remoteRoutes, deps); if (opts.devGraph) httpRoutes.push(devGraphRoute(graph)); + if (opts.devOpenapi) httpRoutes.push(openApiRoute(openapi)); const wsRoutes = buildWsRoutes(routePlans, deps); server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { @@ -147,6 +163,7 @@ export function createApp(opts: { security: opts.security ?? true, cors: opts.cors, bodyDuplicates: opts.bodyDuplicates, + onError: opts.onError, }); server.on('close', () => closeLinks(meshLinks)); await new Promise((resolve) => server!.listen(port, resolve)); @@ -169,6 +186,7 @@ export function createApp(opts: { toMermaid: () => toMermaid(graph()), toDOT: () => toDOT(graph()), explain, + openapi, degraded: () => [...degradedProviders], bus, }; @@ -245,6 +263,9 @@ function collectControllers(controllers: Ctor[], mountpoint: string, origin: str run: async (context: any) => instance[route.handlerName](...(await resolveArgs(argSpecs, context))), transformer: getTransformer(ControllerClass, route.handlerName) ?? JsonTransformer, duplicates: route.duplicates, + maxBodyBytes: route.maxBodyBytes, + maxParts: route.maxParts, + args: argSpecs, }); } } @@ -447,7 +468,7 @@ function buildMeshControl( if (!mesh?.secret || !hasExports) return undefined; const { container, orderedProviders, orderedSteps } = deps; - const { bus, providedSeed, planSteps } = deps.deps; + const { bus, providedSeed, planSteps, onError } = deps.deps; const manifest = buildManifest({ providers: exportedProviders, steps: exportedSteps, routes: exportedRoutes }); const resolveScope = async (name: string, env: RequestEnvelope): Promise => { @@ -480,6 +501,7 @@ function buildMeshControl( handler: plan.run, transformer: plan.transformer, bus, + onError, seed: { ...provided, req: env, params: env.params, query: env.query, body: env.body, headers: env.headers }, }); @@ -497,7 +519,7 @@ function buildMeshControl( /** Compiles every non-ws route plan into an HTTP route that seeds and runs the pipeline, plus any remote routes. */ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps: PipelineDeps): RouteDef[] { - const { providedSeed, planSteps, bus } = deps; + const { providedSeed, planSteps, bus, onError } = deps; const local = routePlans .filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate @@ -506,6 +528,8 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps pattern: plan.pattern, transport: plan.transport, bodyDuplicates: plan.duplicates, + maxBodyBytes: plan.maxBodyBytes, + maxParts: plan.maxParts, handler: async (req) => { const provided = await providedSeed(plan); return runPipeline({ @@ -513,6 +537,7 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps handler: plan.run, transformer: plan.transformer, bus, + onError, seed: { ...provided, req, @@ -546,6 +571,20 @@ function devGraphRoute(graph: () => GraphView): RouteDef { }; } +/** The dev-only `/__openapi__` route: serves the structural OpenAPI 3.1 document as JSON. */ +function openApiRoute(openapi: () => unknown): RouteDef { + return { + method: 'GET', + pattern: '/__openapi__', + transport: 'buffer', + handler: async () => ({ + status: 200, + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(openapi()), + }), + }; +} + /** Compiles every ws/negotiate route plan into a WebSocket route that seeds context and runs its steps + handler. */ function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[] { const { providedSeed, planSteps } = deps; diff --git a/src/app/types.ts b/src/app/types.ts index 8876f44..12cbb4b 100644 --- a/src/app/types.ts +++ b/src/app/types.ts @@ -3,6 +3,8 @@ import type { Bus } from '../bus'; import type { GraphNode } from '../graph'; import type { GraphView } from '../graph-viz'; import type { HttpMethod, Transport } from '../metadata'; +import type { ArgSpec } from '../params'; +import type { OpenApiDoc, OpenApiInfo } from '../openapi'; import { JsonTransformer } from '../transformers'; /** One entry in an {@link App.inspect} listing: a provider, step or handler and where it came from. */ @@ -38,6 +40,8 @@ export interface App { toMermaid(): string; toDOT(): string; explain(routePath: string): Explain; + /** Generate a structural OpenAPI 3.1 document from the registered routes. */ + openapi(info?: OpenApiInfo): OpenApiDoc; /** Names of optional providers that failed to boot and are running degraded (empty until {@link App.listen}). */ degraded(): string[]; bus: Bus; @@ -56,6 +60,9 @@ export interface RoutePlan { run: (ctx: any) => Promise; transformer: typeof JsonTransformer; duplicates?: 'array' | 'last'; + maxBodyBytes?: number; + maxParts?: number; + args: ArgSpec[]; } /** Mesh networking options: a secret to gate this node's exports and/or remote teapots to connect to. */ diff --git a/src/http/server.ts b/src/http/server.ts index eb3a327..719d8ff 100644 --- a/src/http/server.ts +++ b/src/http/server.ts @@ -1,7 +1,7 @@ import http from 'http'; import https from 'https'; -import { errorToResponse } from '../transformers'; -import { isHttpError } from '../signals'; +import { renderError, type ErrorRequest, type ErrorRenderer } from '../transformers'; +import { isHttpError, HttpError, NotFound } from '../signals'; import { isStreamResult, type PipelineResult, type ResponseShape } from '../pipeline'; import type { Bus } from '../bus'; import { buildSecurityHeaders, mergeVary, resolveCors, corsPreflightHeaders } from '../security'; @@ -23,6 +23,24 @@ interface HandlerConfig { /** A ready-to-send error response produced while acquiring the request body. */ type BodyFailure = { fail: { status: number; headers: Record; body: string } }; +/** Builds the {@link ErrorRequest} handed to a user error renderer. */ +function errorRequest(req: http.IncomingMessage): ErrorRequest { + return { method: req.method ?? 'GET', url: req.url ?? '/', headers: req.headers }; +} + +/** Renders an error (through the optional user hook) and writes it, merging any extra headers (e.g. `Allow`). */ +function sendError( + res: http.ServerResponse, + error: unknown, + req: http.IncomingMessage, + onError?: ErrorRenderer, + extraHeaders?: Record, +): void { + const rendered = renderError(error, errorRequest(req), onError); + res.writeHead(rendered.status, extraHeaders ? { ...rendered.headers, ...extraHeaders } : rendered.headers); + res.end(rendered.body); +} + /** * Builds an HTTP/HTTPS server that routes requests, parses bodies, streams results, and handles WebSocket upgrades. * @param routes HTTP route definitions. @@ -83,13 +101,11 @@ function createRequestHandler(cfg: HandlerConfig) { const allow = allowedMethods(routes, path); if (allow.length) { - res.writeHead(405, { 'content-type': 'application/json', allow: allow.join(', ') }); - res.end(JSON.stringify({ error: 'Method Not Allowed' })); + sendError(res, new HttpError(405, 'Method Not Allowed'), req, opts?.onError, { allow: allow.join(', ') }); return; } - res.writeHead(404, { 'content-type': 'application/json' }); - res.end(JSON.stringify({ error: 'Not Found' })); + sendError(res, new NotFound('Not Found'), req, opts?.onError); return; } @@ -115,7 +131,7 @@ function createRequestHandler(cfg: HandlerConfig) { ip: deriveIp(req, trustProxy), }); } catch (error) { - result = errorToResponse(error); + result = renderError(error, errorRequest(req), opts?.onError); } if (isStreamResult(result)) { @@ -138,28 +154,23 @@ async function acquireBody( maxBody: number, ): Promise<{ body: unknown } | BodyFailure> { let buf: Buffer | undefined; + const bodyLimit = matched.def.maxBodyBytes ?? maxBody; // per-route override falls back to the server default try { - buf = await readBody(req, maxBody); + buf = await readBody(req, bodyLimit); } catch (error) { - const response = errorToResponse(error); - return { - fail: { status: response.status, headers: { ...response.headers, connection: 'close' }, body: response.body }, - }; + const rendered = renderError(error, errorRequest(req), opts?.onError); + return { fail: { ...rendered, headers: { ...rendered.headers, connection: 'close' } } }; } const contentType = String(req.headers['content-type'] ?? ''); const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last'; - const parsed = await parseRequestBody(buf, contentType, duplicates, opts?.limits?.maxParts ?? 1000); + const maxParts = matched.def.maxParts ?? opts?.limits?.maxParts ?? 1000; + const parsed = await parseRequestBody(buf, contentType, duplicates, maxParts); if ('error' in parsed) { - return { - fail: { - status: parsed.status ?? 400, - headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ error: parsed.error }), - }, - }; + const rendered = renderError(new HttpError(parsed.status ?? 400, parsed.error), errorRequest(req), opts?.onError); + return { fail: rendered }; } return { body: parsed.body }; diff --git a/src/http/types.ts b/src/http/types.ts index 2afa1a0..44cdcd3 100644 --- a/src/http/types.ts +++ b/src/http/types.ts @@ -1,6 +1,7 @@ import http from 'http'; import type { Transport } from '../metadata'; import type { PipelineResult } from '../pipeline'; +import type { ErrorRenderer } from '../transformers'; import type { TlsOptions, SecurityOptions, CorsOptions } from '../security'; /** Per-request size and timeout ceilings applied by the server. */ @@ -21,6 +22,7 @@ export interface HttpOptions { security?: boolean | SecurityOptions; cors?: CorsOptions; bodyDuplicates?: 'array' | 'last'; + onError?: ErrorRenderer; } /** Handler for a matched HTTP route; receives a normalized request and resolves to a pipeline result. */ @@ -42,6 +44,8 @@ export interface RouteDef { transport: Transport; handler: RouteHandler; bodyDuplicates?: 'array' | 'last'; + maxBodyBytes?: number; // per-route override of the server's maxBodyBytes + maxParts?: number; // per-route override of the server's multipart maxParts } /** Result of matching a request path against a route: extracted params plus the matched definition. */ diff --git a/src/index.ts b/src/index.ts index 0faac48..eb4c42a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -15,6 +15,8 @@ export type { App, InspectLine, Explain, MeshConfig } from './app'; // Graph visualization export { toMermaid, toDOT } from './graph-viz'; export type { GraphView } from './graph-viz'; +export { buildOpenApi } from './openapi'; +export type { OpenApiDoc, OpenApiInfo, OpenApiRoute } from './openapi'; // Routing & decorators export { Provider, Step, Route, Get, Module, Transformer, Sse, Ws, Stream, Post, Put, Patch, Delete } from './metadata'; @@ -23,6 +25,7 @@ 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'; // Bus & flow diff --git a/src/metadata.ts b/src/metadata.ts index 9d47050..2bcab34 100644 --- a/src/metadata.ts +++ b/src/metadata.ts @@ -31,6 +31,8 @@ export interface RouteMeta { transport: Transport; export: boolean; duplicates?: 'array' | 'last'; + maxBodyBytes?: number; + maxParts?: number; } /** Options accepted by the `@Module` decorator. */ export interface ModuleOptions { @@ -93,7 +95,10 @@ export function Route(prefix: string): ClassDecorator { } function routeDecorator(method: HttpMethod, transport: Transport) { - return (path: string, opts?: { export?: boolean; duplicates?: 'array' | 'last' }): MethodDecorator => + return ( + path: string, + opts?: { export?: boolean; duplicates?: 'array' | 'last'; maxBodyBytes?: number; maxParts?: number }, + ): MethodDecorator => (target, propertyKey) => { const ctor = target.constructor; const routes = (Reflect.getMetadata(K.routes, ctor) as RouteMeta[]) ?? []; @@ -104,6 +109,8 @@ function routeDecorator(method: HttpMethod, transport: Transport) { transport, export: opts?.export ?? false, duplicates: opts?.duplicates, + maxBodyBytes: opts?.maxBodyBytes, + maxParts: opts?.maxParts, }); Reflect.defineMetadata(K.routes, routes, ctor); }; diff --git a/src/openapi.ts b/src/openapi.ts new file mode 100644 index 0000000..7eba251 --- /dev/null +++ b/src/openapi.ts @@ -0,0 +1,112 @@ +import type { ArgSpec } from './params'; + +/** Minimal per-route input the OpenAPI projection needs, derived from a route plan. */ +export interface OpenApiRoute { + method: string; + pattern: string; + transport: string; + args: ArgSpec[]; +} + +/** `info` block overrides for the generated document. */ +export interface OpenApiInfo { + title?: string; + version?: string; + description?: string; +} + +/** A generated OpenAPI 3.1 document (structural: paths, params, and error responses; body/response schemas are generic). */ +export interface OpenApiDoc { + openapi: string; + info: { title: string; version: string; description?: string }; + paths: Record>; +} + +type Parameter = { name: string; in: 'path' | 'query' | 'header'; required: boolean; schema: { type: 'string' } }; + +/** Converts a route pattern to an OpenAPI path template: `/users/:id` → `/users/{id}`, `:rest*` → `{rest}`. */ +function templatePath(pattern: string): string { + const segments = pattern + .split('/') + .filter(Boolean) + .map((seg) => (seg.startsWith(':') ? `{${seg.slice(1).replace(/\*$/, '')}}` : seg)); + return `/${segments.join('/')}`; +} + +/** Every `:name` (and `:name*`) segment of a pattern becomes a required path parameter. */ +function pathParams(pattern: string): Parameter[] { + return pattern + .split('/') + .filter((seg) => seg.startsWith(':')) + .map((seg) => ({ name: seg.slice(1).replace(/\*$/, ''), in: 'path', required: true, schema: { type: 'string' } })); +} + +/** Query and header parameters declared by the handler's `@query` / `@headers` / `@header` argument decorators. */ +function argParams(args: ArgSpec[]): Parameter[] { + const params: Parameter[] = []; + + for (const arg of args) { + if (arg.source !== 'query' && arg.source !== 'headers') continue; + const location = arg.source === 'query' ? 'query' : 'header'; + const names = arg.keys ?? (arg.key ? [arg.key] : []); + for (const name of names) params.push({ name, in: location, required: false, schema: { type: 'string' } }); + } + + return params; +} + +/** The success/error responses documented for a route, keyed by transport and whether any input is validated. */ +function responses(route: OpenApiRoute): Record { + const result: Record = {}; + + if (route.transport === 'sse') { + result['200'] = { description: 'Event stream', content: { 'text/event-stream': {} } }; + } else if (route.transport === 'ndjson' || route.transport === 'negotiate') { + result['200'] = { description: 'Stream', content: { 'application/x-ndjson': {} } }; + } else { + result['200'] = { description: 'OK', content: { 'application/json': { schema: {} } } }; + } + + if (route.args.some((arg) => arg.schema)) result['422'] = { description: 'Validation failed' }; + result['500'] = { description: 'Internal Server Error' }; + return result; +} + +/** Builds a single OpenAPI operation object for a route. */ +function operation(route: OpenApiRoute): Record { + const parameters = [...pathParams(route.pattern), ...argParams(route.args)]; + const op: Record = { responses: responses(route) }; + + if (parameters.length) op.parameters = parameters; + + if (route.args.some((arg) => arg.source === 'body')) { + op.requestBody = { content: { 'application/json': { schema: {} } } }; + } + + return op; +} + +/** + * Projects the route graph into a structural OpenAPI 3.1 document: paths, methods, path/query/header + * parameters, which routes take a body, and the systematic error responses. Body and response *schemas* + * are generic — Standard Schema doesn't expose JSON Schema (see the roadmap). WebSocket routes are omitted. + */ +export function buildOpenApi(routes: OpenApiRoute[], info?: OpenApiInfo): OpenApiDoc { + const paths: Record> = {}; + + for (const route of routes) { + if (route.transport === 'ws') continue; // not an HTTP request/response + const path = templatePath(route.pattern); + (paths[path] ??= {})[route.method.toLowerCase()] = operation(route); + } + + return { + openapi: '3.1.0', + info: { + title: info?.title ?? 'green-tea API', + version: info?.version ?? '0.0.0', + ...(info?.description ? { description: info.description } : {}), + }, + paths, + }; +} diff --git a/src/pipeline.ts b/src/pipeline.ts index d2ec969..4810252 100644 --- a/src/pipeline.ts +++ b/src/pipeline.ts @@ -1,5 +1,5 @@ import { Bus } from './bus'; -import { errorToResponse } from './transformers'; +import { renderError, type ErrorRenderer } from './transformers'; import { isAsyncIterable } from './channel'; import type { TransformerFn } from './metadata'; @@ -38,8 +38,9 @@ export async function runPipeline(args: { transformer: TransformerFn; seed: Record; bus: Bus; + onError?: ErrorRenderer; }): Promise { - const { steps, handler, transformer, seed, bus } = args; + const { steps, handler, transformer, seed, bus, onError } = args; // context is intentionally `any`: each step merges arbitrary keys into the accumulator let context: any = { ...seed }; @@ -57,6 +58,11 @@ export async function runPipeline(args: { return { status: transformed.status ?? 200, headers: transformed.headers ?? {}, body: transformed.body }; } catch (error) { bus.emit('request:step:error', { name: 'pipeline', error }); - return errorToResponse(error); + const req = (context.req ?? {}) as { method?: string; url?: string; headers?: Record }; + return renderError( + error, + { method: req.method ?? '', url: req.url ?? '', headers: (context.headers ?? req.headers ?? {}) as never }, + onError, + ); } } diff --git a/src/transformers.ts b/src/transformers.ts index e7aaf5a..328783b 100644 --- a/src/transformers.ts +++ b/src/transformers.ts @@ -2,6 +2,26 @@ import { isHttpError, Redirect, ValidationError } from './signals'; import type { TransformerFn } from './metadata'; import { flattenPath } from './standard-schema'; +/** A ready-to-send HTTP response. */ +export interface ErrorResponse { + status: number; + headers: Record; + body: string; +} + +/** The request a {@link ErrorRenderer} is given, to inspect (e.g. `headers.accept`) while rendering. */ +export interface ErrorRequest { + method: string; + url: string; + headers: Record; +} + +/** + * User hook to render errors however you like (HTML, custom JSON, RFC 7807, …). + * Return a response to take over, or `undefined`/`void` to fall back to the default JSON. + */ +export type ErrorRenderer = (error: unknown, req: ErrorRequest) => ErrorResponse | undefined | void; + /** Default transformer: serialize a handler's return value as a JSON `200` response. */ export const JsonTransformer: TransformerFn = (value) => ({ status: 200, @@ -9,8 +29,11 @@ export const JsonTransformer: TransformerFn = (value) => ({ body: JSON.stringify(value), }); -/** Map a thrown value to a JSON error response (422 for validation, HttpError status, else 500). */ -export function errorToResponse(error: unknown): { status: number; headers: Record; body: string } { +/** + * Map a thrown value to a JSON error response (422 for validation, `HttpError` status, else 500). + * An `HttpError` carrying a `body` renders that payload instead of the default `{ error: message }`. + */ +export function errorToResponse(error: unknown): ErrorResponse { if (error instanceof ValidationError) { return { status: 422, @@ -26,7 +49,8 @@ export function errorToResponse(error: unknown): { status: number; headers: Reco if (isHttpError(error)) { const headers: Record = { 'content-type': 'application/json' }; if (error instanceof Redirect) headers.location = error.location; - return { status: error.status, headers, body: JSON.stringify({ error: error.message }) }; + const payload = error.body !== undefined ? error.body : { error: error.message }; + return { status: error.status, headers, body: JSON.stringify(payload) }; } return { @@ -35,3 +59,8 @@ export function errorToResponse(error: unknown): { status: number; headers: Reco body: JSON.stringify({ error: 'Internal Server Error' }), }; } + +/** Render an error through the optional user {@link ErrorRenderer}, falling back to {@link errorToResponse}. */ +export function renderError(error: unknown, req: ErrorRequest, onError?: ErrorRenderer): ErrorResponse { + return onError?.(error, req) ?? errorToResponse(error); +} diff --git a/test/app.test.ts b/test/app.test.ts index 616c996..dcea67f 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -1,13 +1,17 @@ import 'reflect-metadata'; import { describe, expect, it, test, vi } from 'vitest'; -import { Provider, Step, Route, Get, Module, Transformer } from '../src/metadata'; +import { Provider, Step, Route, Get, Post, Module, Transformer } from '../src/metadata'; import { JsonTransformer } from '../src/transformers'; import { Unauthorized } from '../src/signals'; import { createApp } from '../src/app'; -import { needs, param, query } from '../src/params'; +import { needs, param, query, body } from '../src/params'; @Provider({ provides: 'db' }) -class Db { provide() { return { db: { find: (t: string) => (t === 'good' ? { id: 'u1' } : null) } }; } } +class Db { + provide() { + return { db: { find: (t: string) => (t === 'good' ? { id: 'u1' } : null) } }; + } +} @Step({ provides: 'user', needs: ['db', 'req'] }) class Auth { @@ -22,7 +26,9 @@ class Auth { class UserCtl { @Get('/:id') @Transformer(JsonTransformer) - getUser(@needs('user') user: any, @param('id') id: string) { return { id, user }; } + getUser(@needs('user') user: any, @param('id') id: string) { + return { id, user }; + } } @Module({ mountpoint: '/api', providers: [Db], steps: [Auth], controllers: [UserCtl] }) @@ -54,7 +60,11 @@ test('a logger plugin observes step:enter without mutating the chain', async () test('required provider failure aborts boot', () => { @Provider({ provides: 'broken' }) - class Broken { provide() { throw new Error('cannot connect'); } } + class Broken { + provide() { + throw new Error('cannot connect'); + } + } @Module({ mountpoint: '/x', providers: [Broken], steps: [], controllers: [] }) class BrokenModule {} @@ -65,15 +75,23 @@ test('required provider failure aborts boot', () => { test('optional provider failure warns but does not abort boot', async () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); @Provider({ provides: 'cache', optional: true }) - class FlakyCache { provide() { throw new Error('cache down'); } } + class FlakyCache { + provide() { + throw new Error('cache down'); + } + } @Route('/ping') - class PingCtl { @Get('/') ping() { return { ok: true }; } } + class PingCtl { + @Get('/') ping() { + return { ok: true }; + } + } @Module({ mountpoint: '/sys', providers: [FlakyCache], steps: [], controllers: [PingCtl] }) class SysModule {} const app = createApp({ modules: [SysModule] }); expect(app.degraded()).toEqual([]); // nothing degraded until boot runs - const server = await app.listen(0); // must NOT throw + const server = await app.listen(0); // must NOT throw expect(warn).toHaveBeenCalledWith(expect.stringContaining("optional provider 'cache' failed")); // boot ends with a summary of everything running degraded, and it is queryable on the app expect(warn).toHaveBeenCalledWith(expect.stringContaining('started with 1 degraded optional provider(s): cache')); @@ -86,7 +104,9 @@ test('handler receives @query value through a live request', async () => { @Route('/search') class SearchCtl { @Get('/') - run(@query('q') q: string) { return { q }; } + run(@query('q') q: string) { + return { q }; + } } @Module({ mountpoint: '/s', providers: [], steps: [], controllers: [SearchCtl] }) class SearchModule {} @@ -103,19 +123,31 @@ test('boot fails when a handler needs something nothing provides', () => { @Route('/things') class ThingCtl { @Get('/') - list(@needs('missing') _m: any) { return []; } + list(@needs('missing') _m: any) { + return []; + } } @Module({ mountpoint: '/t', providers: [], steps: [], controllers: [ThingCtl] }) class ThingModule {} - expect(() => createApp({ modules: [ThingModule] })) - .toThrow(/handler 'list' needs 'missing'/); + expect(() => createApp({ modules: [ThingModule] })).toThrow(/handler 'list' needs 'missing'/); }); it('boot error for a misspelled @needs suggests the closest token', () => { - @Step({ provides: 'user', needs: [] }) class Auth { run() { return { user: 1 }; } } - @Route('/u') class Ctl { @Get('/x') x(@needs('usr') u: any) { return { u }; } } - @Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] }) class M {} + @Step({ provides: 'user', needs: [] }) + class Auth { + run() { + return { user: 1 }; + } + } + @Route('/u') + class Ctl { + @Get('/x') x(@needs('usr') u: any) { + return { u }; + } + } + @Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] }) + class M {} expect(() => createApp({ modules: [M] })).toThrow(/did you mean 'user'\?/); }); @@ -128,10 +160,14 @@ describe('app streaming wiring', () => { @Route('/') class Ctl { @Sse('/ticks') ticks() { - return (async function* () { yield { t: 1 }; yield { t: 2 }; })(); + return (async function* () { + yield { t: 1 }; + yield { t: 2 }; + })(); } } - @Module({ mountpoint: '/', controllers: [Ctl] }) class M {} + @Module({ mountpoint: '/', controllers: [Ctl] }) + class M {} const app = createApp({ modules: [M] }); const server = await app.listen(0); const addr = server.address() as import('net').AddressInfo; @@ -147,11 +183,15 @@ describe('app streaming wiring', () => { class Ctl { @Ws('/echo') echo(@inbound() inc: AsyncIterable) { const out = channel(); - (async () => { for await (const m of inc) out.push(`re:${m}`); out.close(); })(); + (async () => { + for await (const m of inc) out.push(`re:${m}`); + out.close(); + })(); return out; } } - @Module({ mountpoint: '/', controllers: [Ctl] }) class M {} + @Module({ mountpoint: '/', controllers: [Ctl] }) + class M {} const app = createApp({ modules: [M] }); const server = await app.listen(0); const addr = server.address() as import('net').AddressInfo; @@ -161,7 +201,8 @@ describe('app streaming wiring', () => { const got = new Promise((r) => client.on('message', (d: Buffer) => r(d.toString()))); client.send('yo'); expect(await got).toBe('re:yo'); - client.close(); server.close(); + client.close(); + server.close(); }); }); @@ -169,53 +210,97 @@ describe('per-route subgraph slicing', () => { it('a route that does not @needs a step does not run it', async () => { const ran: string[] = []; @Step({ provides: 'tracked', needs: [] }) - class Tracked { run() { ran.push('tracked'); return { tracked: true }; } } + class Tracked { + run() { + ran.push('tracked'); + return { tracked: true }; + } + } @Route('/') class Ctl { - @Get('/needs') needs(@needs('tracked') t: any) { return { t }; } - @Get('/free') free() { return { ok: true }; } + @Get('/needs') needs(@needs('tracked') t: any) { + return { t }; + } + @Get('/free') free() { + return { ok: true }; + } } - @Module({ mountpoint: '/', steps: [Tracked], controllers: [Ctl] }) class M {} + @Module({ mountpoint: '/', steps: [Tracked], controllers: [Ctl] }) + class M {} const app = createApp({ modules: [M] }); const server = await app.listen(0); const port = (server.address() as any).port; await fetch(`http://127.0.0.1:${port}/free`).then((r) => r.json()); - expect(ran).toEqual([]); // step did NOT run for /free + expect(ran).toEqual([]); // step did NOT run for /free await fetch(`http://127.0.0.1:${port}/needs`).then((r) => r.json()); - expect(ran).toEqual(['tracked']); // step ran for /needs - expect(app.inspect('/free').map((l) => l.kind)).toEqual(['handler']); // no step in the chain + expect(ran).toEqual(['tracked']); // step ran for /needs + expect(app.inspect('/free').map((l) => l.kind)).toEqual(['handler']); // no step in the chain server.close(); }); it('a side-effect step (provides: []) added by a plugin runs unconditionally', async () => { // NB: @Step always provides exactly one token (always sliceable). provides:[] only arises via a plugin's scope.add. const ran: string[] = []; - const observer = (api: any) => api.scope.add({ kind: 'step', name: 'obs', needs: [], provides: [], run: () => { ran.push('obs'); return {}; } }); + const observer = (api: any) => + api.scope.add({ + kind: 'step', + name: 'obs', + needs: [], + provides: [], + run: () => { + ran.push('obs'); + return {}; + }, + }); @Route('/') - class Ctl { @Get('/free') free() { return { ok: true }; } } - @Module({ mountpoint: '/', controllers: [Ctl] }) class M {} + class Ctl { + @Get('/free') free() { + return { ok: true }; + } + } + @Module({ mountpoint: '/', controllers: [Ctl] }) + class M {} const app = createApp({ modules: [M], plugins: [observer] }); const server = await app.listen(0); const port = (server.address() as any).port; await fetch(`http://127.0.0.1:${port}/free`).then((r) => r.json()); - expect(ran).toEqual(['obs']); // ran despite the route @needs-ing nothing + expect(ran).toEqual(['obs']); // ran despite the route @needs-ing nothing server.close(); }); it('an always-run observer step receives its declared needs even when the route does not need them', async () => { let seen: any; - const observer = (api: any) => api.scope.add({ kind: 'step', name: 'audit', needs: ['user'], provides: [], run: (ctx: any) => { seen = ctx.user; return {}; } }); + const observer = (api: any) => + api.scope.add({ + kind: 'step', + name: 'audit', + needs: ['user'], + provides: [], + run: (ctx: any) => { + seen = ctx.user; + return {}; + }, + }); @Step({ provides: 'user', needs: [] }) - class Auth { run() { return { user: { id: 'u1' } }; } } + class Auth { + run() { + return { user: { id: 'u1' } }; + } + } @Route('/') - class Ctl { @Get('/free') free() { return { ok: true }; } } // does NOT @needs('user') - @Module({ mountpoint: '/', steps: [Auth], controllers: [Ctl] }) class M {} + class Ctl { + @Get('/free') free() { + return { ok: true }; + } + } // does NOT @needs('user') + @Module({ mountpoint: '/', steps: [Auth], controllers: [Ctl] }) + class M {} const app = createApp({ modules: [M], plugins: [observer] }); const server = await app.listen(0); const port = (server.address() as any).port; await fetch(`http://127.0.0.1:${port}/free`).then((r) => r.json()); - expect(seen).toEqual({ id: 'u1' }); // observer got user, not undefined + expect(seen).toEqual({ id: 'u1' }); // observer got user, not undefined server.close(); }); }); @@ -225,10 +310,26 @@ import { toMermaid as renderMermaid } from '../src/graph-viz'; describe('app.graph / explain', () => { it('graph() returns nodes (with origin/needs/provides) and routes with their sliced chain', async () => { - @Provider({ provides: 'db' }) class Db { provide() { return { db: 1 }; } } - @Step({ provides: 'user', needs: ['db'] }) class Auth { run() { return { user: 1 }; } } - @Route('/u') class Ctl { @Get('/:id') get(@needs('user') u: any) { return { u }; } } - @Module({ mountpoint: '/api', providers: [Db], steps: [Auth], controllers: [Ctl] }) class M {} + @Provider({ provides: 'db' }) + class Db { + provide() { + return { db: 1 }; + } + } + @Step({ provides: 'user', needs: ['db'] }) + class Auth { + run() { + return { user: 1 }; + } + } + @Route('/u') + class Ctl { + @Get('/:id') get(@needs('user') u: any) { + return { u }; + } + } + @Module({ mountpoint: '/api', providers: [Db], steps: [Auth], controllers: [Ctl] }) + class M {} const app = createApp({ modules: [M] }); const g = app.graph(); expect(g.nodes.find((n) => n.name === 'db')).toMatchObject({ kind: 'provider', origin: 'module:M' }); @@ -239,9 +340,20 @@ describe('app.graph / explain', () => { }); it('explain() returns the rich chain with origin and a handler entry', async () => { - @Step({ provides: 'user', needs: [] }) class Auth { run() { return { user: 1 }; } } - @Route('/u') class Ctl { @Get('/me') me(@needs('user') u: any) { return { u }; } } - @Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] }) class M {} + @Step({ provides: 'user', needs: [] }) + class Auth { + run() { + return { user: 1 }; + } + } + @Route('/u') + class Ctl { + @Get('/me') me(@needs('user') u: any) { + return { u }; + } + } + @Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] }) + class M {} const app = createApp({ modules: [M] }); const e = app.explain('/api/u/me'); expect(e).toMatchObject({ pattern: '/api/u/me', method: 'GET', transport: 'buffer' }); @@ -253,8 +365,14 @@ describe('app.graph / explain', () => { describe('devGraph endpoint', () => { const portOf = (s: any) => (s.address() as any).port; it('serves /__graph__ as HTML when devGraph:true', async () => { - @Route('/u') class Ctl { @Get('/me') me() { return { ok: 1 }; } } - @Module({ mountpoint: '/api', controllers: [Ctl] }) class M {} + @Route('/u') + class Ctl { + @Get('/me') me() { + return { ok: 1 }; + } + } + @Module({ mountpoint: '/api', controllers: [Ctl] }) + class M {} const app = createApp({ modules: [M], devGraph: true }); const s = await app.listen(0); const html = await fetch(`http://127.0.0.1:${portOf(s)}/__graph__`).then((r) => r.text()); @@ -266,8 +384,14 @@ describe('devGraph endpoint', () => { s.close(); }); it('does NOT mount /__graph__ without devGraph', async () => { - @Route('/u') class Ctl { @Get('/me') me() { return { ok: 1 }; } } - @Module({ mountpoint: '/api', controllers: [Ctl] }) class M {} + @Route('/u') + class Ctl { + @Get('/me') me() { + return { ok: 1 }; + } + } + @Module({ mountpoint: '/api', controllers: [Ctl] }) + class M {} const app = createApp({ modules: [M] }); const s = await app.listen(0); const res = await fetch(`http://127.0.0.1:${portOf(s)}/__graph__`); @@ -279,17 +403,26 @@ describe('devGraph endpoint', () => { describe('graceful shutdown', () => { it('app.close() stops accepting and resolves, even with an SSE stream open', async () => { @Route('/') - class Ctl { @Sse('/ticks') ticks() { return (async function* () { yield { t: 1 }; await new Promise((r) => setTimeout(r, 1000)); yield { t: 2 }; })(); } } - @Module({ mountpoint: '/', controllers: [Ctl] }) class M {} + class Ctl { + @Sse('/ticks') ticks() { + return (async function* () { + yield { t: 1 }; + await new Promise((r) => setTimeout(r, 1000)); + yield { t: 2 }; + })(); + } + } + @Module({ mountpoint: '/', controllers: [Ctl] }) + class M {} const app = createApp({ modules: [M] }); const server = await app.listen(0); const port = (server.address() as any).port; const res = await fetch(`http://127.0.0.1:${port}/ticks`, { headers: { accept: 'text/event-stream' } }); const reader = res.body!.getReader(); - await reader.read(); // first event; stream still open + await reader.read(); // first event; stream still open - await app.close(); // must NOT hang despite the open stream + await app.close(); // must NOT hang despite the open stream await expect(fetch(`http://127.0.0.1:${port}/ticks`).then((r) => r.text())).rejects.toThrow(); reader.cancel().catch(() => {}); }); @@ -298,26 +431,54 @@ describe('graceful shutdown', () => { describe('overrides', () => { const portOf = (s: any) => (s.address() as any).port; it('overrides a provider token with a plain value (wrapped as a merge object)', async () => { - @Provider({ provides: 'db' }) class Db { provide() { return { db: { real: true } }; } } - @Route('/u') class Ctl { @Get('/x') x(@needs('db') db: any) { return { db }; } } - @Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] }) class M {} + @Provider({ provides: 'db' }) + class Db { + provide() { + return { db: { real: true } }; + } + } + @Route('/u') + class Ctl { + @Get('/x') x(@needs('db') db: any) { + return { db }; + } + } + @Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] }) + class M {} const app = createApp({ modules: [M], overrides: { db: { fake: true } } }); const s = await app.listen(0); expect(await fetch(`http://127.0.0.1:${portOf(s)}/api/u/x`).then((r) => r.json())).toEqual({ db: { fake: true } }); s.close(); }); it('overrides with a function runner', async () => { - @Provider({ provides: 'db' }) class Db { provide() { return { db: 'real' }; } } - @Route('/u') class Ctl { @Get('/x') x(@needs('db') db: any) { return { db }; } } - @Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] }) class M {} + @Provider({ provides: 'db' }) + class Db { + provide() { + return { db: 'real' }; + } + } + @Route('/u') + class Ctl { + @Get('/x') x(@needs('db') db: any) { + return { db }; + } + } + @Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] }) + class M {} const app = createApp({ modules: [M], overrides: { db: () => ({ db: 'fn' }) } }); const s = await app.listen(0); expect(await fetch(`http://127.0.0.1:${portOf(s)}/api/u/x`).then((r) => r.json())).toEqual({ db: 'fn' }); s.close(); }); it('rejects an override for an unknown token', async () => { - @Route('/u') class Ctl { @Get('/x') x() { return { ok: 1 }; } } - @Module({ mountpoint: '/api', controllers: [Ctl] }) class M {} + @Route('/u') + class Ctl { + @Get('/x') x() { + return { ok: 1 }; + } + } + @Module({ mountpoint: '/api', controllers: [Ctl] }) + class M {} const app = createApp({ modules: [M], overrides: { nope: 1 } }); await expect(app.listen(0)).rejects.toThrow(/unknown token 'nope'/); }); @@ -325,8 +486,14 @@ describe('overrides', () => { describe('rooms auto-provide', () => { it('injects a built-in rooms instance resolvable via @needs("rooms")', async () => { - @Route('/r') class Ctl { @Get('/x') x(@needs('rooms') rooms: Rooms) { return { ok: rooms instanceof Rooms }; } } - @Module({ mountpoint: '/api', controllers: [Ctl] }) class M {} + @Route('/r') + class Ctl { + @Get('/x') x(@needs('rooms') rooms: Rooms) { + return { ok: rooms instanceof Rooms }; + } + } + @Module({ mountpoint: '/api', controllers: [Ctl] }) + class M {} const app = createApp({ modules: [M] }); const s = await app.listen(0); const port = (s.address() as any).port; @@ -334,9 +501,47 @@ describe('rooms auto-provide', () => { s.close(); }); it('a user-declared rooms provider wins (no duplicate-name throw)', () => { - @Provider({ provides: 'rooms' }) class MyRooms { provide() { return { rooms: { custom: true } }; } } - @Route('/r') class Ctl { @Get('/x') x(@needs('rooms') rooms: any) { return rooms; } } - @Module({ mountpoint: '/api', providers: [MyRooms], controllers: [Ctl] }) class M {} + @Provider({ provides: 'rooms' }) + class MyRooms { + provide() { + return { rooms: { custom: true } }; + } + } + @Route('/r') + class Ctl { + @Get('/x') x(@needs('rooms') rooms: any) { + return rooms; + } + } + @Module({ mountpoint: '/api', providers: [MyRooms], controllers: [Ctl] }) + class M {} expect(() => createApp({ modules: [M] })).not.toThrow(); }); }); + +test('per-route maxBodyBytes overrides the server default', async () => { + @Route('/up') + class C { + @Post('/small', { maxBodyBytes: 10 }) small(@body() _b: unknown) { + return { ok: true }; + } + @Post('/big') big(@body() _b: unknown) { + return { ok: true }; + } + } + @Module({ mountpoint: '/', providers: [], steps: [], controllers: [C] }) + class M {} + + const app = createApp({ modules: [M], limits: { maxBodyBytes: 1000 } }); + const server = await app.listen(0); + const port = (server.address() as any).port; + const payload = JSON.stringify({ x: 'aaaaaaaaaaaaaaaaaaaa' }); // ~30 bytes, over the route's 10-byte cap + const opts = { method: 'POST', headers: { 'content-type': 'application/json' }, body: payload }; + + const tight = await fetch(`http://127.0.0.1:${port}/up/small`, opts); + expect(tight.status).toBe(413); // per-route cap of 10 bytes + const loose = await fetch(`http://127.0.0.1:${port}/up/big`, opts); + expect(loose.status).toBe(200); // falls back to the server's 1000-byte limit + + server.close(); +}); diff --git a/test/errors.test.ts b/test/errors.test.ts new file mode 100644 index 0000000..6245a10 --- /dev/null +++ b/test/errors.test.ts @@ -0,0 +1,82 @@ +import 'reflect-metadata'; +import { describe, it, expect } from 'vitest'; +import { createApp } from '../src/app'; +import { Route, Get, Module } from '../src/metadata'; +import { HttpError, Unauthorized, isHttpError } from '../src/signals'; +import type { ErrorRenderer } from '../src/transformers'; + +// Renders every error as HTML, reading the status off HttpError when present. +const htmlErrors: ErrorRenderer = (error) => ({ + status: isHttpError(error) ? error.status : 500, + headers: { 'content-type': 'text/html' }, + body: `

${isHttpError(error) ? error.status : 500}

`, +}); + +@Route('/x') +class Ctl { + @Get('/boom') boom() { + throw new Unauthorized('nope'); + } + @Get('/ok') ok() { + return { ok: true }; + } + @Get('/teapot') teapot() { + throw new HttpError(418, 'short and stout', { code: 'TEA', reason: 'short and stout' }); + } +} +@Module({ mountpoint: '/', controllers: [Ctl] }) +class M {} + +async function serve(onError?: ErrorRenderer) { + const app = createApp({ modules: [M], onError }); + const server = await app.listen(0); + const port = (server.address() as any).port; + return { server, base: `http://127.0.0.1:${port}` }; +} + +describe('onError renderer', () => { + it('renders a handler-thrown error through the hook (HTML, right status)', async () => { + const { server, base } = await serve(htmlErrors); + const res = await fetch(`${base}/x/boom`); + expect(res.status).toBe(401); + expect(res.headers.get('content-type')).toBe('text/html'); + expect(await res.text()).toBe('

401

'); + server.close(); + }); + + it('renders infra errors too — a no-route 404 goes through the hook', async () => { + const { server, base } = await serve(htmlErrors); + const res = await fetch(`${base}/nope`); + expect(res.status).toBe(404); + expect(res.headers.get('content-type')).toBe('text/html'); + expect(await res.text()).toBe('

404

'); + server.close(); + }); + + it('falls back to the default JSON when the hook returns undefined', async () => { + const { server, base } = await serve(() => undefined); + const res = await fetch(`${base}/x/boom`); + expect(res.status).toBe(401); + expect(res.headers.get('content-type')).toBe('application/json'); + expect(await res.json()).toEqual({ error: 'nope' }); + server.close(); + }); + + it('with no hook, behavior is unchanged (default JSON 404)', async () => { + const { server, base } = await serve(); + const res = await fetch(`${base}/nope`); + expect(res.status).toBe(404); + expect(await res.json()).toEqual({ error: 'Not Found' }); + server.close(); + }); +}); + +describe('HttpError body', () => { + it('an HttpError carrying a body renders that payload instead of { error: message }', async () => { + const { server, base } = await serve(); + const res = await fetch(`${base}/x/teapot`); + expect(res.status).toBe(418); + expect(await res.json()).toEqual({ code: 'TEA', reason: 'short and stout' }); + server.close(); + }); +}); diff --git a/test/openapi.test.ts b/test/openapi.test.ts new file mode 100644 index 0000000..94f04ed --- /dev/null +++ b/test/openapi.test.ts @@ -0,0 +1,83 @@ +import 'reflect-metadata'; +import { describe, it, expect } from 'vitest'; +import { createApp } from '../src/app'; +import { Route, Get, Post, Ws, Module } from '../src/metadata'; +import { param, query, headers, body } from '../src/params'; + +const numSchema = { + '~standard': { + version: 1 as const, + vendor: 'test', + validate: (v: unknown) => ({ value: Number(v) }), + }, +}; + +@Route('/users') +class Users { + @Get('/:id') get(@param('id') _id: string, @query('expand') _e: string, @headers('x-trace') _t: string) { + return {}; + } + @Post('/') create(@body() _b: unknown) { + return {}; + } + @Get('/:id/files/:path*') files(@param('path') _p: string) { + return {}; + } + @Get('/search') search(@query('n', numSchema) _n: number) { + return {}; + } + @Ws('/live') live() { + return (async function* () {})(); + } +} +@Module({ mountpoint: '/api', controllers: [Users] }) +class M {} + +describe('app.openapi()', () => { + const doc = createApp({ modules: [M] }).openapi({ title: 'Demo', version: '1.2.3' }); + + it('emits a 3.1 doc with info overrides', () => { + expect(doc.openapi).toBe('3.1.0'); + expect(doc.info).toEqual({ title: 'Demo', version: '1.2.3' }); + }); + + it('templates path params: /users/:id → /users/{id}', () => { + expect(doc.paths['/api/users/{id}']).toBeDefined(); + expect(doc.paths['/api/users/{id}/files/{path}']).toBeDefined(); + }); + + it('derives path, query, and header parameters from the handler signature', () => { + const op = doc.paths['/api/users/{id}'].get as any; + const byName = Object.fromEntries(op.parameters.map((p: any) => [p.name, p.in])); + expect(byName).toEqual({ id: 'path', expand: 'query', 'x-trace': 'header' }); + }); + + it('marks routes that take a body with requestBody', () => { + const op = doc.paths['/api/users'].post as any; + expect(op.requestBody.content['application/json']).toBeDefined(); + }); + + it('adds a 422 response when an argument is validated by a schema', () => { + const op = doc.paths['/api/users/search'].get as any; + expect(op.responses['422']).toBeDefined(); + expect((doc.paths['/api/users/{id}'].get as any).responses['422']).toBeUndefined(); + }); + + it('omits WebSocket routes', () => { + expect(doc.paths['/api/users/live']).toBeUndefined(); + }); +}); + +describe('GET /__openapi__', () => { + it('serves the document as JSON when devOpenapi is enabled', async () => { + const app = createApp({ modules: [M], devOpenapi: true }); + const server = await app.listen(0); + const port = (server.address() as any).port; + const res = await fetch(`http://127.0.0.1:${port}/__openapi__`); + expect(res.headers.get('content-type')).toBe('application/json'); + const json = (await res.json()) as any; + expect(json.openapi).toBe('3.1.0'); + expect(json.paths['/api/users/{id}']).toBeDefined(); + server.close(); + }); +}); diff --git a/website/astro.config.mjs b/website/astro.config.mjs index ad5f45a..a331056 100644 --- a/website/astro.config.mjs +++ b/website/astro.config.mjs @@ -31,11 +31,13 @@ export default defineConfig({ { label: 'Dependency injection', slug: 'guides/dependency-injection' }, { label: 'Argument decorators', slug: 'guides/arguments' }, { label: 'Validation', slug: 'guides/validation' }, + { label: 'Error handling', slug: 'guides/errors' }, { label: 'Streaming & real-time', slug: 'guides/streaming' }, { label: 'File uploads', slug: 'guides/uploads' }, { label: 'Transport security', slug: 'guides/security' }, { label: 'Plugins & observability', slug: 'guides/plugins' }, { label: 'Graph introspection', slug: 'guides/introspection' }, + { label: 'OpenAPI', slug: 'guides/openapi' }, { label: 'Testing', slug: 'guides/testing' }, { label: 'Mesh (alpha)', slug: 'guides/mesh', badge: { text: 'alpha', variant: 'caution' } }, ], diff --git a/website/src/content/docs/guides/errors.md b/website/src/content/docs/guides/errors.md new file mode 100644 index 0000000..d239606 --- /dev/null +++ b/website/src/content/docs/guides/errors.md @@ -0,0 +1,68 @@ +--- +title: Error handling +description: "Throw typed errors anywhere; render them however you like with onError." +--- + +Errors are **thrown, not returned**. Throw a typed error anywhere in the pipeline — a provider, a step, or a handler — and green-tea converts it to a response at one place. + +## The typed errors + +All live in `@green-tea/core`: + +| Throw | Status | +|---|---| +| `Unauthorized(msg?)` | `401` | +| `NotFound(msg?)` | `404` | +| `NotModified()` | `304` | +| `Redirect(location)` | `302` + `Location` | +| `ValidationError` | `422` (raised for you by schema validation) | +| `HttpError(status, msg?, body?)` | any status | +| anything else | `500` (message hidden — internals never leak) | + +```typescript +@Step({ provides: 'user', needs: ['db', 'req'] }) +class Authenticate { + run(ctx) { + const user = ctx.db.find(ctx.req.headers['x-token']); + if (!user) throw new Unauthorized('invalid token'); // → 401, cuts the request + return { user }; + } +} +``` + +By default an error becomes JSON: `{ "error": "" }` (validation adds `source` + per-field `issues`). + +## Structured error bodies + +An `HttpError` can carry a **body** — return a structured payload instead of the default `{ error }`: + +```typescript +throw new HttpError(409, 'conflict', { code: 'DUP_EMAIL', field: 'email' }); +// → 409 { "code": "DUP_EMAIL", "field": "email" } +``` + +## Render errors your way — `onError` + +Not everything should be JSON. Pass `onError` to `createApp` to render errors however you like — HTML, [RFC 7807](https://www.rfc-editor.org/rfc/rfc7807), content-negotiated, anything. It receives the error and the request, and returns a response — or `undefined` to fall back to the default JSON. + +```typescript +import { isHttpError } from '@green-tea/core'; + +const app = createApp({ + modules: [ApiModule], + onError(error, req) { + const status = isHttpError(error) ? error.status : 500; + // negotiate: HTML for browsers, JSON for API clients + if (String(req.headers.accept).includes('text/html')) { + return { status, headers: { 'content-type': 'text/html' }, body: `

${status}

` }; + } + return undefined; // fall back to the default JSON + }, +}); +``` + +`onError` intercepts **every** HTTP error response — handler/step throws, a `404` for an unmatched route, `405`, a `413` (body too large), and a `400` (malformed body) — 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). + +:::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. +::: diff --git a/website/src/content/docs/guides/openapi.md b/website/src/content/docs/guides/openapi.md new file mode 100644 index 0000000..cabb51c --- /dev/null +++ b/website/src/content/docs/guides/openapi.md @@ -0,0 +1,41 @@ +--- +title: OpenAPI +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**. + +## `app.openapi()` + +```typescript +const app = createApp({ modules: [ApiModule] }); +const spec = app.openapi({ title: 'My API', version: '1.0.0' }); +// → OpenAPI 3.1 document +``` + +It reads the routes and handler signatures and produces, for each route: + +- the **path**, templated — `/users/:id` → `/users/{id}`, catch-all `:path*` → `{path}`; +- the **method**; +- **parameters** — path params from the pattern, plus query/header params from the handler's `@query` / `@headers` / `@header` decorators; +- a **request body** entry for routes that read `@body()`; +- the systematic **responses** — `200`, a `422` when any argument is schema-validated, and `500`. + +WebSocket routes are omitted (they aren't request/response). + +## Serve it — `devOpenapi` + +Opt in to a `GET /__openapi__` endpoint that returns the document as JSON — point Swagger UI, Redoc, or a codegen client at it: + +```typescript +const app = createApp({ modules: [ApiModule], devOpenapi: true }); +// GET /__openapi__ → application/json +``` + +## What's structural (and what isn't yet) + +This is a **structural** spec: paths, methods, parameters, which routes take a body, and the standard error responses. What it does **not** include yet: + +- **Request/response body schemas.** [Standard Schema](/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. diff --git a/website/src/content/docs/guides/uploads.md b/website/src/content/docs/guides/uploads.md index f5939f0..0162ee9 100644 --- a/website/src/content/docs/guides/uploads.md +++ b/website/src/content/docs/guides/uploads.md @@ -57,7 +57,14 @@ Uploaded files are held in memory, so they're bounded by the same `maxBodyBytes` const app = createApp({ modules: [ApiModule], limits: { maxParts: 500 } }); ``` -A malformed multipart body (bad boundary, missing headers, truncated part) → **400**. +Both limits can be overridden **per route** — an upload endpoint can allow a larger body than the rest of the API: + +```typescript +@Post('/avatar', { maxBodyBytes: 5_000_000, maxParts: 20 }) +uploadAvatar(@body() form: MultipartBody) { /* ... */ } +``` + +A route's `maxBodyBytes` / `maxParts` fall back to the server-wide `limits` when unset. A malformed multipart body (bad boundary, missing headers, truncated part) → **400**. :::note To validate parsed fields against a schema, pass a Standard Schema to `@body()` — see [validation](/guides/validation/). diff --git a/website/src/content/docs/reference/createapp.md b/website/src/content/docs/reference/createapp.md index 518f4ab..2bb4e26 100644 --- a/website/src/content/docs/reference/createapp.md +++ b/website/src/content/docs/reference/createapp.md @@ -15,12 +15,14 @@ const app = createApp(options); | `plugins` | `Plugin[]` | `[]` | plugins, each limited to `bus.on` + `scope.add` ([plugins](/guides/plugins/)) | | `limits` | `RequestLimits` | see below | body-size and timeout ceilings | | `devGraph` | `boolean` | `false` | mount `GET /__graph__` ([introspection](/guides/introspection/)) | +| `devOpenapi` | `boolean` | `false` | mount `GET /__openapi__` serving the [OpenAPI](/guides/openapi/) document | | `overrides` | `Record` | — | swap any node by token ([testing](/guides/testing/)) | | `tls` | `TlsOptions` | — | serve over https/wss | | `trustProxy` | `boolean` | `false` | honor `X-Forwarded-*` for `ctx.protocol` / `ctx.ip` | | `security` | `boolean \| SecurityOptions` | `true` | secure-by-default headers ([security](/guides/security/)) | | `cors` | `CorsOptions` | — | CORS handling | | `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 | | `mesh` | `MeshConfig` | — | distributed DI — **requires `experimental: true`** ([mesh](/guides/mesh/)) | | `experimental` | `boolean` | `false` | opt in to alpha features (currently gates `mesh`) | @@ -62,6 +64,7 @@ const app = createApp(options); | `explain(route)` | `Explain` | the chain annotated with each node's needs/provides | | `graph()` | `GraphView` | the full node + route graph | | `toMermaid()` / `toDOT()` | `string` | render the graph | +| `openapi(info?)` | `OpenApiDoc` | structural OpenAPI 3.1 document ([details](/guides/openapi/)) | | `degraded()` | `string[]` | optional providers running degraded (empty until `listen()`) | | `bus` | `Bus` | lifecycle + request event bus | diff --git a/website/src/content/docs/reference/decorators.md b/website/src/content/docs/reference/decorators.md index 5e26430..d0d60f4 100644 --- a/website/src/content/docs/reference/decorators.md +++ b/website/src/content/docs/reference/decorators.md @@ -48,7 +48,7 @@ Method decorator. Turns a handler's return value into `{ status?, headers?, body ## Routes -Method decorators on a controller. All accept `(path, opts?)` where `opts = { export?: boolean, duplicates?: 'array' | 'last' }`. +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. | Decorator | Method | Transport | |---|---|---| @@ -58,8 +58,9 @@ Method decorators on a controller. All accept `(path, opts?)` where `opts = { ex | `@Stream` | GET | negotiated (SSE / ndjson / WS) | ```typescript -@Get('/ping', { export: true }) // exportable over mesh -@Post('/upload', { duplicates: 'array' }) // repeated form fields → arrays +@Get('/ping', { export: true }) // exportable over mesh +@Post('/upload', { duplicates: 'array' }) // repeated form fields → arrays +@Post('/avatar', { maxBodyBytes: 5_000_000, maxParts: 20 }) // per-route upload limits ``` See [Routing](/guides/routing/) for pattern matching and [Streaming](/guides/streaming/) for the transports. From 27a984f07046bede5f6733829b320d5e74ec6f62 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 10:44:03 -0500 Subject: [PATCH 079/139] feat(graph): interactive Cytoscape viewer for /__graph__ MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Mermaid's static diagram overlaps badly as the graph grows. Replace the /__graph__ HTML with an interactive Cytoscape.js + dagre viewer (both loaded from a CDN, so no runtime dependency is added — the one-dep pitch holds). Clicking a route lights up its real transitive slice and dims the rest; clicking a provider/step shows its blast radius. Edges are colour-coded by kind (needs vs feeds-endpoint), provider/step/endpoint nodes are visually distinct, and nodes are draggable. toMermaid()/toDOT() and the text/plain path are unchanged. Signed-off-by: Diego Resendez --- src/app/index.ts | 6 +- src/graph-viz.ts | 148 ++++++++++++++++++++++++++++++++++++++--- test/app.test.ts | 4 +- test/graph-viz.test.ts | 28 +++++--- 4 files changed, 162 insertions(+), 24 deletions(-) diff --git a/src/app/index.ts b/src/app/index.ts index 076742d..6d1d966 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -562,11 +562,11 @@ function devGraphRoute(graph: () => GraphView): RouteDef { pattern: '/__graph__', transport: 'buffer', handler: async (req) => { - const mermaid = toMermaid(graph()); + const view = graph(); const accept = String(req.headers['accept'] ?? ''); return accept.includes('text/plain') - ? { status: 200, headers: { 'content-type': 'text/plain' }, body: mermaid } - : { status: 200, headers: { 'content-type': 'text/html' }, body: graphHtml(mermaid) }; + ? { status: 200, headers: { 'content-type': 'text/plain' }, body: toMermaid(view) } + : { status: 200, headers: { 'content-type': 'text/html' }, body: graphHtml(view) }; }, }; } diff --git a/src/graph-viz.ts b/src/graph-viz.ts index 686c2eb..a10809b 100644 --- a/src/graph-viz.ts +++ b/src/graph-viz.ts @@ -68,14 +68,142 @@ export function toDOT(view: GraphView): string { return out.join('\n'); } -/** Wraps Mermaid source in a self-contained HTML page that renders it in the browser. */ -export function graphHtml(mermaid: string): string { - return [ - 'green-tea graph', - '', - '
',
-    mermaid,
-    '
', - '', - ].join('\n'); +/** + * Renders the graph as a self-contained, interactive HTML page (Cytoscape.js + + * dagre, both from a CDN — no runtime dependency is added). Clicking a route + * lights up its exact transitive slice and dims everything else; clicking a + * provider/step shows its blast radius (every route that depends on it). + * + * The whole {@link GraphView} is embedded as JSON, so all interaction is + * client-side — the page needs nothing from the server after it loads. + */ +export function graphHtml(view: GraphView): string { + const data = JSON.stringify(view).replace(/ + +green-tea graph + + + + +
🍵 green-tea · click a route for its slice · click a provider/step for its blast radius · drag to rearrange · click canvas to reset +
providerstependpointneedsfeeds endpoint
+
+
+`; } diff --git a/test/app.test.ts b/test/app.test.ts index dcea67f..4b52a50 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -376,8 +376,8 @@ describe('devGraph endpoint', () => { const app = createApp({ modules: [M], devGraph: true }); const s = await app.listen(0); const html = await fetch(`http://127.0.0.1:${portOf(s)}/__graph__`).then((r) => r.text()); - expect(html).toContain('class="mermaid"'); - expect(html).toContain('flowchart'); + expect(html).toContain('cytoscape'); + expect(html).toContain('/api/u/me'); const mmd = await fetch(`http://127.0.0.1:${portOf(s)}/__graph__`, { headers: { accept: 'text/plain' } }); expect(mmd.headers.get('content-type')).toContain('text/plain'); expect(await mmd.text()).toContain('flowchart'); diff --git a/test/graph-viz.test.ts b/test/graph-viz.test.ts index 940c0d3..bcbee3a 100644 --- a/test/graph-viz.test.ts +++ b/test/graph-viz.test.ts @@ -16,10 +16,10 @@ describe('toMermaid', () => { expect(m).toContain('flowchart'); expect(m).toContain('"db"'); expect(m).toContain('"user"'); - expect(m).toContain('n_config --> n_db'); // db needs config - expect(m).toContain('n_db --> n_user'); // user needs db - expect(m).not.toContain('n_req'); // 'req' is a seed (no node) -> no edge - expect(m).toContain('GET /users/:id'); // route node label + expect(m).toContain('n_config --> n_db'); // db needs config + expect(m).toContain('n_db --> n_user'); // user needs db + expect(m).not.toContain('n_req'); // 'req' is a seed (no node) -> no edge + expect(m).toContain('GET /users/:id'); // route node label }); }); @@ -32,10 +32,20 @@ describe('toDOT', () => { }); describe('graphHtml', () => { - it('wraps mermaid source in an HTML page that loads mermaid', () => { - const html = graphHtml('flowchart LR\n a-->b'); - expect(html).toContain('
');
-    expect(html).toContain('flowchart LR');
-    expect(html).toContain('mermaid');
+  it('emits an interactive Cytoscape page with the graph embedded as JSON', () => {
+    const html = graphHtml(view);
+    expect(html).toContain('cytoscape'); // loads the viz lib from CDN
+    expect(html).toContain('cytoscape-dagre'); // and the DAG layout
+    expect(html).toContain('"user"'); // node data is embedded client-side
+    expect(html).toContain('/users/:id'); // route data too
+  });
+
+  it('escapes embedded JSON so a node name cannot break out of the script tag', () => {
+    const evil = graphHtml({
+      nodes: [{ name: 'a
Date: Thu, 9 Jul 2026 11:06:47 -0500
Subject: [PATCH 080/139] feat(graph): color-code endpoint method and transport
 in the viewer
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Follow-up to the interactive viewer. Route nodes were arrow 'tag' shapes
that read as disruptive and edges were thick. Calm them down: routes are
now rounded rectangles with thinner edges.

Encode two axes visually on each endpoint — fill colour = HTTP method
(GET/POST/PUT/PATCH/DELETE), border style = transport (solid HTTP, dashed
SSE, double WS) — with a legend that explains node types, edge kinds,
transports and methods.

Signed-off-by: Diego Resendez 
---
 src/graph-viz.ts | 32 ++++++++++++++++++++++++++------
 1 file changed, 26 insertions(+), 6 deletions(-)

diff --git a/src/graph-viz.ts b/src/graph-viz.ts
index a10809b..ee252d4 100644
--- a/src/graph-viz.ts
+++ b/src/graph-viz.ts
@@ -104,12 +104,15 @@ export function graphHtml(view: GraphView): string {
   #legend .route { background:var(--tea); border-color:var(--tea); }
   #legend .ln { width:16px; height:0; border-top:3px solid; border-radius:0; }
   #legend .need { border-color:var(--need); } #legend .feed { border-color:var(--feed); }
+  #legend .tp { background:transparent; border-color:var(--dim); }
+  #legend .tp-http { border-style:solid; } #legend .tp-sse { border-style:dashed; }
+  #legend .tp-ws { border-style:double; border-width:3px; }
   #info { position:absolute; left:14px; bottom:14px; z-index:2; max-width:340px; padding:10px 12px;
     background:var(--panel); border:1px solid var(--line); border-radius:8px; white-space:pre-wrap; display:none; }
   #info .t { color:var(--tea); font-weight:700; } #info .k { color:var(--dim); }
 
 
🍵 green-tea · click a route for its slice · click a provider/step for its blast radius · drag to rearrange · click canvas to reset -
providerstependpointneedsfeeds endpoint
+
providerstepneedsfeeds endpointHTTPSSEWS
+ -
🍵 green-tea · click a route for its slice · click a provider/step for its blast radius · drag to rearrange · click canvas to reset +
${BRAND_LOGO}Green Tea.
click a route for its slice · click a provider/step for its blast radius · drag to rearrange · click canvas to reset
providerstepneedsfeeds endpointHTTPSSEWS
diff --git a/website/astro.config.mjs b/website/astro.config.mjs index a331056..ea69358 100644 --- a/website/astro.config.mjs +++ b/website/astro.config.mjs @@ -6,8 +6,11 @@ export default defineConfig({ site: 'https://green-tea.dev', integrations: [ starlight({ - title: 'green-tea', - description: 'A calm, type-safe HTTP framework for Node — your API is an explicit dependency graph.', + title: 'Green Tea.', + description: 'A zen, opinionated, type-safe framework — your API is a graph, not a chain.', + logo: { src: './src/assets/logo.svg', alt: 'Green Tea' }, + favicon: '/favicon.svg', + customCss: ['./src/styles/brand.css'], tableOfContents: { minHeadingLevel: 2, maxHeadingLevel: 3 }, sidebar: [ { diff --git a/website/public/favicon.svg b/website/public/favicon.svg new file mode 100644 index 0000000..03eb98c --- /dev/null +++ b/website/public/favicon.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/website/src/assets/logo.svg b/website/src/assets/logo.svg new file mode 100644 index 0000000..03eb98c --- /dev/null +++ b/website/src/assets/logo.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/website/src/content/docs/index.mdx b/website/src/content/docs/index.mdx index e3be954..ce98f9d 100644 --- a/website/src/content/docs/index.mdx +++ b/website/src/content/docs/index.mdx @@ -1,9 +1,12 @@ --- -title: green-tea -description: A calm, type-safe HTTP framework for Node — your API is an explicit dependency graph you can see, slice, and trust. +title: Green Tea. +description: A zen, opinionated, type-safe framework — your API is a graph you can see, slice, and trust, not a chain. template: splash hero: - tagline: Your API is an explicit dependency graph you can see, slice, and trust — not a mutable bag threaded through positional middleware. + image: + file: ../../assets/logo.svg + alt: Green Tea + tagline: A zen, opinionated, type-safe framework. Your API is a dependency graph you can see, slice, and trust — not a mutable bag threaded through positional middleware. That's the tea. 🍵 actions: - text: Get started link: /getting-started/ diff --git a/website/src/styles/brand.css b/website/src/styles/brand.css new file mode 100644 index 0000000..0f94940 --- /dev/null +++ b/website/src/styles/brand.css @@ -0,0 +1,32 @@ +/* Green Tea. — brand theme for Starlight */ +@import url('https://fonts.googleapis.com/css2?family=Zen+Maru+Gothic:wght@500;700&display=swap'); + +/* Accent = matcha (dark theme in :root, light overridden below) */ +:root { + --sl-color-accent-low: #14352a; + --sl-color-accent: #348a5f; + --sl-color-accent-high: #b9e8cf; + --sl-color-text-accent: #6fc599; + --gt-purple: #a78bfa; +} +:root[data-theme='light'] { + --sl-color-accent-low: #d3efe1; + --sl-color-accent: #2f8a5f; + --sl-color-accent-high: #123528; + --sl-color-text-accent: #2f8a5f; + --gt-purple: #7c6cf0; +} + +/* Brand type: Zen Maru for the site title and headings */ +.site-title, +h1, h2, h3 { + font-family: 'Zen Maru Gothic', var(--sl-font, sans-serif); +} +.site-title { font-weight: 700; } +.site-title img { height: 1.7rem; width: auto; } + +/* Splash hero logo */ +.hero img { max-height: 190px; width: auto; } + +/* A little zen: soften the accent link underlines */ +a { text-underline-offset: 0.15em; } From 118eb5516da92bfff72f7e0f75cee9dc3a52db29 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 13:51:55 -0500 Subject: [PATCH 082/139] refactor(http): extract mergeInjectedHeaders pure helper Signed-off-by: Diego Resendez --- src/http/headers.ts | 32 ++++++++++++++++++++++++++++++++ src/http/server.ts | 24 +++--------------------- test/http-headers.test.ts | 25 +++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 21 deletions(-) create mode 100644 src/http/headers.ts create mode 100644 test/http-headers.test.ts diff --git a/src/http/headers.ts b/src/http/headers.ts new file mode 100644 index 0000000..d9fb64e --- /dev/null +++ b/src/http/headers.ts @@ -0,0 +1,32 @@ +import { mergeVary } from '../security'; + +/** + * Merges a handler's response headers with authoritative `injected` headers + * (security + CORS). Injected keys win case-insensitively; `vary` is merged. + * Extracted from the Node writeHead patch so app.fetch shares the exact logic. + */ +export function mergeInjectedHeaders( + handlerHeaders: Record | undefined, + injected: Record, +): Record { + const merged: Record = {}; + const injectedLower = new Set(Object.keys(injected).map((key) => key.toLowerCase())); + let handlerVary: string | undefined; + + if (handlerHeaders) + for (const key of Object.keys(handlerHeaders)) { + const lowerKey = key.toLowerCase(); + + if (lowerKey === 'vary') { + handlerVary = handlerHeaders[key]; + continue; + } + + if (!injectedLower.has(lowerKey)) merged[key] = handlerHeaders[key]; + } + + Object.assign(merged, injected); + if (injected['vary']) merged['vary'] = mergeVary(handlerVary, injected['vary']); + else if (handlerVary !== undefined) merged['vary'] = handlerVary; + return merged; +} diff --git a/src/http/server.ts b/src/http/server.ts index 719d8ff..70e39fb 100644 --- a/src/http/server.ts +++ b/src/http/server.ts @@ -4,12 +4,13 @@ import { renderError, type ErrorRequest, type ErrorRenderer } from '../transform import { isHttpError, HttpError, NotFound } from '../signals'; import { isStreamResult, type PipelineResult, type ResponseShape } from '../pipeline'; import type { Bus } from '../bus'; -import { buildSecurityHeaders, mergeVary, resolveCors, corsPreflightHeaders } from '../security'; +import { buildSecurityHeaders, resolveCors, corsPreflightHeaders } from '../security'; import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart'; import { matchRoute, allowedMethods, parseQuery } from './router'; import { readBody, deriveSecure, deriveIp } from './request'; import { pickEncoder, pipeStream } from './stream'; import { attachWs } from './ws'; +import { mergeInjectedHeaders } from './headers'; import type { RouteDef, WsRouteDef, MatchedRoute, MeshControl, HttpOptions } from './types'; interface HandlerConfig { @@ -185,27 +186,8 @@ function patchResponseHeaders(res: http.ServerResponse, injected: Record { - // normalize (statusMessage?, headers?) overloads const handlerHeaders = (typeof arg2 === 'string' ? arg3 : arg2) as Record | undefined; - const merged: Record = {}; - const injectedLower = new Set(Object.keys(injected).map((key) => key.toLowerCase())); - let handlerVary: string | undefined; - - if (handlerHeaders) - for (const key of Object.keys(handlerHeaders)) { - const lowerKey = key.toLowerCase(); - - if (lowerKey === 'vary') { - handlerVary = handlerHeaders[key]; - continue; - } // merged separately below - - if (!injectedLower.has(lowerKey)) merged[key] = handlerHeaders[key]; - } - - Object.assign(merged, injected); - if (injected['vary']) merged['vary'] = mergeVary(handlerVary, injected['vary']); - else if (handlerVary !== undefined) merged['vary'] = handlerVary; // preserve handler Vary when no CORS + const merged = mergeInjectedHeaders(handlerHeaders, injected); return typeof arg2 === 'string' ? origWriteHead(status, arg2, merged) : origWriteHead(status, merged); }; } diff --git a/test/http-headers.test.ts b/test/http-headers.test.ts new file mode 100644 index 0000000..ac12196 --- /dev/null +++ b/test/http-headers.test.ts @@ -0,0 +1,25 @@ +import { describe, it, expect } from 'vitest'; +import { mergeInjectedHeaders } from '../src/http/headers'; + +describe('mergeInjectedHeaders', () => { + it('makes injected keys authoritative regardless of handler casing', () => { + const out = mergeInjectedHeaders( + { 'Content-Type': 'text/html', 'X-Content-Type-Options': 'sniffme' }, + { 'x-content-type-options': 'nosniff' }, + ); + expect(out['x-content-type-options']).toBe('nosniff'); + expect(Object.keys(out).filter((k) => k.toLowerCase() === 'x-content-type-options')).toHaveLength(1); + expect(out['Content-Type']).toBe('text/html'); // untouched handler header kept + }); + + it('merges Vary from handler and injected', () => { + const out = mergeInjectedHeaders({ Vary: 'Accept' }, { vary: 'Origin' }); + expect(out['vary'].toLowerCase()).toContain('accept'); + expect(out['vary'].toLowerCase()).toContain('origin'); + }); + + it('preserves handler Vary when no injected Vary', () => { + const out = mergeInjectedHeaders({ Vary: 'Accept' }, {}); + expect(out['vary']).toBe('Accept'); + }); +}); From 16823408c7d6c6ae37b490dcbcbcb47cea483554 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 13:58:35 -0500 Subject: [PATCH 083/139] refactor(http): extract runtime-neutral handle() core Signed-off-by: Diego Resendez --- src/http/core.ts | 89 ++++++++++++++++++++++++++++++++++ src/http/server.ts | 116 +++++++++++++++++++-------------------------- 2 files changed, 137 insertions(+), 68 deletions(-) create mode 100644 src/http/core.ts diff --git a/src/http/core.ts b/src/http/core.ts new file mode 100644 index 0000000..76fab22 --- /dev/null +++ b/src/http/core.ts @@ -0,0 +1,89 @@ +// src/http/core.ts — runtime-neutral request handling core, shared by the Node adapter and (later) app.fetch. +import { HttpError, NotFound } from '../signals'; +import { renderError } from '../transformers'; +import { isStreamResult, type PipelineResult } from '../pipeline'; +import { buildSecurityHeaders, resolveCors, corsPreflightHeaders } from '../security'; +import { matchRoute, allowedMethods, parseQuery } from './router'; +import { pickEncoder } from './stream'; +import type { RouteDef, HttpOptions } from './types'; +import type { StreamEncoder } from '../encoders'; + +/** A runtime-neutral inbound request: body already parsed by the caller's ingress (Node stream, fetch Request, …). */ +export interface NeutralRequest { + method: string; + url: string; // path + query, e.g. "/users/9?x=1" + headers: Record; + body: unknown; // already-parsed body + secure: boolean; + ip: string; +} + +/** The neutral shape of a response: a fully buffered body, or a stream to pipe frame-by-frame. */ +export type NeutralOutcome = + | { kind: 'buffered'; status: number; headers: Record; body: string | Buffer } + | { kind: 'stream'; headers: Record; stream: AsyncIterable; encoder: StreamEncoder }; + +/** {@link handle}'s result for a normal (non-preflight) request. */ +export interface HandleResult { + injected: Record; + outcome: NeutralOutcome; +} + +/** {@link handle}'s result for a CORS preflight: the caller must answer with 204 + these headers. */ +export interface Preflight { + preflight: Record; +} + +/** + * Runtime-neutral request handler: security/CORS headers, preflight short-circuit, route match / 404 / 405, + * route-handler invocation with error rendering, and the buffered-vs-stream decision. Does no I/O — the + * caller (a Node adapter, a fetch adapter, …) reads/writes the actual request/response. + */ +export async function handle( + routes: RouteDef[], + opts: HttpOptions | undefined, + req: NeutralRequest, +): Promise { + const path = req.url.split('?')[0]; + const injected: Record = { ...buildSecurityHeaders(opts?.security ?? true, req.secure) }; + if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req)); + + if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) { + return { preflight: corsPreflightHeaders(opts.cors, req) }; + } + + const matched = matchRoute(routes, req.method, path); + + if (!matched) { + // Path matches a route under a different method → 405 with Allow; otherwise 404. + const allow = allowedMethods(routes, path); + const err = allow.length ? new HttpError(405, 'Method Not Allowed') : new NotFound('Not Found'); + const rendered = renderError(err, { method: req.method, url: req.url, headers: req.headers }, opts?.onError); + const headers = allow.length ? { ...rendered.headers, allow: allow.join(', ') } : rendered.headers; + return { injected, outcome: { kind: 'buffered', status: rendered.status, headers, body: rendered.body } }; + } + + let result: PipelineResult; + + try { + result = await matched.def.handler({ + method: req.method, + url: req.url, + headers: req.headers, + params: matched.params, + query: parseQuery(req.url), + body: req.body, + protocol: req.secure ? 'https' : 'http', + ip: req.ip, + }); + } catch (error) { + result = renderError(error, { method: req.method, url: req.url, headers: req.headers }, opts?.onError); + } + + if (isStreamResult(result)) { + const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? '')); + return { injected, outcome: { kind: 'stream', headers: encoder.headers, stream: result.stream, encoder } }; + } + + return { injected, outcome: { kind: 'buffered', status: result.status, headers: result.headers, body: result.body } }; +} diff --git a/src/http/server.ts b/src/http/server.ts index 70e39fb..37d1cda 100644 --- a/src/http/server.ts +++ b/src/http/server.ts @@ -1,16 +1,16 @@ import http from 'http'; import https from 'https'; -import { renderError, type ErrorRequest, type ErrorRenderer } from '../transformers'; -import { isHttpError, HttpError, NotFound } from '../signals'; -import { isStreamResult, type PipelineResult, type ResponseShape } from '../pipeline'; +import { renderError, type ErrorRequest } from '../transformers'; +import { isHttpError, HttpError } from '../signals'; import type { Bus } from '../bus'; -import { buildSecurityHeaders, resolveCors, corsPreflightHeaders } from '../security'; +import { buildSecurityHeaders, resolveCors } from '../security'; import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart'; -import { matchRoute, allowedMethods, parseQuery } from './router'; +import { matchRoute } from './router'; import { readBody, deriveSecure, deriveIp } from './request'; -import { pickEncoder, pipeStream } from './stream'; +import { pipeStream } from './stream'; import { attachWs } from './ws'; import { mergeInjectedHeaders } from './headers'; +import { handle } from './core'; import type { RouteDef, WsRouteDef, MatchedRoute, MeshControl, HttpOptions } from './types'; interface HandlerConfig { @@ -29,19 +29,6 @@ function errorRequest(req: http.IncomingMessage): ErrorRequest { return { method: req.method ?? 'GET', url: req.url ?? '/', headers: req.headers }; } -/** Renders an error (through the optional user hook) and writes it, merging any extra headers (e.g. `Allow`). */ -function sendError( - res: http.ServerResponse, - error: unknown, - req: http.IncomingMessage, - onError?: ErrorRenderer, - extraHeaders?: Record, -): void { - const rendered = renderError(error, errorRequest(req), onError); - res.writeHead(rendered.status, extraHeaders ? { ...rendered.headers, ...extraHeaders } : rendered.headers); - res.end(rendered.body); -} - /** * Builds an HTTP/HTTPS server that routes requests, parses bodies, streams results, and handles WebSocket upgrades. * @param routes HTTP route definitions. @@ -72,13 +59,20 @@ export function createHttpServer( return server; } -/** Builds the request listener: security/CORS headers, routing, body parsing, then buffered or streamed response. */ +/** + * Builds the request listener: a thin Node adapter around the runtime-neutral {@link handle} core. + * Reads the body (Node-specific), delegates security/CORS/routing/error-rendering to `handle()`, + * then writes the result to `res` (buffered or streamed). The security-header monkeypatch is + * installed here — and stays the single source of truth for merging headers into every response — + * so `handle()`'s own `injected` is intentionally unused by this adapter. + */ function createRequestHandler(cfg: HandlerConfig) { const { routes, bus, opts, maxBody, trustProxy } = cfg; return async (req: http.IncomingMessage, res: http.ServerResponse): Promise => { const url = req.url ?? '/'; const path = url.split('?')[0]; + const method = req.method ?? 'GET'; // Install the security-header patch BEFORE any routing/response so every path // (200, 404, error, stream) writes headers through the same patched writeHead. const secure = deriveSecure(req, trustProxy); @@ -89,61 +83,47 @@ function createRequestHandler(cfg: HandlerConfig) { // by reference at writeHead time, so keys added here still land on every response. if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req)); - if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) { - res.writeHead(204, corsPreflightHeaders(opts.cors, req)); + // Mirror handle()'s own preflight/route-match decision here, so we only read the body + // (below) for a request that actually reaches a route handler — matching prior behaviour. + const isPreflight = Boolean(opts?.cors && method === 'OPTIONS' && req.headers['access-control-request-method']); + const matched = isPreflight ? undefined : matchRoute(routes, method, path); + + let body: unknown; + + if (matched) { + const acquired = await acquireBody(req, matched, opts, maxBody); + + if ('fail' in acquired) { + res.writeHead(acquired.fail.status, acquired.fail.headers); + res.end(acquired.fail.body); + return; + } + + body = acquired.body; + } + + const result = await handle(routes, opts, { + method, + url, + headers: req.headers, + body, + secure, + ip: deriveIp(req, trustProxy), + }); + + if ('preflight' in result) { + res.writeHead(204, result.preflight); res.end(); return; } - const matched = matchRoute(routes, req.method ?? 'GET', path); - - if (!matched) { - // Path matches a route under a different method → 405 with Allow; otherwise 404. - const allow = allowedMethods(routes, path); - - if (allow.length) { - sendError(res, new HttpError(405, 'Method Not Allowed'), req, opts?.onError, { allow: allow.join(', ') }); - return; - } - - sendError(res, new NotFound('Not Found'), req, opts?.onError); + if (result.outcome.kind === 'stream') { + await pipeStream(res, result.outcome.stream, result.outcome.encoder, bus, matched?.def.pattern, opts?.streams); return; } - const acquired = await acquireBody(req, matched, opts, maxBody); - - if ('fail' in acquired) { - res.writeHead(acquired.fail.status, acquired.fail.headers); - res.end(acquired.fail.body); - return; - } - - let result: PipelineResult; - - try { - result = await matched.def.handler({ - method: req.method ?? 'GET', - url, - headers: req.headers, - params: matched.params, - query: parseQuery(url), - body: acquired.body, - protocol: secure ? 'https' : 'http', - ip: deriveIp(req, trustProxy), - }); - } catch (error) { - result = renderError(error, errorRequest(req), opts?.onError); - } - - if (isStreamResult(result)) { - const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? '')); - await pipeStream(res, result.stream, encoder, bus, matched.def.pattern, opts?.streams); - return; - } - - const response: ResponseShape = result; - res.writeHead(response.status, response.headers); - res.end(response.body); + res.writeHead(result.outcome.status, result.outcome.headers); + res.end(result.outcome.body); }; } From fc75cc05e5309f411934ef7f9a7a2498b44b7de2 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 14:04:03 -0500 Subject: [PATCH 084/139] =?UTF-8?q?feat(http):=20asReadableStream=20?= =?UTF-8?q?=E2=80=94=20AsyncIterable=20to=20web=20ReadableStream?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Diego Resendez --- src/http/web.ts | 28 ++++++++++++++++++++++++++++ test/web-stream.test.ts | 25 +++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 src/http/web.ts create mode 100644 test/web-stream.test.ts diff --git a/src/http/web.ts b/src/http/web.ts new file mode 100644 index 0000000..c489822 --- /dev/null +++ b/src/http/web.ts @@ -0,0 +1,28 @@ +import type { StreamEncoder } from '../encoders'; + +/** Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream cancel. */ +export function asReadableStream(source: AsyncIterable, encoder: StreamEncoder): ReadableStream { + const iterator = source[Symbol.asyncIterator](); + const te = new TextEncoder(); + return new ReadableStream({ + async pull(controller) { + try { + const { value, done } = await iterator.next(); + + if (done) { + controller.close(); + return; + } + + const encoded = encoder.encode(value); + const bytes = typeof encoded === 'string' ? te.encode(encoded) : encoded; + controller.enqueue(bytes); + } catch (err) { + controller.error(err); + } + }, + async cancel() { + await iterator.return?.(); + }, + }); +} diff --git a/test/web-stream.test.ts b/test/web-stream.test.ts new file mode 100644 index 0000000..ad21768 --- /dev/null +++ b/test/web-stream.test.ts @@ -0,0 +1,25 @@ +import { describe, it, expect } from 'vitest'; +import { asReadableStream } from '../src/http/web'; +import { sseEncoder } from '../src/encoders'; + +async function* nums() { yield { n: 1 }; yield { n: 2 }; } + +describe('asReadableStream', () => { + it('encodes each yielded value with the encoder', async () => { + const rs = asReadableStream(nums(), sseEncoder); + const text = await new Response(rs).text(); + expect(text).toContain('data: {"n":1}'); + expect(text).toContain('data: {"n":2}'); + }); + + it('cancels the source iterator when the stream is cancelled', async () => { + let returned = false; + async function* forever() { try { while (true) yield { t: 1 }; } finally { returned = true; } } + const rs = asReadableStream(forever(), sseEncoder); + const reader = rs.getReader(); + await reader.read(); + await reader.cancel(); + await new Promise((r) => setTimeout(r, 10)); + expect(returned).toBe(true); + }); +}); From 93a4246de5a61acfb186b6397a1bd7c0eb78d02c Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 14:15:26 -0500 Subject: [PATCH 085/139] =?UTF-8?q?feat(app):=20app.fetch=20=E2=80=94=20We?= =?UTF-8?q?b-Standards=20handler=20over=20the=20neutral=20core?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Diego Resendez --- src/app/index.ts | 101 ++++++++++++++++++++++++++++++++++++++---- src/app/types.ts | 2 + src/http/server.ts | 2 +- src/http/web.ts | 107 +++++++++++++++++++++++++++++++++++++++++++++ test/fetch.test.ts | 47 ++++++++++++++++++++ 5 files changed, 249 insertions(+), 10 deletions(-) create mode 100644 test/fetch.test.ts diff --git a/src/app/index.ts b/src/app/index.ts index 6d1d966..a05c755 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -5,6 +5,8 @@ import { topoSort, subgraphFor, GraphNode, nearest } from '../graph'; import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz'; import { runPipeline, PipelineStep } from '../pipeline'; import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http'; +import type { HttpOptions } from '../http'; +import { buildFetch } from '../http/web'; import { isAsyncIterable } from '../channel'; import { JsonTransformer, type ErrorRenderer } from '../transformers'; import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin'; @@ -119,6 +121,33 @@ export function createApp(opts: { const providedSeed = (plan: RoutePlan) => seedProviders(container, plan); const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan); + // 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, + opts.overrides, + () => orderedProviders, + { runners, container, providerMeta, bus }, + degradedProviders, + ); + + const fetchOpts: HttpOptions = { + limits: opts.limits, + tls: opts.tls, + trustProxy: opts.trustProxy, + security: opts.security ?? true, + cors: opts.cors, + bodyDuplicates: opts.bodyDuplicates, + onError: opts.onError, + }; + const fetchFn = buildAppFetch( + booted, + routePlans, + { providedSeed, planSteps, bus, onError: opts.onError }, + fetchOpts, + bootAppProviders, + ); + const listen = async (port: number): Promise => { const deps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError }; @@ -133,15 +162,7 @@ export function createApp(opts: { finalize(); } - applyOverrides(opts.overrides, registry); - degradedProviders.length = 0; - degradedProviders.push(...(await bootProviders(orderedProviders, { runners, container, providerMeta, bus }))); - - if (degradedProviders.length) { - console.warn( - `[green-tea] started with ${degradedProviders.length} degraded optional provider(s): ${degradedProviders.join(', ')} — routes that need them will fail at request time.`, - ); - } + await bootAppProviders(); const meshControl = buildMeshControl(opts.mesh, registry, { container, @@ -181,6 +202,7 @@ export function createApp(opts: { return { listen, close, + fetch: fetchFn, inspect, graph, toMermaid: () => toMermaid(graph()), @@ -450,6 +472,43 @@ async function bootProviders( return degraded; } +/** + * Returns a memoized boot function: applies overrides and boots app-scope providers exactly once, + * however first triggered — {@link buildAppFetch}'s handler or `listen()` may both call it, and the + * memoization guarantees only the first call actually runs (and warns about) the boot sequence. + */ +function makeProviderBooter( + registry: Registry, + overrides: Record | undefined, + getOrderedProviders: () => GraphNode[], + deps: { + runners: Map; + container: Container; + providerMeta: Map; + bus: Bus; + }, + degradedProviders: string[], +): () => Promise { + let bootPromise: Promise | undefined; + + const runBoot = async (): Promise => { + applyOverrides(overrides, registry); + degradedProviders.length = 0; + degradedProviders.push(...(await bootProviders(getOrderedProviders(), deps))); + + if (degradedProviders.length) { + console.warn( + `[green-tea] started with ${degradedProviders.length} degraded optional provider(s): ${degradedProviders.join(', ')} — routes that need them will fail at request time.`, + ); + } + }; + + return (): Promise => { + if (!bootPromise) bootPromise = runBoot(); + return bootPromise; + }; +} + /** * Builds the mesh control gateway that exposes this node's declared exports over the control channel. * Returns undefined when there is nothing to export; throws if exports are declared without a gating secret. @@ -555,6 +614,30 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps return [...local, ...remoteRoutes]; } +/** + * Builds `app.fetch`: a Web-Standards handler over the same route table `listen()` uses, so + * `Deno.serve(app.fetch)` / `Bun.serve({ fetch: app.fetch })` work without ever calling `listen()`. + * Non-mesh apps finalize eagerly, so `booted` is already `true` and the route table is ready + * immediately. Mesh apps defer finalize to `listen()` (remote scopes must splice into the graph + * first), so the returned function throws until then — mirroring the explain()/graph()/inspect() + * "unavailable before listen()" guard. + */ +function buildAppFetch( + booted: boolean, + routePlans: RoutePlan[], + deps: PipelineDeps, + fetchOpts: HttpOptions, + ensureBooted: () => Promise, +): (request: Request) => Promise { + const handler = booted ? buildFetch(buildHttpRoutes(routePlans, [], deps), fetchOpts) : undefined; + + return async (request: Request): Promise => { + if (!handler) throw new Error('fetch() unavailable before listen() for mesh apps'); + await ensureBooted(); // idempotent: no-op if listen() already booted the providers + return handler(request); + }; +} + /** The dev-only `/__graph__` route: serves the dependency graph as Mermaid text or an HTML viewer. */ function devGraphRoute(graph: () => GraphView): RouteDef { return { diff --git a/src/app/types.ts b/src/app/types.ts index 12cbb4b..086146b 100644 --- a/src/app/types.ts +++ b/src/app/types.ts @@ -35,6 +35,8 @@ export interface Explain { export interface App { listen(port: number): Promise; close(): Promise; + /** 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; inspect(routePath: string): InspectLine[]; graph(): GraphView; toMermaid(): string; diff --git a/src/http/server.ts b/src/http/server.ts index 37d1cda..27ec76a 100644 --- a/src/http/server.ts +++ b/src/http/server.ts @@ -179,7 +179,7 @@ type ParseResult = { body: unknown } | { error: string; status?: number }; * Parses a raw request body by content type (JSON, urlencoded, multipart, or plain text). * @returns `{ body }` on success, or `{ error, status? }` on malformed input / missing multipart support. */ -async function parseRequestBody( +export async function parseRequestBody( buf: Buffer | undefined, contentType: string, duplicates: 'array' | 'last', diff --git a/src/http/web.ts b/src/http/web.ts index c489822..d146b42 100644 --- a/src/http/web.ts +++ b/src/http/web.ts @@ -1,4 +1,11 @@ import type { StreamEncoder } from '../encoders'; +import { handle, type HandleResult } from './core'; +import { mergeInjectedHeaders } from './headers'; +import { parseRequestBody } from './server'; +import { matchRoute } from './router'; +import { HttpError } from '../signals'; +import { renderError, type ErrorRequest, type ErrorResponse } from '../transformers'; +import type { RouteDef, HttpOptions, MatchedRoute } from './types'; /** Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream cancel. */ export function asReadableStream(source: AsyncIterable, encoder: StreamEncoder): ReadableStream { @@ -26,3 +33,103 @@ export function asReadableStream(source: AsyncIterable, encoder: Stream }, }); } + +/** Converts a web `Headers` into the plain record shape the neutral core and body parser expect. */ +function headersToRecord(headers: Headers): Record { + const out: Record = {}; + headers.forEach((value, key) => { + out[key] = value; + }); + return out; +} + +/** Turns a rendered error (or any {status, headers, body}) into a web `Response`. */ +function errorResponse(rendered: ErrorResponse): Response { + return new Response(rendered.body, { status: rendered.status, headers: rendered.headers }); +} + +/** + * Reads and parses a matched request's body (enforcing `maxBodyBytes` → 413), mirroring the Node + * adapter's `acquireBody`. Returns `{ body }` on success, or a ready-to-send `{ response }` on failure. + */ +async function acquireFetchBody( + request: Request, + matched: MatchedRoute, + headers: Record, + path: string, + maxBody: number, + opts: HttpOptions | undefined, +): Promise<{ body: unknown } | { response: Response }> { + const errReq: ErrorRequest = { method: request.method, url: path, headers }; + let buf: Buffer | undefined; + + if (request.body) { + const arrayBuffer = await request.arrayBuffer(); + const bodyLimit = matched.def.maxBodyBytes ?? maxBody; + + if (arrayBuffer.byteLength > bodyLimit) { + return { response: errorResponse(renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError)) }; + } + + buf = arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer); + } + + const contentType = headers['content-type'] ?? ''; + const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last'; + const maxParts = matched.def.maxParts ?? opts?.limits?.maxParts ?? 1000; + const parsed = await parseRequestBody(buf, contentType, duplicates, maxParts); + + if ('error' in parsed) { + return { + response: errorResponse(renderError(new HttpError(parsed.status ?? 400, parsed.error), errReq, opts?.onError)), + }; + } + + return { body: parsed.body }; +} + +/** Converts a {@link HandleResult}'s outcome into a web `Response`, buffered or streamed. */ +function outcomeToResponse(result: HandleResult): Response { + const headers = mergeInjectedHeaders(result.outcome.headers, result.injected) as Record; + + if (result.outcome.kind === 'stream') { + return new Response(asReadableStream(result.outcome.stream, result.outcome.encoder), { headers }); + } + + return new Response(result.outcome.body, { status: result.outcome.status, headers }); +} + +/** + * Builds a Web-Standards `fetch(request)` handler over the same route table the Node adapter uses: + * reads the body (enforcing `maxBodyBytes` → 413), parses it by content type, runs it through the + * runtime-neutral {@link handle}, and converts the outcome to a `Response` (buffered or streamed). + */ +export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) { + const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000; + + return async (request: Request): Promise => { + const url = new URL(request.url); + const path = url.pathname + url.search; + const headers = headersToRecord(request.headers); + const matched = matchRoute(routes, request.method, url.pathname); + let body: unknown; + + if (matched) { + const acquired = await acquireFetchBody(request, matched, headers, path, maxBody, opts); + if ('response' in acquired) return acquired.response; + body = acquired.body; + } + + const result = await handle(routes, opts, { + method: request.method, + url: path, + headers, + body, + secure: url.protocol === 'https:', + ip: headers['x-forwarded-for'] ?? '', + }); + + if ('preflight' in result) return new Response(null, { status: 204, headers: result.preflight }); + return outcomeToResponse(result); + }; +} diff --git a/test/fetch.test.ts b/test/fetch.test.ts new file mode 100644 index 0000000..fd96008 --- /dev/null +++ b/test/fetch.test.ts @@ -0,0 +1,47 @@ +import { describe, it, expect } from 'vitest'; +import { createApp, Provider, Route, Get, Post, Module, needs, body } from '../src/index'; + +@Provider({ provides: 'store' }) +class Store { + provide() { + return { store: { hi: 'ok' } }; + } +} +@Route('/api') +class Ctl { + @Get('/hello') hello(@needs('store') s: any) { + return { store: s.hi }; + } + @Post('/echo') echo(@body() b: any) { + return { got: b }; + } +} +@Module({ mountpoint: '/', providers: [Store], controllers: [Ctl] }) +class M {} +const app = createApp({ modules: [M] }); + +describe('app.fetch', () => { + it('handles GET and returns JSON 200', async () => { + const res = await app.fetch(new Request('http://x/api/hello')); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ store: 'ok' }); + }); + it('parses a POST body', async () => { + const res = await app.fetch( + new Request('http://x/api/echo', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ a: 1 }), + }), + ); + expect(await res.json()).toEqual({ got: { a: 1 } }); + }); + it('404s an unknown route', async () => { + const res = await app.fetch(new Request('http://x/nope')); + expect(res.status).toBe(404); + }); + it('sets secure-by-default headers', async () => { + const res = await app.fetch(new Request('http://x/api/hello')); + expect(res.headers.get('x-content-type-options')).toBe('nosniff'); + }); +}); From 08cb8554e6797b0cf6423fecf37a581e454b4e6f Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 14:26:45 -0500 Subject: [PATCH 086/139] fix(fetch): security headers on early failures, live mesh boot gate app.fetch's 413/400/501 body-acquisition failures were returned without the injected security/CORS headers Node's writeHead patch always applies, breaking byte-identical parity with the listen() path. Extract computeInjected() (shared by handle() and buildFetch()) and merge it into every error response, not just handle()'s outcomes. Also, buildAppFetch captured `booted` by value at createApp() time, so mesh apps (whose finalize() is deferred into listen()) had app.fetch permanently throw even after a successful listen(). Read booted live via a getter, mirroring explain()/graph()/inspect(), and lazily build/cache the fetch handler on first call after boot. Signed-off-by: Diego Resendez --- src/app/index.ts | 21 +++++++++++------- src/http/core.ts | 18 ++++++++++++++-- src/http/web.ts | 33 +++++++++++++++++++++------- test/fetch.test.ts | 54 ++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 108 insertions(+), 18 deletions(-) diff --git a/src/app/index.ts b/src/app/index.ts index a05c755..d156c21 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -141,7 +141,7 @@ export function createApp(opts: { onError: opts.onError, }; const fetchFn = buildAppFetch( - booted, + () => booted, routePlans, { providedSeed, planSteps, bus, onError: opts.onError }, fetchOpts, @@ -617,22 +617,27 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps /** * 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()`. - * Non-mesh apps finalize eagerly, so `booted` is already `true` and the route table is ready - * immediately. Mesh apps defer finalize to `listen()` (remote scopes must splice into the graph - * first), so the returned function throws until then — mirroring the explain()/graph()/inspect() - * "unavailable before listen()" guard. + * Non-mesh apps finalize eagerly, so `getBooted()` is already `true` and the route table is built + * on the very first call. Mesh apps defer finalize to `listen()` (remote scopes must splice into the + * graph first): `getBooted` reads the outer `booted` flag *live* on every call — exactly like + * `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( - booted: boolean, + getBooted: () => boolean, routePlans: RoutePlan[], deps: PipelineDeps, fetchOpts: HttpOptions, ensureBooted: () => Promise, ): (request: Request) => Promise { - const handler = booted ? buildFetch(buildHttpRoutes(routePlans, [], deps), fetchOpts) : undefined; + let handler: ((request: Request) => Promise) | undefined; return async (request: Request): Promise => { - if (!handler) throw new Error('fetch() unavailable before listen() for mesh apps'); + if (!handler) { + if (!getBooted()) throw new Error('fetch() unavailable before listen() for mesh apps'); + handler = buildFetch(buildHttpRoutes(routePlans, [], deps), fetchOpts); + } + await ensureBooted(); // idempotent: no-op if listen() already booted the providers return handler(request); }; diff --git a/src/http/core.ts b/src/http/core.ts index 76fab22..a6771bb 100644 --- a/src/http/core.ts +++ b/src/http/core.ts @@ -34,6 +34,21 @@ export interface Preflight { preflight: Record; } +/** + * Computes the security + CORS headers that get injected into every response for a request — the same + * authoritative set {@link handle} applies to its outcomes. Shared with `buildFetch` (src/http/web.ts) + * so early-failure responses (413/400/501, before a route even matches) carry the same headers Node's + * `patchResponseHeaders` would have installed up-front. + */ +export function computeInjected( + opts: HttpOptions | undefined, + req: { secure: boolean; headers: Record }, +): Record { + const injected: Record = { ...buildSecurityHeaders(opts?.security ?? true, req.secure) }; + if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req)); + return injected; +} + /** * Runtime-neutral request handler: security/CORS headers, preflight short-circuit, route match / 404 / 405, * route-handler invocation with error rendering, and the buffered-vs-stream decision. Does no I/O — the @@ -45,8 +60,7 @@ export async function handle( req: NeutralRequest, ): Promise { const path = req.url.split('?')[0]; - const injected: Record = { ...buildSecurityHeaders(opts?.security ?? true, req.secure) }; - if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req)); + const injected = computeInjected(opts, req); if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) { return { preflight: corsPreflightHeaders(opts.cors, req) }; diff --git a/src/http/web.ts b/src/http/web.ts index d146b42..e8d073a 100644 --- a/src/http/web.ts +++ b/src/http/web.ts @@ -1,5 +1,5 @@ import type { StreamEncoder } from '../encoders'; -import { handle, type HandleResult } from './core'; +import { handle, computeInjected, type HandleResult } from './core'; import { mergeInjectedHeaders } from './headers'; import { parseRequestBody } from './server'; import { matchRoute } from './router'; @@ -43,9 +43,15 @@ function headersToRecord(headers: Headers): Record { return out; } -/** Turns a rendered error (or any {status, headers, body}) into a web `Response`. */ -function errorResponse(rendered: ErrorResponse): Response { - return new Response(rendered.body, { status: rendered.status, headers: rendered.headers }); +/** + * Turns a rendered error (or any {status, headers, body}) into a web `Response`, merging in the + * authoritative `injected` security/CORS headers — mirrors the Node adapter, where + * `patchResponseHeaders` installs these before body acquisition even runs, so early failures + * (413/400/501) carry them too. + */ +function errorResponse(rendered: ErrorResponse, injected: Record): Response { + const headers = mergeInjectedHeaders(rendered.headers, injected); + return new Response(rendered.body, { status: rendered.status, headers }); } /** @@ -59,6 +65,7 @@ async function acquireFetchBody( path: string, maxBody: number, opts: HttpOptions | undefined, + injected: Record, ): Promise<{ body: unknown } | { response: Response }> { const errReq: ErrorRequest = { method: request.method, url: path, headers }; let buf: Buffer | undefined; @@ -68,7 +75,9 @@ async function acquireFetchBody( const bodyLimit = matched.def.maxBodyBytes ?? maxBody; if (arrayBuffer.byteLength > bodyLimit) { - return { response: errorResponse(renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError)) }; + return { + response: errorResponse(renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError), injected), + }; } buf = arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer); @@ -81,7 +90,10 @@ async function acquireFetchBody( if ('error' in parsed) { return { - response: errorResponse(renderError(new HttpError(parsed.status ?? 400, parsed.error), errReq, opts?.onError)), + response: errorResponse( + renderError(new HttpError(parsed.status ?? 400, parsed.error), errReq, opts?.onError), + injected, + ), }; } @@ -112,10 +124,15 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) { const path = url.pathname + url.search; const headers = headersToRecord(request.headers); const matched = matchRoute(routes, request.method, url.pathname); + const secure = url.protocol === 'https:'; + // Computed up-front from the same inputs `handle()` uses, so early-failure responses (413/400/501, + // before a route handler even runs) carry the same security/CORS headers Node's writeHead patch + // would have installed before body acquisition. + const injected = computeInjected(opts, { secure, headers }); let body: unknown; if (matched) { - const acquired = await acquireFetchBody(request, matched, headers, path, maxBody, opts); + const acquired = await acquireFetchBody(request, matched, headers, path, maxBody, opts, injected); if ('response' in acquired) return acquired.response; body = acquired.body; } @@ -125,7 +142,7 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) { url: path, headers, body, - secure: url.protocol === 'https:', + secure, ip: headers['x-forwarded-for'] ?? '', }); diff --git a/test/fetch.test.ts b/test/fetch.test.ts index fd96008..9b1a253 100644 --- a/test/fetch.test.ts +++ b/test/fetch.test.ts @@ -15,11 +15,23 @@ class Ctl { @Post('/echo') echo(@body() b: any) { return { got: b }; } + @Post('/tiny', { maxBodyBytes: 10 }) tiny(@body() b: any) { + return { got: b }; + } } @Module({ mountpoint: '/', providers: [Store], controllers: [Ctl] }) class M {} const app = createApp({ modules: [M] }); +@Route('/mesh') +class MeshCtl { + @Get('/ping') ping() { + return { pong: true }; + } +} +@Module({ mountpoint: '/api', controllers: [MeshCtl] }) +class MeshModule {} + describe('app.fetch', () => { it('handles GET and returns JSON 200', async () => { const res = await app.fetch(new Request('http://x/api/hello')); @@ -44,4 +56,46 @@ describe('app.fetch', () => { const res = await app.fetch(new Request('http://x/api/hello')); expect(res.headers.get('x-content-type-options')).toBe('nosniff'); }); + + it('a 413 (oversized body) still carries the injected security headers', async () => { + const res = await app.fetch( + new Request('http://x/api/tiny', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ x: 'well over ten bytes' }), + }), + ); + expect(res.status).toBe(413); + expect(res.headers.get('x-content-type-options')).toBe('nosniff'); + expect(res.headers.get('x-frame-options')).toBe('SAMEORIGIN'); + }); + + it('a 400 (invalid JSON) still carries the injected security headers', async () => { + const res = await app.fetch( + new Request('http://x/api/echo', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: '{not json', + }), + ); + expect(res.status).toBe(400); + expect(res.headers.get('x-content-type-options')).toBe('nosniff'); + }); +}); + +describe('app.fetch mesh gating (live `booted` read)', () => { + it('throws before listen() and starts working after listen() finalizes', async () => { + 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 server = await meshApp.listen(0); + try { + const res = await meshApp.fetch(new Request('http://x/api/mesh/ping')); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ pong: true }); + } finally { + server.close(); + } + }); }); From b75f127b2c3717b61563a84d6f79c83c08d63fde Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 14:33:31 -0500 Subject: [PATCH 087/139] fix(http): merge security headers into app.fetch CORS preflight responses Add a Node-vs-app.fetch parity suite that drives GET/POST/404/CORS-preflight/SSE through both the real Node server and app.fetch and asserts identical status, headers, and body. It caught a real divergence: buildFetch's preflight branch returned only the CORS-specific headers, skipping the security headers (x-content-type-options, x-frame-options, referrer-policy, x-dns-prefetch-control) that the Node adapter's writeHead patch applies to every response including the 204 preflight. Fix buildFetch to merge `injected` into the preflight response the same way, so both paths agree. Signed-off-by: Diego Resendez --- src/http/web.ts | 8 ++++- test/parity.test.ts | 86 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+), 1 deletion(-) create mode 100644 test/parity.test.ts diff --git a/src/http/web.ts b/src/http/web.ts index e8d073a..5fd6f8e 100644 --- a/src/http/web.ts +++ b/src/http/web.ts @@ -146,7 +146,13 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) { ip: headers['x-forwarded-for'] ?? '', }); - if ('preflight' in result) return new Response(null, { status: 204, headers: result.preflight }); + // Mirrors the Node adapter, where `result.preflight` is written through the writeHead patch and + // so picks up the same authoritative security headers `injected` carries (Node's writeHead patch + // merges every response — including the 204 preflight — with `injected`; this adapter must too). + if ('preflight' in result) { + return new Response(null, { status: 204, headers: mergeInjectedHeaders(result.preflight, injected) }); + } + return outcomeToResponse(result); }; } diff --git a/test/parity.test.ts b/test/parity.test.ts new file mode 100644 index 0000000..c880a20 --- /dev/null +++ b/test/parity.test.ts @@ -0,0 +1,86 @@ +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import type { Server } from 'http'; +import { createApp, Provider, Route, Get, Post, Module, needs, body, Sse } from '../src/index'; + +@Provider({ provides: 'db' }) +class Db { + provide() { + return { db: { v: 42 } }; + } +} +@Route('/api') +class Ctl { + @Get('/x') x(@needs('db') d: any) { + return { v: d.v }; + } + @Post('/y') y(@body() b: any) { + return { echo: b }; + } + @Sse('/s') s() { + return (async function* () { + yield { n: 1 }; + yield { n: 2 }; + })(); + } +} +@Module({ mountpoint: '/', providers: [Db], controllers: [Ctl] }) +class M {} +const app = createApp({ modules: [M], cors: { origins: ['https://a.test'], credentials: false } }); + +// `app.listen` returns a Promise, so it's acquired in `beforeAll` rather than via a top-level +// `await` — this repo's tsconfig (module: commonjs, target: es2017) doesn't support top-level await. +let server: Server; +let base: string; + +beforeAll(async () => { + server = await app.listen(0); + const port = (server.address() as any).port; + base = `http://127.0.0.1:${port}`; +}); +afterAll(() => server.close()); + +const norm = (h: Headers) => { + const o: Record = {}; + h.forEach((v, k) => { + if (k !== 'date' && k !== 'connection' && k !== 'keep-alive' && k !== 'content-length' && k !== 'transfer-encoding') + o[k] = v; + }); + return o; +}; + +async function both(path: string, init?: RequestInit) { + const node = await fetch(base + path, init); + const web = await app.fetch(new Request(base + path, init)); + return { node, web }; +} + +describe('Node vs app.fetch parity (Node is truth)', () => { + it('GET /api/x', async () => { + const { node, web } = await both('/api/x'); + expect(web.status).toBe(node.status); + expect(norm(web.headers)).toEqual(norm(node.headers)); + expect(await web.json()).toEqual(await node.json()); + }); + it('POST /api/y', async () => { + const init = { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ a: 1 }) }; + const { node, web } = await both('/api/y', init); + expect(web.status).toBe(node.status); + expect(await web.json()).toEqual(await node.json()); + }); + it('404', async () => { + const { node, web } = await both('/missing'); + expect(web.status).toBe(node.status); + expect(norm(web.headers)).toEqual(norm(node.headers)); + }); + it('CORS preflight', async () => { + const init = { method: 'OPTIONS', headers: { origin: 'https://a.test', 'access-control-request-method': 'GET' } }; + const { node, web } = await both('/api/x', init); + expect(web.status).toBe(node.status); + expect(norm(web.headers)).toEqual(norm(node.headers)); + }); + it('SSE first two events', async () => { + const nodeText = await (await fetch(base + '/api/s')).text(); + const webText = await (await app.fetch(new Request(base + '/api/s'))).text(); + expect(webText).toBe(nodeText); + }); +}); From 1fee7de5432a87c9272a430866908a7207ba2ebe Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 14:37:12 -0500 Subject: [PATCH 088/139] docs: app.fetch runtimes guide (Node/Deno/Bun/edge) Signed-off-by: Diego Resendez --- website/astro.config.mjs | 1 + website/src/content/docs/guides/runtimes.md | 30 +++++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 website/src/content/docs/guides/runtimes.md diff --git a/website/astro.config.mjs b/website/astro.config.mjs index ea69358..db488a6 100644 --- a/website/astro.config.mjs +++ b/website/astro.config.mjs @@ -41,6 +41,7 @@ export default defineConfig({ { label: 'Plugins & observability', slug: 'guides/plugins' }, { label: 'Graph introspection', slug: 'guides/introspection' }, { label: 'OpenAPI', slug: 'guides/openapi' }, + { label: 'Runtimes', slug: 'guides/runtimes' }, { label: 'Testing', slug: 'guides/testing' }, { label: 'Mesh (alpha)', slug: 'guides/mesh', badge: { text: 'alpha', variant: 'caution' } }, ], diff --git a/website/src/content/docs/guides/runtimes.md b/website/src/content/docs/guides/runtimes.md new file mode 100644 index 0000000..fae3a81 --- /dev/null +++ b/website/src/content/docs/guides/runtimes.md @@ -0,0 +1,30 @@ +--- +title: Runtimes (Node, Deno, Bun, edge) +description: "Run Green Tea anywhere with app.fetch — the Web-Standards handler." +--- + +Green Tea exposes a Web-Standards handler, `app.fetch(request): Promise`, so the +same app runs on any runtime that speaks the Fetch API — for **HTTP and SSE** today. + +```ts +const app = createApp({ modules: [ApiModule] }); + +// Node (native listener, TLS, timeouts) +app.listen(3000); + +// Deno +Deno.serve(app.fetch); + +// Bun +Bun.serve({ fetch: app.fetch }); + +// Cloudflare / edge +export default { fetch: app.fetch }; +``` + +**Node is the reference implementation** — every runtime returns the same status, headers, +and body for the same request (enforced by a parity test suite). + +**Not yet on non-Node runtimes:** WebSocket (`@Ws`) and mesh — Node-only for now; cross-runtime +WebSocket is on the roadmap. `app.listen()` and TLS are Node-only; on Deno/Bun/edge you get +`app.fetch`. From 43a4316a29928b944f47c0db62f90c58226fe8df Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 14:45:27 -0500 Subject: [PATCH 089/139] fix(fetch): gate x-forwarded-for on trustProxy in app.fetch The Web-Standards fetch adapter read x-forwarded-for unconditionally to seed ctx.ip, unlike Node's deriveIp which only honours it when trustProxy is enabled. A client could spoof ctx.ip on any handler relying on it. Mirror deriveIp's first-hop semantics and only trust the header when trustProxy is set; otherwise ctx.ip is ''. Signed-off-by: Diego Resendez --- src/http/web.ts | 9 ++++++++- test/fetch.test.ts | 29 ++++++++++++++++++++++++++++- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/src/http/web.ts b/src/http/web.ts index 5fd6f8e..c0f5e97 100644 --- a/src/http/web.ts +++ b/src/http/web.ts @@ -143,7 +143,14 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) { headers, body, secure, - ip: headers['x-forwarded-for'] ?? '', + // Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the proxy is + // trusted, and take its first hop — an untrusted XFF is client-spoofable, and there's no socket + // peer address to fall back to on the fetch path, so the untrusted case is simply ''. + ip: opts?.trustProxy + ? String(headers['x-forwarded-for'] ?? '') + .split(',')[0] + .trim() + : '', }); // Mirrors the Node adapter, where `result.preflight` is written through the writeHead patch and diff --git a/test/fetch.test.ts b/test/fetch.test.ts index 9b1a253..1d0373b 100644 --- a/test/fetch.test.ts +++ b/test/fetch.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { createApp, Provider, Route, Get, Post, Module, needs, body } from '../src/index'; +import { createApp, Provider, Route, Get, Post, Module, needs, body, ctx } from '../src/index'; @Provider({ provides: 'store' }) class Store { @@ -83,6 +83,33 @@ describe('app.fetch', () => { }); }); +@Route('/ip') +class IpCtl { + @Get('/whoami') whoami(@ctx() c: any) { + return { ip: c.ip }; + } +} +@Module({ mountpoint: '/', controllers: [IpCtl] }) +class IpModule {} + +describe('app.fetch trustProxy gates x-forwarded-for', () => { + it('honors x-forwarded-for (first hop) when trustProxy is true', async () => { + const trustingApp = createApp({ modules: [IpModule], trustProxy: true }); + const res = await trustingApp.fetch( + new Request('http://x/ip/whoami', { headers: { 'x-forwarded-for': '9.9.9.9, 1.1.1.1' } }), + ); + expect(await res.json()).toEqual({ ip: '9.9.9.9' }); + }); + + it('ignores x-forwarded-for when trustProxy is off (default)', async () => { + const untrustingApp = createApp({ modules: [IpModule] }); + const res = await untrustingApp.fetch( + new Request('http://x/ip/whoami', { headers: { 'x-forwarded-for': '9.9.9.9, 1.1.1.1' } }), + ); + expect(await res.json()).toEqual({ ip: '' }); + }); +}); + describe('app.fetch mesh gating (live `booted` read)', () => { it('throws before listen() and starts working after listen() finalizes', async () => { const meshApp = createApp({ modules: [MeshModule], experimental: true, mesh: { secret: 's3cr3t' } }); From 58853e8ba853d1ab759a89360f343a39f2fcbb9e Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 14:45:34 -0500 Subject: [PATCH 090/139] docs: changelog for app.fetch + provider memoization, runtimes body-size note Record the app.fetch Web-Standards handler and the app-scope provider memoization behaviour change in the changelog, and note on the runtimes guide that app.fetch reads oversized bodies fully before rejecting them (unlike Node's mid-stream abort) so non-Node deployments should also bound request size at the platform layer. Signed-off-by: Diego Resendez --- CHANGELOG.md | 9 ++++++++- website/src/content/docs/guides/runtimes.md | 4 ++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 71eafdd..61d84f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,14 @@ green-tea uses calendar versioning: `YY.MM.PATCH`. ## [Unreleased] -_Nothing yet._ +### Added +- **`app.fetch(request): Promise`** — a Web-Standards handler so the + same app runs HTTP and SSE on Deno/Bun/edge runtimes via the Fetch API + (WebSocket and mesh remain Node-only). + +### Changed +- App-scope providers now boot exactly once (memoized): a second `app.listen()` + call no longer re-runs provider factories or their side effects. ## [26.7.0-beta.0] - 2026-07-07 diff --git a/website/src/content/docs/guides/runtimes.md b/website/src/content/docs/guides/runtimes.md index fae3a81..0136f73 100644 --- a/website/src/content/docs/guides/runtimes.md +++ b/website/src/content/docs/guides/runtimes.md @@ -28,3 +28,7 @@ and body for the same request (enforced by a parity test suite). **Not yet on non-Node runtimes:** WebSocket (`@Ws`) and mesh — Node-only for now; cross-runtime WebSocket is on the roadmap. `app.listen()` and TLS are Node-only; on Deno/Bun/edge you get `app.fetch`. + +**Body-size enforcement differs slightly:** on `app.fetch`, an oversized body is read in full +before the `413` is returned, whereas Node aborts mid-stream once the limit is hit — so on +non-Node runtimes, also bound request size at the platform/runtime layer. From 179a58f0e4a0cc29ee22bfe1051e6efe79a7ae1c Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 16:44:59 -0500 Subject: [PATCH 091/139] feat(ws): neutral runWsConnection core behind a WsSocket capability Signed-off-by: Diego Resendez --- src/http/types.ts | 5 +- src/http/ws-core.ts | 114 +++++++++++++++++++++++++++++++++++++++++++ test/ws-core.test.ts | 112 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 229 insertions(+), 2 deletions(-) create mode 100644 src/http/ws-core.ts create mode 100644 test/ws-core.test.ts diff --git a/src/http/types.ts b/src/http/types.ts index 44cdcd3..ddd02db 100644 --- a/src/http/types.ts +++ b/src/http/types.ts @@ -3,6 +3,7 @@ import type { Transport } from '../metadata'; import type { PipelineResult } from '../pipeline'; import type { ErrorRenderer } from '../transformers'; import type { TlsOptions, SecurityOptions, CorsOptions } from '../security'; +import type { WsRequest } from './ws-core'; /** Per-request size and timeout ceilings applied by the server. */ export interface RequestLimits { @@ -54,12 +55,12 @@ export interface MatchedRoute { def: RouteDef; } -/** Context passed to a WebSocket route's `open`: path params, inbound message stream, abort signal, and raw request. */ +/** Context passed to a WebSocket route's `open`: path params, inbound message stream, abort signal, and neutral request. */ export interface WsOpenCtx { params: Record; inbound: AsyncIterable; abort: AbortSignal; - req: http.IncomingMessage; + req: WsRequest; } /** A registered WebSocket route: path pattern and an `open` that returns the outbound message stream. */ diff --git a/src/http/ws-core.ts b/src/http/ws-core.ts new file mode 100644 index 0000000..8e411af --- /dev/null +++ b/src/http/ws-core.ts @@ -0,0 +1,114 @@ +import { isHttpError } from '../signals'; +import type { Bus } from '../bus'; +import { matchPattern } from './router'; +import type { WsRouteDef } from './types'; + +/** Neutral, runtime-free WebSocket request context (replaces the raw Node req). */ +export interface WsRequest { + url: string; + headers: Record; + protocol: 'http' | 'https'; + ip: string; +} + +/** Capability an adapter builds from its runtime socket. The neutral core talks only to this. */ +export interface WsSocket { + readonly inbound: AsyncIterable; + readonly abort: AbortSignal; + readonly isOpen: boolean; + send(data: string): void; + close(code?: number, reason?: string): void; + terminate(): void; +} + +/** Finds the first ws route whose pattern matches `path`, capturing its params. */ +export function matchWsRoute( + wsRoutes: WsRouteDef[], + path: string, +): { def: WsRouteDef; params: Record | undefined } | undefined { + return wsRoutes + .map((candidate) => ({ def: candidate, params: matchPattern(candidate.pattern, path) })) + .find((entry) => entry.params); +} + +/** Registers the connection with the stream registry so it can be force-closed on shutdown. */ +function trackConnection(socket: WsSocket, streams?: Set<() => void>): { closer: () => void } { + const closer = () => { + try { + socket.terminate(); + } catch { + /* */ + } + }; + + streams?.add(closer); + return { closer }; +} + +/** Drives the outbound async iterator, sending each yielded value until done or the socket closes. */ +async function pumpOutbound(socket: WsSocket, iterator: AsyncIterator): Promise { + while (true) { + const { value, done } = await iterator.next(); + if (done) break; + if (!socket.isOpen) break; + socket.send(typeof value === 'string' ? value : JSON.stringify(value)); + } + + try { + socket.close(); + } catch { + /* already closed */ + } +} + +/** Closes with 4000+status for HttpErrors, 1011 otherwise. */ +function closeOnError(socket: WsSocket, err: unknown): void { + if (isHttpError(err)) { + const reason = Buffer.from(String(err.message)).subarray(0, 120).toString(); + + try { + socket.close(4000 + err.status, reason); + } catch { + /* already closed */ + } + } else { + try { + socket.close(1011); + } catch { + /* already closed */ + } + } +} + +/** Runs the full per-connection lifecycle over a neutral socket capability. */ +export async function runWsConnection( + socket: WsSocket, + request: WsRequest, + route: { def: WsRouteDef; params: Record | undefined }, + bus?: Bus, + streams?: Set<() => void>, +): Promise { + const { closer } = trackConnection(socket, streams); + const name = route.def.pattern; + let iterator: AsyncIterator | undefined; + const cancelOutbound = () => void Promise.resolve(iterator?.return?.()).catch(() => {}); + socket.abort.addEventListener('abort', cancelOutbound, { once: true }); + bus?.emit('stream:open', { name }); + + try { + const outbound = await route.def.open({ + params: route.params ?? {}, + inbound: socket.inbound, + abort: socket.abort, + req: request, + }); + iterator = outbound[Symbol.asyncIterator](); + await pumpOutbound(socket, iterator); + } catch (err) { + bus?.emit('stream:error', { name, error: err }); + closeOnError(socket, err); + } finally { + streams?.delete(closer); + bus?.emit('stream:close', { name }); + } +} diff --git a/test/ws-core.test.ts b/test/ws-core.test.ts new file mode 100644 index 0000000..e93ec66 --- /dev/null +++ b/test/ws-core.test.ts @@ -0,0 +1,112 @@ +import { describe, it, expect } from 'vitest'; +import { runWsConnection, matchWsRoute, type WsSocket, type WsRequest } from '../src/http/ws-core'; +import { channel } from '../src/channel'; +import { HttpError } from '../src/signals'; +import type { WsRouteDef } from '../src/http/types'; + +/** A controllable fake WsSocket that records sends and closes. */ +function fakeSocket() { + const inbound = channel(); + const ac = new AbortController(); + const sent: string[] = []; + const closes: Array<{ code?: number; reason?: string }> = []; + let open = true; + const socket: WsSocket = { + inbound, + abort: ac.signal, + get isOpen() { + return open; + }, + send: (d) => sent.push(d), + close: (code, reason) => { + open = false; + closes.push({ code, reason }); + ac.abort(); + }, + terminate: () => { + open = false; + ac.abort(); + }, + }; + return { socket, inbound, sent, closes, ac }; +} + +const req: WsRequest = { url: '/ws', headers: {}, protocol: 'http', ip: '127.0.0.1' }; + +describe('runWsConnection (neutral core)', () => { + it('sends each yielded outbound value, string or JSON', async () => { + const def: WsRouteDef = { + pattern: '/ws', + open: async () => + (async function* () { + yield 'hi'; + yield { n: 1 }; + })(), + }; + const { socket, sent } = fakeSocket(); + await runWsConnection(socket, req, { def, params: {} }); + expect(sent).toEqual(['hi', JSON.stringify({ n: 1 })]); + }); + + it('closes with 4000+status when the route throws an HttpError', async () => { + const def: WsRouteDef = { + pattern: '/ws', + open: async () => { + throw new HttpError(401, 'nope'); + }, + }; + const { socket, closes } = fakeSocket(); + await runWsConnection(socket, req, { def, params: {} }); + expect(closes[0].code).toBe(4401); + expect(closes[0].reason).toBe('nope'); + }); + + it('closes with 1011 on a generic throw', async () => { + const def: WsRouteDef = { + pattern: '/ws', + open: async () => { + throw new Error('boom'); + }, + }; + const { socket, closes } = fakeSocket(); + await runWsConnection(socket, req, { def, params: {} }); + expect(closes[0].code).toBe(1011); + }); + + it('registers a closer in the shutdown registry and removes it when done', async () => { + const streams = new Set<() => void>(); + const def: WsRouteDef = { + pattern: '/ws', + open: async () => + (async function* () { + yield 'x'; + })(), + }; + const { socket } = fakeSocket(); + await runWsConnection(socket, req, { def, params: {} }, undefined, streams); + expect(streams.size).toBe(0); // added then removed + }); + + it('passes inbound + params + request to route.open', async () => { + let seen: any; + const def: WsRouteDef = { + pattern: '/ws/:id', + open: async (ctx) => { + seen = ctx; + return (async function* () {})(); + }, + }; + const { socket } = fakeSocket(); + await runWsConnection(socket, req, { def, params: { id: '7' } }); + expect(seen.params).toEqual({ id: '7' }); + expect(seen.req).toBe(req); + expect(typeof seen.inbound[Symbol.asyncIterator]).toBe('function'); + expect(seen.abort).toBeInstanceOf(AbortSignal); + }); + + it('matchWsRoute finds a pattern and captures params', () => { + const routes: WsRouteDef[] = [{ pattern: '/ws/:id', open: async () => (async function* () {})() }]; + expect(matchWsRoute(routes, '/ws/42')?.params).toEqual({ id: '42' }); + expect(matchWsRoute(routes, '/nope')).toBeUndefined(); + }); +}); From 5e68d2de65f5efd0c3554de07bdae934536f0bb3 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 16:51:42 -0500 Subject: [PATCH 092/139] fix(ws): runtime-neutral close reason + registry removal on transport close Signed-off-by: Diego Resendez --- src/http/ws-core.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/http/ws-core.ts b/src/http/ws-core.ts index 8e411af..7a642bb 100644 --- a/src/http/ws-core.ts +++ b/src/http/ws-core.ts @@ -64,7 +64,7 @@ async function pumpOutbound(socket: WsSocket, iterator: AsyncIterator): /** Closes with 4000+status for HttpErrors, 1011 otherwise. */ function closeOnError(socket: WsSocket, err: unknown): void { if (isHttpError(err)) { - const reason = Buffer.from(String(err.message)).subarray(0, 120).toString(); + const reason = new TextDecoder().decode(new TextEncoder().encode(String(err.message)).subarray(0, 120)); try { socket.close(4000 + err.status, reason); @@ -91,8 +91,13 @@ export async function runWsConnection( const { closer } = trackConnection(socket, streams); const name = route.def.pattern; let iterator: AsyncIterator | undefined; - const cancelOutbound = () => void Promise.resolve(iterator?.return?.()).catch(() => {}); - socket.abort.addEventListener('abort', cancelOutbound, { once: true }); + + const onAbort = () => { + streams?.delete(closer); + void Promise.resolve(iterator?.return?.()).catch(() => {}); + }; + + socket.abort.addEventListener('abort', onAbort, { once: true }); bus?.emit('stream:open', { name }); try { @@ -108,7 +113,6 @@ export async function runWsConnection( bus?.emit('stream:error', { name, error: err }); closeOnError(socket, err); } finally { - streams?.delete(closer); bus?.emit('stream:close', { name }); } } From 7a8be39d57588f353281f0283494c3c7e4082782 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 16:56:17 -0500 Subject: [PATCH 093/139] refactor(ws): Node adapter builds WsSocket over the neutral core MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Also fixes buildWsRoutes (app/index.ts) to read the pre-derived protocol/ip off the neutral WsRequest instead of req.socket, which no longer exists now that WsOpenCtx.req is WsRequest — without this every real @Ws route throws on open() and the connection hangs. Signed-off-by: Diego Resendez --- src/app/index.ts | 7 +-- src/http/ws.ts | 127 ++++++++++++----------------------------------- 2 files changed, 35 insertions(+), 99 deletions(-) diff --git a/src/app/index.ts b/src/app/index.ts index d156c21..5a80b11 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -683,7 +683,8 @@ function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[ pattern: plan.pattern, open: async ({ params, inbound, abort, req }) => { const provided = await providedSeed(plan); - // ws upgrades come in on the raw Node req; trustProxy derivation for ws is out of scope here + // ws upgrades carry the neutral WsRequest (protocol/ip pre-derived by the runtime adapter); + // trustProxy derivation for ws is out of scope here // context is intentionally `any`: each step merges arbitrary keys into it let context: any = { ...provided, @@ -694,8 +695,8 @@ function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[ headers: req.headers, inbound, abort, - protocol: (req.socket as any).encrypted ? 'https' : 'http', - ip: req.socket.remoteAddress ?? '', + protocol: req.protocol, + ip: req.ip, }; for (const step of planSteps(plan)) { diff --git a/src/http/ws.ts b/src/http/ws.ts index a2736fe..5f0ae62 100644 --- a/src/http/ws.ts +++ b/src/http/ws.ts @@ -1,8 +1,7 @@ import http from 'http'; import { channel } from '../channel'; -import { isHttpError } from '../signals'; import type { Bus } from '../bus'; -import { matchPattern } from './router'; +import { runWsConnection, matchWsRoute, type WsSocket, type WsRequest } from './ws-core'; import type { WsRouteDef, MeshControl } from './types'; /** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */ @@ -43,108 +42,42 @@ function handleMeshUpgrade( return true; } -/** Finds the first ws route whose pattern matches `path`, capturing its params. */ -function matchWsRoute( - wsRoutes: WsRouteDef[], - path: string, -): { def: WsRouteDef; params: Record | undefined } | undefined { - return wsRoutes - .map((candidate) => ({ def: candidate, params: matchPattern(candidate.pattern, path) })) - .find((entry) => entry.params); +/** Builds the neutral WsRequest from a Node upgrade request. Same values the old open() read from req.socket. */ +function nodeWsRequest(req: http.IncomingMessage): WsRequest { + return { + url: req.url ?? '/', + headers: req.headers, + protocol: (req.socket as any).encrypted ? 'https' : 'http', + ip: req.socket.remoteAddress ?? '', + }; } -/** Wires inbound message/close/error events into a channel and returns the channel plus its abort controller. */ -function wireInbound(ws: any): { inbound: ReturnType>; abortController: AbortController } { +/** Wraps a `ws` socket as a neutral WsSocket: inbound channel + abort on close + send/close/terminate. */ +function nodeSocket(ws: any): WsSocket { const inbound = channel(); - const abortController = new AbortController(); + const ac = new AbortController(); ws.on('message', (data: Buffer) => inbound.push(data.toString())); ws.on('close', () => { inbound.close(); - abortController.abort(); + ac.abort(); }); ws.on('error', (err: unknown) => inbound.fail(err)); - - return { inbound, abortController }; -} - -/** Registers the connection with the stream registry so it can be force-closed on shutdown. */ -function trackConnection(ws: any, streams?: Set<() => void>): void { - const closer = () => { - try { - (ws.terminate ?? ws.close).call(ws); - } catch { - /* */ - } + return { + inbound, + abort: ac.signal, + get isOpen() { + return ws.readyState === 1; // 1 = OPEN + }, + send: (data) => ws.send(data), + close: (code, reason) => { + try { + ws.close(code, reason); + } catch { + /* already closed */ + } + }, + terminate: () => (ws.terminate ?? ws.close).call(ws), }; - - streams?.add(closer); - ws.on('close', () => streams?.delete(closer)); -} - -/** Drives the outbound async iterator, sending each yielded value over the socket until done or closed. */ -async function pumpOutbound(ws: any, iterator: AsyncIterator): Promise { - while (true) { - const { value, done } = await iterator.next(); - if (done) break; - if (ws.readyState !== 1) break; // 1 = OPEN; stop if socket gone - ws.send(typeof value === 'string' ? value : JSON.stringify(value)); - } - - try { - ws.close(); - } catch { - /* already closed */ - } -} - -/** Closes the socket with the appropriate code after an outbound error (4000+status for HTTP errors, 1011 otherwise). */ -function closeOnError(ws: any, err: unknown): void { - if (isHttpError(err)) { - const reason = Buffer.from(String(err.message)).subarray(0, 120).toString(); - - try { - ws.close(4000 + err.status, reason); - } catch { - /* already closed */ - } - } else { - try { - ws.close(1011); - } catch { - /* already closed */ - } - } -} - -/** Runs the full per-connection lifecycle: inbound wiring, opening the route stream, and pumping outbound values. */ -async function openWsConnection( - ws: any, - route: { def: WsRouteDef; params: Record | undefined }, - req: http.IncomingMessage, - bus?: Bus, - streams?: Set<() => void>, -): Promise { - trackConnection(ws, streams); - const { inbound, abortController } = wireInbound(ws); - - const name = route.def.pattern; - let iterator: AsyncIterator | undefined; - ws.on('close', () => { - void Promise.resolve(iterator?.return?.()).catch(() => {}); - }); // force-cancel outbound - bus?.emit('stream:open', { name }); - - try { - const outbound = await route.def.open({ params: route.params!, inbound, abort: abortController.signal, req }); - iterator = outbound[Symbol.asyncIterator](); - await pumpOutbound(ws, iterator); - } catch (err) { - bus?.emit('stream:error', { name, error: err }); - closeOnError(ws, err); - } finally { - abortController.abort(); - bus?.emit('stream:close', { name }); - } } /** Attaches WebSocket upgrade handling to the server: routes to `wsRoutes` or a mesh control path. */ @@ -175,6 +108,8 @@ export function attachWs( return; } - wss.handleUpgrade(req, socket, head, (ws: any) => openWsConnection(ws, route, req, bus, streams)); + wss.handleUpgrade(req, socket, head, (ws: any) => { + void runWsConnection(nodeSocket(ws), nodeWsRequest(req), route, bus, streams); + }); }); } From d72452d9b655a6bbc8be32983168a745e024dcf8 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 17:04:38 -0500 Subject: [PATCH 094/139] =?UTF-8?q?feat(app):=20app.upgrade=20=E2=80=94=20?= =?UTF-8?q?neutral=20WebSocket=20entry=20over=20the=20graph?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Diego Resendez --- src/app/index.ts | 45 ++++++++++++++++++++++++++++++ src/app/types.ts | 3 ++ test/app-upgrade.test.ts | 59 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 107 insertions(+) create mode 100644 test/app-upgrade.test.ts diff --git a/src/app/index.ts b/src/app/index.ts index 5a80b11..6976798 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -7,6 +7,7 @@ import { runPipeline, PipelineStep } from '../pipeline'; import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http'; import type { HttpOptions } from '../http'; import { buildFetch } from '../http/web'; +import { matchWsRoute, runWsConnection, type WsRequest, type WsSocket } from '../http/ws-core'; import { isAsyncIterable } from '../channel'; import { JsonTransformer, type ErrorRenderer } from '../transformers'; import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin'; @@ -147,6 +148,13 @@ export function createApp(opts: { fetchOpts, bootAppProviders, ); + const upgradeFn = buildAppUpgrade( + () => booted, + routePlans, + { providedSeed, planSteps, bus, onError: opts.onError }, + streams, + bootAppProviders, + ); const listen = async (port: number): Promise => { const deps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError }; @@ -203,6 +211,7 @@ export function createApp(opts: { listen, close, fetch: fetchFn, + upgrade: upgradeFn, inspect, graph, toMermaid: () => toMermaid(graph()), @@ -643,6 +652,42 @@ function buildAppFetch( }; } +/** + * Builds `app.upgrade`: the neutral WebSocket entry over the same route table `listen()` uses, so + * Deno/Bun/edge adapters can drive ws connections without ever calling `listen()`. Node keeps its own + * `server.on('upgrade')` path (see `attachWs`) and never calls this. + * Mirrors {@link buildAppFetch}'s finalize guard exactly: non-mesh apps finalize eagerly, so + * `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( + getBooted: () => boolean, + routePlans: RoutePlan[], + deps: PipelineDeps, + streams: Set<() => void>, + ensureBooted: () => Promise, +): (request: WsRequest, socket: WsSocket) => Promise { + let wsRoutes: WsRouteDef[] | undefined; + + return async (request: WsRequest, socket: WsSocket): Promise => { + if (!wsRoutes) { + if (!getBooted()) throw new Error('upgrade() unavailable before listen() for mesh apps'); + wsRoutes = buildWsRoutes(routePlans, deps); + } + + await ensureBooted(); // idempotent: no-op if listen() already booted the providers + const path = request.url.split('?')[0]; + const route = matchWsRoute(wsRoutes, path); + + if (!route) { + socket.close(1008, 'no matching ws route'); + return; + } + + await runWsConnection(socket, request, route, deps.bus, streams); + }; +} + /** The dev-only `/__graph__` route: serves the dependency graph as Mermaid text or an HTML viewer. */ function devGraphRoute(graph: () => GraphView): RouteDef { return { diff --git a/src/app/types.ts b/src/app/types.ts index 086146b..50606a1 100644 --- a/src/app/types.ts +++ b/src/app/types.ts @@ -5,6 +5,7 @@ import type { GraphView } from '../graph-viz'; import type { HttpMethod, Transport } from '../metadata'; import type { ArgSpec } from '../params'; import type { OpenApiDoc, OpenApiInfo } from '../openapi'; +import type { WsRequest, WsSocket } from '../http/ws-core'; import { JsonTransformer } from '../transformers'; /** One entry in an {@link App.inspect} listing: a provider, step or handler and where it came from. */ @@ -37,6 +38,8 @@ export interface App { close(): Promise; /** 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; + /** Run a WebSocket upgrade through the graph using an adapter-provided socket (Deno/Bun/edge). Node uses its own listener path. */ + upgrade(request: WsRequest, socket: WsSocket): Promise; inspect(routePath: string): InspectLine[]; graph(): GraphView; toMermaid(): string; diff --git a/test/app-upgrade.test.ts b/test/app-upgrade.test.ts new file mode 100644 index 0000000..ebad14c --- /dev/null +++ b/test/app-upgrade.test.ts @@ -0,0 +1,59 @@ +import { describe, it, expect } from 'vitest'; +import { createApp, Route, Ws, Module, ctx } from '../src/index'; +import { channel } from '../src/channel'; +import type { WsSocket, WsRequest } from '../src/http/ws-core'; + +@Route('/rt') +class Rt { + @Ws('/echo') + echo(@ctx() { inbound }: any) { + return (async function* () { + for await (const msg of inbound) yield `echo:${msg}`; + })(); + } +} +@Module({ mountpoint: '/', controllers: [Rt] }) +class M {} +const app = createApp({ modules: [M] }); + +function fakeSocket() { + const inbound = channel(); + const ac = new AbortController(); + const sent: string[] = []; + const socket: WsSocket = { + inbound, + abort: ac.signal, + isOpen: true, + send: (d) => sent.push(d), + close: () => ac.abort(), + terminate: () => ac.abort(), + }; + return { socket, inbound, sent }; +} + +describe('app.upgrade', () => { + it('routes a matching ws path through the graph', async () => { + const { socket, inbound, sent } = fakeSocket(); + const req: WsRequest = { url: '/rt/echo', headers: {}, protocol: 'http', ip: '' }; + const run = app.upgrade(req, socket); + // let the handler's async generator start subscribing to `inbound` (channel is fan-out: + // push before subscription is lost) before pushing — a macrotask flushes every pending + // microtask in the upgrade/boot chain first, so this is deterministic, not a sleep-and-hope. + await new Promise((resolve) => setTimeout(resolve, 0)); + inbound.push('hi'); + inbound.close(); + await run; + expect(sent).toEqual(['echo:hi']); + }); + + it('closes 1008 on an unknown ws path', async () => { + const { socket } = fakeSocket(); + let closedCode: number | undefined; + socket.close = (c) => { + closedCode = c; + }; + const req: WsRequest = { url: '/rt/nope', headers: {}, protocol: 'http', ip: '' }; + await app.upgrade(req, socket); + expect(closedCode).toBe(1008); + }); +}); From 12eccd941cbd0d954d1f05fbbfa1a9636028de43 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 17:11:00 -0500 Subject: [PATCH 095/139] =?UTF-8?q?feat(deno):=20serveDeno=20adapter=20?= =?UTF-8?q?=E2=80=94=20HTTP+SSE+WS=20on=20Deno=20via=20/deno=20subpath?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Diego Resendez --- package.json | 11 +++++ src/deno.ts | 110 +++++++++++++++++++++++++++++++++++++++++++++++++ tsup.config.ts | 2 +- 3 files changed, 122 insertions(+), 1 deletion(-) create mode 100644 src/deno.ts diff --git a/package.json b/package.json index f9cb8c5..9a3d9e9 100644 --- a/package.json +++ b/package.json @@ -36,6 +36,16 @@ "types": "./dist/index.d.ts", "default": "./dist/index.js" } + }, + "./deno": { + "import": { + "types": "./dist/deno.d.mts", + "default": "./dist/deno.mjs" + }, + "require": { + "types": "./dist/deno.d.ts", + "default": "./dist/deno.js" + } } }, "files": [ @@ -49,6 +59,7 @@ "build": "tsup", "test": "vitest run", "test:dev": "vitest", + "test:deno": "deno test --allow-net --allow-read test/deno/", "typecheck": "tsc --noEmit -p tsconfig.json", "typecheck:bench": "tsc --noEmit -p bench/tsconfig.json", "lint": "eslint src", diff --git a/src/deno.ts b/src/deno.ts new file mode 100644 index 0000000..f0d6e9b --- /dev/null +++ b/src/deno.ts @@ -0,0 +1,110 @@ +import { channel } from './channel'; +import type { App } from './app/types'; +import type { WsSocket, WsRequest } from './http/ws-core'; + +// 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 +// (both the instance interface and the `OPEN` static, mirroring the real WebSocket). +interface WebSocketEventMap { + message: { data: unknown }; + close: object; + error: object; +} +interface WebSocket { + readonly readyState: number; + send(data: string): void; + close(code?: number, reason?: string): void; + addEventListener(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. +// Mirrors the real Deno.serve / Deno.upgradeWebSocket signatures we call. +interface DenoServeOptions { + port?: number; + hostname?: string; + signal?: AbortSignal; + onListen?: (addr: { hostname: string; port: number }) => void; +} +interface DenoServeHandlerInfo { + remoteAddr: { hostname: string; port: number; transport: string }; +} +interface DenoHttpServer { + finished: Promise; + shutdown(): Promise; +} +type DenoServeHandler = (request: Request, info: DenoServeHandlerInfo) => Response | Promise; +declare const Deno: { + serve(options: DenoServeOptions, handler: DenoServeHandler): DenoHttpServer; + 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 = {}; + 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(); + const ac = new AbortController(); + ws.addEventListener('message', (e) => inbound.push(typeof e.data === 'string' ? e.data : String(e.data))); + 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. + * WebSocket messages flow through app.upgrade over the shared neutral core. + */ +export function serveDeno(app: App, options?: DenoServeOptions): DenoHttpServer { + return Deno.serve(options ?? {}, (request, info) => { + if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { + const { socket, response } = Deno.upgradeWebSocket(request); + // fire-and-forget: the graph runs after we return the upgrade response. + // runWsConnection swallows its own errors (closeOnError), so nothing escapes. + void app.upgrade(toWsRequest(request, info), denoSocket(socket)); + return response; + } + + return app.fetch(request); + }); +} diff --git a/tsup.config.ts b/tsup.config.ts index 20e97ef..ac3aeff 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -4,7 +4,7 @@ import { defineConfig } from 'tsup'; // tsup injects a createRequire shim into the ESM output so the lazy require('ws') / require('busboy') // (optional peer deps) keep working there. reflect-metadata and the peer deps stay external. export default defineConfig({ - entry: ['src/index.ts'], + entry: ['src/index.ts', 'src/deno.ts'], format: ['cjs', 'esm'], dts: true, clean: true, From e9357efb5ca06ad7a15b4e87e437835a368cbc67 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 17:17:20 -0500 Subject: [PATCH 096/139] fix(deno): guard fire-and-forget app.upgrade against fatal unhandled rejection Signed-off-by: Diego Resendez --- src/deno.ts | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/deno.ts b/src/deno.ts index f0d6e9b..008653e 100644 --- a/src/deno.ts +++ b/src/deno.ts @@ -99,9 +99,17 @@ export function serveDeno(app: App, options?: DenoServeOptions): DenoHttpServer return Deno.serve(options ?? {}, (request, info) => { if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { const { socket, response } = Deno.upgradeWebSocket(request); - // fire-and-forget: the graph runs after we return the upgrade response. - // runWsConnection swallows its own errors (closeOnError), so nothing escapes. - void app.upgrade(toWsRequest(request, info), denoSocket(socket)); + // Fire-and-forget: the upgrade response must be returned synchronously while + // the graph runs. app.upgrade can reject BEFORE runWsConnection's own try/catch + // (mesh-before-listen throw, or a provider boot failure), so guard the call here — + // 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; } From f85b39c2c3bf0408853da417c4d03300881d6eed Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 17:23:24 -0500 Subject: [PATCH 097/139] test(deno): serveDeno HTTP + WebSocket integration Signed-off-by: Diego Resendez --- deno.json | 16 ++++++++++ deno.lock | 51 +++++++++++++++++++++++++++++++ package.json | 2 +- test/deno/ws.test.ts | 71 ++++++++++++++++++++++++++++++++++++++++++++ tsconfig.json | 3 +- vitest.config.ts | 11 +++++-- 6 files changed, 150 insertions(+), 4 deletions(-) create mode 100644 deno.json create mode 100644 deno.lock create mode 100644 test/deno/ws.test.ts diff --git a/deno.json b/deno.json new file mode 100644 index 0000000..3a2fd5b --- /dev/null +++ b/deno.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "experimentalDecorators": true, + "emitDecoratorMetadata": true, + "lib": ["deno.window", "deno.ns"] + }, + "unstable": ["sloppy-imports"], + "imports": { + "http": "node:http", + "https": "node:https", + "crypto": "node:crypto", + "events": "node:events", + "stream": "node:stream" + }, + "lint": { "exclude": ["dist", "node_modules"] } +} diff --git a/deno.lock b/deno.lock new file mode 100644 index 0000000..c087fc3 --- /dev/null +++ b/deno.lock @@ -0,0 +1,51 @@ +{ + "version": "5", + "specifiers": { + "jsr:@std/assert@*": "1.0.19", + "jsr:@std/internal@^1.0.12": "1.0.14" + }, + "jsr": { + "@std/assert@1.0.19": { + "integrity": "eaada96ee120cb980bc47e040f82814d786fe8162ecc53c91d8df60b8755991e", + "dependencies": [ + "jsr:@std/internal" + ] + }, + "@std/internal@1.0.14": { + "integrity": "291516b3d4c35024d6ffbc0a9df5bf4c64116e05b50012cf846710152d2ffdf7" + } + }, + "workspace": { + "packageJson": { + "dependencies": [ + "npm:@eslint/js@^9.39.4", + "npm:@nestjs/common@^11.1.27", + "npm:@nestjs/core@^11.1.27", + "npm:@nestjs/platform-express@^11.1.27", + "npm:@nestjs/platform-fastify@^11.1.27", + "npm:@stylistic/eslint-plugin@^5.10.0", + "npm:@types/autocannon@^7.12.7", + "npm:@types/busboy@^1.5.4", + "npm:@types/express@^5.0.6", + "npm:@types/node@^18.19.0", + "npm:@types/ws@^8.18.1", + "npm:autocannon@8", + "npm:busboy@^1.6.0", + "npm:cognitive-complexity-ts@~0.8.2", + "npm:eslint@^9.39.4", + "npm:express@^5.2.1", + "npm:fastify@^5.10.0", + "npm:graphql@^16.9.0", + "npm:prettier@^3.9.4", + "npm:reflect-metadata@0.2.2", + "npm:rxjs@^7.8.2", + "npm:tsup@^8.5.1", + "npm:tsx@^4.23.0", + "npm:typescript-eslint@^8.63.0", + "npm:typescript@^5.5.0", + "npm:vitest@2", + "npm:ws@^8.21.0" + ] + } + } +} diff --git a/package.json b/package.json index 9a3d9e9..68ffafa 100644 --- a/package.json +++ b/package.json @@ -59,7 +59,7 @@ "build": "tsup", "test": "vitest run", "test:dev": "vitest", - "test:deno": "deno test --allow-net --allow-read test/deno/", + "test:deno": "deno test --allow-net --allow-read --no-check test/deno/", "typecheck": "tsc --noEmit -p tsconfig.json", "typecheck:bench": "tsc --noEmit -p bench/tsconfig.json", "lint": "eslint src", diff --git a/test/deno/ws.test.ts b/test/deno/ws.test.ts new file mode 100644 index 0000000..4bd39e4 --- /dev/null +++ b/test/deno/ws.test.ts @@ -0,0 +1,71 @@ +// Real Deno integration test for serveDeno: boots an app under the actual Deno runtime +// and round-trips both HTTP (app.fetch) and WebSocket (Deno.upgradeWebSocket -> app.upgrade). +// +// Run with: npm run test:deno (or: deno test --allow-net --allow-read --no-check test/deno/) +// +// `--no-check`: the barrel (`src/index.ts`) re-exports types from Node-only modules +// (e.g. `src/http/*`) that reference ambient Node globals like `Buffer`. Those modules +// aren't executed under Deno (this test only exercises `serveDeno`'s fetch/WebSocket +// path), but Deno's checker still type-checks the whole reachable graph and has no +// ambient `Buffer` type without a full `@types/node` setup. Node-side static typing for +// those modules is already covered by `npm run typecheck` (tsc); this test's job is to +// prove Deno *runtime* behavior of the adapter, not re-typecheck Node-only internals. +import 'npm:reflect-metadata'; +import { assertEquals } from 'jsr:@std/assert'; +import { createApp, Route, Ws, Get, Module, ctx } from '../../src/index.ts'; +import { serveDeno } from '../../src/deno.ts'; + +@Route('/rt') +class Rt { + @Get('/hello') + hello() { + return { ok: true }; + } + + @Ws('/echo') + echo(@ctx() { inbound }: any) { + return (async function* () { + for await (const msg of inbound) yield `echo:${msg}`; + })(); + } +} + +@Module({ mountpoint: '/', controllers: [Rt] }) +class M {} + +Deno.test('serveDeno: HTTP + WebSocket round-trip through the graph', async () => { + const app = createApp({ modules: [M] }); + + let port = 0; + const server = serveDeno(app, { + port: 0, + onListen: (addr) => { + port = addr.port; + }, + }); + + // Let onListen fire before we try to connect. + await new Promise((resolve) => setTimeout(resolve, 50)); + + try { + const httpRes = await fetch(`http://127.0.0.1:${port}/rt/hello`); + assertEquals(httpRes.status, 200); + assertEquals((await httpRes.json()).ok, true); + + const ws = new WebSocket(`ws://127.0.0.1:${port}/rt/echo`); + try { + const got = await new Promise((resolve, reject) => { + ws.onopen = () => ws.send('hi'); + ws.onmessage = (e) => resolve(String(e.data)); + ws.onerror = () => reject(new Error('ws error')); + }); + assertEquals(got, 'echo:hi'); + } finally { + ws.close(); + // Give the close frame a moment to complete the handshake so no socket is leaked. + await new Promise((resolve) => setTimeout(resolve, 20)); + } + } finally { + await server.shutdown(); + } +}); diff --git a/tsconfig.json b/tsconfig.json index bea4487..5383782 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -14,5 +14,6 @@ "emitDecoratorMetadata": true, "forceConsistentCasingInFileNames": true }, - "include": ["src", "test", "example"] + "include": ["src", "test", "example"], + "exclude": ["test/deno"] } diff --git a/vitest.config.ts b/vitest.config.ts index f8fcf14..2343b4a 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,5 +1,12 @@ -import { defineConfig } from 'vitest/config'; +import { defineConfig, configDefaults } from 'vitest/config'; export default defineConfig({ - test: { globals: false, environment: 'node', include: ['test/**/*.test.ts'] }, + test: { + globals: false, + environment: 'node', + include: ['test/**/*.test.ts'], + // test/deno/** holds Deno.test files run separately via `npm run test:deno`; + // they use `npm:`/`jsr:` specifiers vitest can't resolve. + exclude: [...configDefaults.exclude, 'test/deno/**'], + }, }); From 47b7bf5f24b26f7c713d98cfa3e4f387eaad10ab Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 17:27:26 -0500 Subject: [PATCH 098/139] =?UTF-8?q?docs:=20serveDeno=20+=20app.upgrade=20?= =?UTF-8?q?=E2=80=94=20WebSocket=20on=20Deno?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Diego Resendez --- CHANGELOG.md | 2 ++ website/src/content/docs/guides/runtimes.md | 32 +++++++++++++++++++-- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 61d84f6..d28243b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ green-tea uses calendar versioning: `YY.MM.PATCH`. - **`app.fetch(request): Promise`** — a Web-Standards handler so the 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. +- **`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`). ### Changed - App-scope providers now boot exactly once (memoized): a second `app.listen()` diff --git a/website/src/content/docs/guides/runtimes.md b/website/src/content/docs/guides/runtimes.md index 0136f73..957389d 100644 --- a/website/src/content/docs/guides/runtimes.md +++ b/website/src/content/docs/guides/runtimes.md @@ -25,10 +25,36 @@ export default { fetch: app.fetch }; **Node is the reference implementation** — every runtime returns the same status, headers, and body for the same request (enforced by a parity test suite). -**Not yet on non-Node runtimes:** WebSocket (`@Ws`) and mesh — Node-only for now; cross-runtime -WebSocket is on the roadmap. `app.listen()` and TLS are Node-only; on Deno/Bun/edge you get -`app.fetch`. +**Not yet on Bun/edge runtimes:** WebSocket (`@Ws`) and mesh — still Node-only there; Deno now +has WebSocket support via `serveDeno` (see below). `app.listen()` and TLS remain Node-only; on +Deno/Bun/edge you get `app.fetch`. **Body-size enforcement differs slightly:** on `app.fetch`, an oversized body is read in full before the `413` is returned, whereas Node aborts mid-stream once the limit is hit — so on non-Node runtimes, also bound request size at the platform/runtime layer. + +## WebSocket on Deno + +`app.fetch` covers HTTP + SSE on every runtime. WebSocket needs a runtime-specific +upgrade, so Deno gets a dedicated adapter at `@green-tea/core/deno`: + +```ts +import { createApp } from '@green-tea/core'; +import { serveDeno } from '@green-tea/core/deno'; + +const app = createApp({ modules: [ChatModule] }); + +// HTTP + SSE via app.fetch, WebSocket via Deno.upgradeWebSocket — one call: +serveDeno(app, { port: 8000 }); +``` + +`serveDeno` routes normal requests through `app.fetch` and WebSocket upgrades through +`app.upgrade` — the same graph, the same `@Ws` handlers, the same rooms/channels you +run on Node. Behaviour matches the Node reference. + +**Advanced:** `app.upgrade(request, socket)` is the neutral primitive `serveDeno` uses. +Any runtime can build a `WsSocket` capability (`inbound`, `abort`, `isOpen`, `send`, +`close`, `terminate`) and drive the graph — this is how Bun and edge support will land. + +**Still Node-only:** `app.listen()`, TLS, per-request timeouts, and mesh. On Deno you +get `app.fetch` + `serveDeno`. From 4a6ef784ec776d264b3496031c469beb69578cc7 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 17:38:23 -0500 Subject: [PATCH 099/139] fix(deno): decode binary ws frames to match Node; changelog ctx.req note Signed-off-by: Diego Resendez --- CHANGELOG.md | 6 ++++++ src/deno.ts | 10 ++++++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d28243b..5226a77 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,12 @@ green-tea uses calendar versioning: `YY.MM.PATCH`. ### Changed - App-scope providers now boot exactly once (memoized): a second `app.listen()` call no longer re-runs provider factories or their side effects. +- **`WsOpenCtx.req`** (available in `@Ws`/`@Sse` handlers) is now a neutral + `WsRequest` (`{ url, headers, protocol, ip }`) instead of the Node + `http.IncomingMessage`, so it works the same across Node and Deno. Node-only + fields such as `req.socket` / `req.rawHeaders` are no longer available on + `ctx.req`; use `ctx.protocol` / `ctx.ip` / `ctx.query` / `ctx.headers` + instead — all still provided. ## [26.7.0-beta.0] - 2026-07-07 diff --git a/src/deno.ts b/src/deno.ts index 008653e..eafe6dc 100644 --- a/src/deno.ts +++ b/src/deno.ts @@ -6,12 +6,13 @@ import type { WsSocket, WsRequest } from './http/ws-core'; // 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 WebSocketEventMap { - message: { data: unknown }; + message: { data: string | ArrayBuffer }; close: object; error: object; } interface WebSocket { readonly readyState: number; + binaryType: string; send(data: string): void; close(code?: number, reason?: string): void; addEventListener(type: K, listener: (event: WebSocketEventMap[K]) => void): void; @@ -58,7 +59,12 @@ function toWsRequest(request: Request, info: DenoServeHandlerInfo): WsRequest { function denoSocket(ws: WebSocket): WsSocket { const inbound = channel(); const ac = new AbortController(); - ws.addEventListener('message', (e) => inbound.push(typeof e.data === 'string' ? e.data : String(e.data))); + 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(); From fd6446f5146a67373e8dc90009b2a21c2d828d62 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 21:44:46 -0500 Subject: [PATCH 100/139] =?UTF-8?q?feat(bun):=20serveBun=20adapter=20?= =?UTF-8?q?=E2=80=94=20HTTP+SSE+WS=20on=20Bun=20via=20/bun=20subpath?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Diego Resendez --- package.json | 11 +++++ src/bun.ts | 131 +++++++++++++++++++++++++++++++++++++++++++++++++ tsup.config.ts | 2 +- 3 files changed, 143 insertions(+), 1 deletion(-) create mode 100644 src/bun.ts diff --git a/package.json b/package.json index 68ffafa..7f29f35 100644 --- a/package.json +++ b/package.json @@ -46,6 +46,16 @@ "types": "./dist/deno.d.ts", "default": "./dist/deno.js" } + }, + "./bun": { + "import": { + "types": "./dist/bun.d.mts", + "default": "./dist/bun.mjs" + }, + "require": { + "types": "./dist/bun.d.ts", + "default": "./dist/bun.js" + } } }, "files": [ @@ -60,6 +70,7 @@ "test": "vitest run", "test:dev": "vitest", "test:deno": "deno test --allow-net --allow-read --no-check test/deno/", + "test:bun": "bun test test/bun/", "typecheck": "tsc --noEmit -p tsconfig.json", "typecheck:bench": "tsc --noEmit -p bench/tsconfig.json", "lint": "eslint src", diff --git a/src/bun.ts b/src/bun.ts new file mode 100644 index 0000000..4da5579 --- /dev/null +++ b/src/bun.ts @@ -0,0 +1,131 @@ +import { channel } from './channel'; +import type { Channel } from './channel'; +import type { App } from './app/types'; +import type { WsSocket, WsRequest } from './http/ws-core'; + +// Minimal ambient for the Bun globals we use — avoids a @types/bun devDep. +// Mirrors the real Bun.serve / server.upgrade / ServerWebSocket signatures we call. +interface BunServerWebSocket { + data: unknown; + readyState: number; + send(data: string): number; + close(code?: number, reason?: string): void; + terminate?(): void; +} +interface BunWebSocketHandler { + open?(ws: BunServerWebSocket): void; + message(ws: BunServerWebSocket, message: string | Uint8Array): void; + close?(ws: BunServerWebSocket, code: number, reason: string): void; +} +interface BunServer { + port: number; + stop(closeActiveConnections?: boolean): void; + upgrade(request: Request, options?: { data?: unknown; headers?: Record }): boolean; + requestIP(request: Request): { address: string; family: string; port: number } | null; +} +interface BunServeOptions { + port?: number; + hostname?: string; + fetch(request: Request, server: BunServer): Response | Promise | undefined; + websocket?: BunWebSocketHandler; +} +type BunServeShortOptions = { port?: number; hostname?: string }; +declare const Bun: { serve(options: BunServeOptions): BunServer }; + +/** Per-connection state stashed on ws.data between fetch (upgrade) and the open/message/close callbacks. */ +interface BunConnData { + wsReq: WsRequest; + inbound: Channel; + ac: AbortController; +} + +/** Builds a neutral WsRequest from a Bun request + server (for the client IP). */ +function toWsRequest(request: Request, server: BunServer): WsRequest { + const url = new URL(request.url); + const headers: Record = {}; + 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 { + const { inbound, ac } = ws.data as BunConnData; + return { + inbound, + abort: ac.signal, + get isOpen() { + return ws.readyState === 1; // 1 = OPEN + }, + send: (data) => { + ws.send(data); + }, + close: (code, reason) => { + try { + ws.close(code, reason); + } catch { + /* already closed */ + } + }, + terminate: () => { + try { + (ws.terminate ?? ws.close).call(ws); + } catch { + /* already closed */ + } + }, + }; +} + +/** + * Serve a Green Tea app on Bun: HTTP + SSE via app.fetch, WebSocket via Bun's server-level + * websocket handler. The ServerWebSocket only exists in open(), so per-connection state + * (inbound channel, abort, WsRequest) is stashed on ws.data during the upgrade. + */ +export function serveBun(app: App, options?: BunServeShortOptions): BunServer { + return Bun.serve({ + ...options, + fetch(request, server) { + if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { + const inbound = channel(); + const ac = new AbortController(); + const data: BunConnData = { wsReq: toWsRequest(request, server), inbound, ac }; + if (server.upgrade(request, { data })) return undefined; + return new Response('WebSocket upgrade failed', { status: 400 }); + } + + return app.fetch(request); + }, + websocket: { + open(ws) { + const { wsReq } = ws.data as BunConnData; + // fire-and-forget: app.upgrade can reject before runWsConnection's try/catch + // (mesh-before-listen, provider boot failure); guard it or an uncaught rejection + // could crash the Bun process. + void app.upgrade(wsReq, bunSocket(ws)).catch(() => { + try { + ws.close(1011, 'internal error'); + } catch { + /* already closed */ + } + }); + }, + message(ws, message) { + 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 : new TextDecoder().decode(message)); + }, + close(ws) { + const { inbound, ac } = ws.data as BunConnData; + inbound.close(); + ac.abort(); + }, + }, + }); +} diff --git a/tsup.config.ts b/tsup.config.ts index ac3aeff..bfad144 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -4,7 +4,7 @@ import { defineConfig } from 'tsup'; // tsup injects a createRequire shim into the ESM output so the lazy require('ws') / require('busboy') // (optional peer deps) keep working there. reflect-metadata and the peer deps stay external. export default defineConfig({ - entry: ['src/index.ts', 'src/deno.ts'], + entry: ['src/index.ts', 'src/deno.ts', 'src/bun.ts'], format: ['cjs', 'esm'], dts: true, clean: true, From 4351b41038f5a9c509bd25e5fdfed5b173140e7d Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 21:51:33 -0500 Subject: [PATCH 101/139] test(bun): serveBun HTTP + WebSocket integration Signed-off-by: Diego Resendez --- test/bun/ws.test.ts | 49 +++++++++++++++++++++++++++++++++++++++++++++ tsconfig.json | 2 +- vitest.config.ts | 2 +- 3 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 test/bun/ws.test.ts diff --git a/test/bun/ws.test.ts b/test/bun/ws.test.ts new file mode 100644 index 0000000..e4cd4f9 --- /dev/null +++ b/test/bun/ws.test.ts @@ -0,0 +1,49 @@ +// Real Bun integration test for serveBun: boots an app under the actual Bun runtime +// and round-trips both HTTP (app.fetch) and WebSocket (Bun's server-level websocket +// handler -> app.upgrade). +// +// Run with: npm run test:bun (or: bun test test/bun/) +import 'reflect-metadata'; +import { test, expect } from 'bun:test'; +import { createApp, Route, Get, Ws, ctx, Module } from '../../src/index.ts'; +import { serveBun } from '../../src/bun.ts'; + +@Route('/rt') +class Rt { + @Get('/hello') + hello() { + return { ok: true }; + } + @Ws('/echo') + echo(@ctx() { inbound }: any) { + return (async function* () { + for await (const msg of inbound) yield `echo:${msg}`; + })(); + } +} +@Module({ mountpoint: '/', controllers: [Rt] }) +class M {} + +test('serveBun: HTTP + WebSocket round-trip', async () => { + const app = createApp({ modules: [M] }); + const server = serveBun(app, { port: 0 }); + const port = server.port; + try { + const httpRes = await fetch(`http://127.0.0.1:${port}/rt/hello`); + expect(httpRes.status).toBe(200); + expect((await httpRes.json()).ok).toBe(true); + + const ws = new WebSocket(`ws://127.0.0.1:${port}/rt/echo`); + const got = await new Promise((resolve, reject) => { + ws.onopen = () => ws.send('hi'); + ws.onmessage = (e) => { + resolve(String(e.data)); + ws.close(); + }; + ws.onerror = () => reject(new Error('ws error')); + }); + expect(got).toBe('echo:hi'); + } finally { + server.stop(true); + } +}); diff --git a/tsconfig.json b/tsconfig.json index 5383782..6dff172 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -15,5 +15,5 @@ "forceConsistentCasingInFileNames": true }, "include": ["src", "test", "example"], - "exclude": ["test/deno"] + "exclude": ["test/deno", "test/bun"] } diff --git a/vitest.config.ts b/vitest.config.ts index 2343b4a..48255af 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -7,6 +7,6 @@ export default defineConfig({ include: ['test/**/*.test.ts'], // test/deno/** holds Deno.test files run separately via `npm run test:deno`; // they use `npm:`/`jsr:` specifiers vitest can't resolve. - exclude: [...configDefaults.exclude, 'test/deno/**'], + exclude: [...configDefaults.exclude, 'test/deno/**', 'test/bun/**'], }, }); From 3d21117a07c747d1e75cc5628234497f2b6570e4 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 21:54:34 -0500 Subject: [PATCH 102/139] =?UTF-8?q?docs:=20serveBun=20=E2=80=94=20WebSocke?= =?UTF-8?q?t=20on=20Bun?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Diego Resendez --- CHANGELOG.md | 1 + website/src/content/docs/guides/runtimes.md | 31 ++++++++++++++++++--- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5226a77..0efc786 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ green-tea uses calendar versioning: `YY.MM.PATCH`. 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. +- **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. - **`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`). ### Changed diff --git a/website/src/content/docs/guides/runtimes.md b/website/src/content/docs/guides/runtimes.md index 957389d..7dd7470 100644 --- a/website/src/content/docs/guides/runtimes.md +++ b/website/src/content/docs/guides/runtimes.md @@ -25,9 +25,9 @@ export default { fetch: app.fetch }; **Node is the reference implementation** — every runtime returns the same status, headers, and body for the same request (enforced by a parity test suite). -**Not yet on Bun/edge runtimes:** WebSocket (`@Ws`) and mesh — still Node-only there; Deno now -has WebSocket support via `serveDeno` (see below). `app.listen()` and TLS remain Node-only; on -Deno/Bun/edge you get `app.fetch`. +**Not yet on edge runtimes:** WebSocket (`@Ws`) and mesh — still Node-only there; Deno and Bun +now have full WebSocket support via `serveDeno` and `serveBun` (see below). `app.listen()` and +TLS remain Node-only; on Deno/Bun/edge you get `app.fetch`. **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 @@ -54,7 +54,30 @@ run on Node. Behaviour matches the Node reference. **Advanced:** `app.upgrade(request, socket)` is the neutral primitive `serveDeno` uses. Any runtime can build a `WsSocket` capability (`inbound`, `abort`, `isOpen`, `send`, -`close`, `terminate`) and drive the graph — this is how Bun and edge support will land. +`close`, `terminate`) and drive the graph — `serveBun` builds on the same primitive +(see below), and this is how future edge support will land. **Still Node-only:** `app.listen()`, TLS, per-request timeouts, and mesh. On Deno you get `app.fetch` + `serveDeno`. + +## WebSocket on Bun + +`app.fetch` covers HTTP + SSE on every runtime. WebSocket needs a runtime-specific +upgrade, so Bun gets a dedicated adapter at `@green-tea/core/bun`: + +```ts +import { createApp } from '@green-tea/core'; +import { serveBun } from '@green-tea/core/bun'; + +const app = createApp({ modules: [ChatModule] }); + +// HTTP + SSE via app.fetch, WebSocket via Bun's server-level handler — one call: +serveBun(app, { port: 8000 }); +``` + +`serveBun` routes normal requests through `app.fetch` and WebSocket upgrades through +`app.upgrade` — the same graph, the same `@Ws` handlers, the same rooms/channels you +run on Node and Deno. Behaviour matches the Node reference. + +**Still Node-only:** `app.listen()`, TLS, per-request timeouts, and mesh. On Bun you +get `app.fetch` + `serveBun`. From 82824e5f6d409e7d90b5d63e58dea160c9facfe4 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 22:00:23 -0500 Subject: [PATCH 103/139] fix(bun): add ws error handler for Node/Deno parity; hoist TextDecoder Signed-off-by: Diego Resendez --- src/bun.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/bun.ts b/src/bun.ts index 4da5579..9169db7 100644 --- a/src/bun.ts +++ b/src/bun.ts @@ -16,6 +16,7 @@ interface BunWebSocketHandler { open?(ws: BunServerWebSocket): void; message(ws: BunServerWebSocket, message: string | Uint8Array): void; close?(ws: BunServerWebSocket, code: number, reason: string): void; + error?(ws: BunServerWebSocket, error?: unknown): void; } interface BunServer { port: number; @@ -32,6 +33,8 @@ interface BunServeOptions { type BunServeShortOptions = { port?: number; hostname?: string }; 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. */ interface BunConnData { wsReq: WsRequest; @@ -119,13 +122,18 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServer { message(ws, message) { 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 : new TextDecoder().decode(message)); + inbound.push(typeof message === 'string' ? message : decoder.decode(message)); }, close(ws) { const { inbound, ac } = ws.data as BunConnData; inbound.close(); ac.abort(); }, + error(ws) { + const { inbound, ac } = ws.data as BunConnData; + inbound.fail(new Error('websocket error')); + ac.abort(); + }, }, }); } From 9344cc7d43c5cf000ab0e1ab0017d234ee76591c Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 23:22:28 -0500 Subject: [PATCH 104/139] =?UTF-8?q?feat(edge):=20edgeHandler=20adapter=20?= =?UTF-8?q?=E2=80=94=20HTTP+SSE+WS=20on=20Cloudflare=20Workers=20via=20/ed?= =?UTF-8?q?ge=20subpath?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Diego Resendez --- package.json | 10 +++++ src/edge.ts | 108 +++++++++++++++++++++++++++++++++++++++++++++++++ tsup.config.ts | 2 +- 3 files changed, 119 insertions(+), 1 deletion(-) create mode 100644 src/edge.ts diff --git a/package.json b/package.json index 7f29f35..6cd1cc4 100644 --- a/package.json +++ b/package.json @@ -56,6 +56,16 @@ "types": "./dist/bun.d.ts", "default": "./dist/bun.js" } + }, + "./edge": { + "import": { + "types": "./dist/edge.d.mts", + "default": "./dist/edge.mjs" + }, + "require": { + "types": "./dist/edge.d.ts", + "default": "./dist/edge.js" + } } }, "files": [ diff --git a/src/edge.ts b/src/edge.ts new file mode 100644 index 0000000..ec4780c --- /dev/null +++ b/src/edge.ts @@ -0,0 +1,108 @@ +import { channel } from './channel'; +import type { App } from './app/types'; +import type { WsSocket, WsRequest } from './http/ws-core'; + +// Minimal ambient for the Cloudflare Workers globals we use — avoids @cloudflare/workers-types. +// Declares only what we call; mirrors the real workerd signatures. +interface EdgeWebSocket { + 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 { + waitUntil(promise: Promise): void; +} +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 = {}; + 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. + * Use as `export default { fetch: edgeHandler(app) }`. Requires the `nodejs_compat` + * compatibility flag. The WS lifecycle runs on ctx.waitUntil so it survives past the 101 response. + */ +export function edgeHandler( + app: App, +): (request: Request, env?: unknown, ctx?: EdgeCtx) => Response | Promise { + return (request, _env, ctx) => { + if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { + const [client, server] = Object.values(new WebSocketPair()) as [EdgeWebSocket, EdgeWebSocket]; + server.accept(); + const lifecycle = app.upgrade(toWsRequest(request), edgeSocket(server)).catch(() => { + try { + server.close(1011, 'internal error'); + } catch { + /* already closed */ + } + }); + if (ctx?.waitUntil) ctx.waitUntil(lifecycle); + else void lifecycle; + + return new Response(null, { status: 101, webSocket: client } as ResponseInit & { webSocket: EdgeWebSocket }); + } + + return app.fetch(request); + }; +} diff --git a/tsup.config.ts b/tsup.config.ts index bfad144..99f1c7f 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -4,7 +4,7 @@ import { defineConfig } from 'tsup'; // tsup injects a createRequire shim into the ESM output so the lazy require('ws') / require('busboy') // (optional peer deps) keep working there. reflect-metadata and the peer deps stay external. export default defineConfig({ - entry: ['src/index.ts', 'src/deno.ts', 'src/bun.ts'], + entry: ['src/index.ts', 'src/deno.ts', 'src/bun.ts', 'src/edge.ts'], format: ['cjs', 'esm'], dts: true, clean: true, From a4c9df9a74269aae7149633624413c89b0ed8db5 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 23:34:19 -0500 Subject: [PATCH 105/139] test(edge): edgeHandler HTTP + WebSocket on real workerd via Miniflare MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Boots the actual workerd engine locally (miniflare devDep, no CF account needed) and round-trips HTTP (app.fetch) + WebSocket (WebSocketPair + app.upgrade) through edgeHandler's real request path, mirroring the Deno/Bun adapter tests' assertion shape. workerd's nodejs_compat genuinely does not implement node:http/node:https (confirmed in isolation against the real runtime; node:crypto, node:stream, node:net, node:tls, node:events, node:util, node:buffer all load fine under the same flags). The barrel statically imports them for the Node listen() path even though edgeHandler never touches it, so the bundler stubs those two modules at test-bundle time (inert createServer that throws if ever called) purely to let the worker load — edgeHandler itself is untouched. See project-docs/.superpowers/sdd/task-2-report.md for the full writeup and the suggested core follow-up (lazy-defer those imports behind listen()). Signed-off-by: Diego Resendez --- .gitignore | 3 + package-lock.json | 846 +++++++++++++++++++++++++++++++++++++++++++- package.json | 2 + test/edge/run.ts | 124 +++++++ test/edge/worker.ts | 27 ++ tsconfig.json | 2 +- vitest.config.ts | 2 +- 7 files changed, 1002 insertions(+), 4 deletions(-) create mode 100644 test/edge/run.ts create mode 100644 test/edge/worker.ts diff --git a/.gitignore b/.gitignore index 32206f8..f4437d0 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,6 @@ coverage/ # Astro (docs site) .astro/ website/dist/ + +# Edge (Miniflare) test bundle artifact +test/edge/_worker.mjs diff --git a/package-lock.json b/package-lock.json index a78fbe7..383ec9e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@green-tea/core", - "version": "0.0.0", + "version": "26.7.0-beta.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@green-tea/core", - "version": "0.0.0", + "version": "26.7.0-beta.0", "license": "MIT", "dependencies": { "reflect-metadata": "0.2.2" @@ -30,6 +30,7 @@ "express": "^5.2.1", "fastify": "^5.10.0", "graphql": "^16.9.0", + "miniflare": "^4.20260708.1", "prettier": "^3.9.4", "rxjs": "^7.8.2", "tsup": "^8.5.1", @@ -39,6 +40,9 @@ "vitest": "^2.0.0", "ws": "^8.21.0" }, + "engines": { + "node": ">=18" + }, "peerDependencies": { "busboy": "^1.6.0", "ws": "^8.18.0" @@ -70,6 +74,91 @@ "url": "https://github.com/sponsors/Borewit" } }, + "node_modules/@cloudflare/workerd-darwin-64": { + "version": "1.20260708.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20260708.1.tgz", + "integrity": "sha512-HXFCvhS1wpg3uXO0CLUwmwC41i2loM5FSK69EUchOBpmYBAXxT1oHLm6EOA5lqhTk5Mu9kjRiQYxa1GwKPwfJg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-darwin-arm64": { + "version": "1.20260708.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20260708.1.tgz", + "integrity": "sha512-JVlJaKDoRTVKSroHIlf8g3UCPjKj4iDbMZE2CNYht5qQ+2rL0FAUiVlV82G3BqKnnw9kHYnnsMzC08b9zVtdzA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-linux-64": { + "version": "1.20260708.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20260708.1.tgz", + "integrity": "sha512-3daE60YdD7YX0Jtuzc9DE/r/qMkmx8ZvHTkF8Mzmp3F5tbzlV0DAzmu5PFUPF2WuvtKbAhZKbvC2cHmWpQYxnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-linux-arm64": { + "version": "1.20260708.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20260708.1.tgz", + "integrity": "sha512-VLdNYOx5Hj+9C6isy0ACWZsbMtSxex2DIJWEe7cZxUdlphZ58ZT8zxNXK8yunFiowd34hn3VwGMopdvdj8lvmA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-windows-64": { + "version": "1.20260708.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20260708.1.tgz", + "integrity": "sha512-bC/aSAwLy16Vjo24i9XU3aWH+eRgz7NeR5xPKavGbembO18ZywYTQbXh14eXtY6fAqN3RzRG8psijTdhX4xydA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16" + } + }, "node_modules/@colors/colors": { "version": "1.5.0", "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz", @@ -81,6 +170,41 @@ "node": ">=0.1.90" } }, + "node_modules/@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.9" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@cspotcode/source-map-support/node_modules/@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.11.2", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.2.tgz", + "integrity": "sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@esbuild/aix-ppc64": { "version": "0.21.5", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz", @@ -950,6 +1074,496 @@ "url": "https://github.com/sponsors/nzakas" } }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.5.tgz", + "integrity": "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.2.4" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.5.tgz", + "integrity": "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.2.4" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.4.tgz", + "integrity": "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.4.tgz", + "integrity": "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.4.tgz", + "integrity": "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.4.tgz", + "integrity": "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.2.4.tgz", + "integrity": "sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.2.4.tgz", + "integrity": "sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.2.4.tgz", + "integrity": "sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.4.tgz", + "integrity": "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.4.tgz", + "integrity": "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.4.tgz", + "integrity": "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.5.tgz", + "integrity": "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.5.tgz", + "integrity": "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.34.5.tgz", + "integrity": "sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.34.5.tgz", + "integrity": "sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.5.tgz", + "integrity": "sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.5.tgz", + "integrity": "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.2.4" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.5.tgz", + "integrity": "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.2.4" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.5.tgz", + "integrity": "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.2.4" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.34.5.tgz", + "integrity": "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.7.0" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.5.tgz", + "integrity": "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.5.tgz", + "integrity": "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.5.tgz", + "integrity": "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, "node_modules/@isaacs/cliui": { "version": "8.0.2", "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", @@ -1296,6 +1910,48 @@ "node": ">=14" } }, + "node_modules/@poppinss/colors": { + "version": "4.1.6", + "resolved": "https://registry.npmjs.org/@poppinss/colors/-/colors-4.1.6.tgz", + "integrity": "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==", + "dev": true, + "license": "MIT", + "dependencies": { + "kleur": "^4.1.5" + } + }, + "node_modules/@poppinss/dumper": { + "version": "0.6.5", + "resolved": "https://registry.npmjs.org/@poppinss/dumper/-/dumper-0.6.5.tgz", + "integrity": "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@poppinss/colors": "^4.1.5", + "@sindresorhus/is": "^7.0.2", + "supports-color": "^10.0.0" + } + }, + "node_modules/@poppinss/dumper/node_modules/supports-color": { + "version": "10.2.2", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-10.2.2.tgz", + "integrity": "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/@poppinss/exception": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@poppinss/exception/-/exception-1.2.3.tgz", + "integrity": "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==", + "dev": true, + "license": "MIT" + }, "node_modules/@rollup/rollup-android-arm-eabi": { "version": "4.62.2", "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.62.2.tgz", @@ -1646,6 +2302,26 @@ "win32" ] }, + "node_modules/@sindresorhus/is": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-7.2.0.tgz", + "integrity": "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sindresorhus/is?sponsor=1" + } + }, + "node_modules/@speed-highlight/core": { + "version": "1.2.17", + "resolved": "https://registry.npmjs.org/@speed-highlight/core/-/core-1.2.17.tgz", + "integrity": "sha512-Z92FwKpCtfaW1V0jTU/fh3QzYEZN8wDwrzRIBoADCJfn4mJCNcJN/XegifX7BDrQ8/h9Xh/JnbyMchL0FqXrkg==", + "dev": true, + "license": "CC0-1.0" + }, "node_modules/@stylistic/eslint-plugin": { "version": "5.10.0", "resolved": "https://registry.npmjs.org/@stylistic/eslint-plugin/-/eslint-plugin-5.10.0.tgz", @@ -3064,6 +3740,16 @@ "node": ">=6" } }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, "node_modules/dunder-proto": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", @@ -3155,6 +3841,16 @@ "node": ">= 0.8" } }, + "node_modules/error-stack-parser-es": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/error-stack-parser-es/-/error-stack-parser-es-1.0.5.tgz", + "integrity": "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, "node_modules/es-define-property": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", @@ -4515,6 +5211,16 @@ "json-buffer": "3.0.1" } }, + "node_modules/kleur": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", + "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/levn": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", @@ -4767,6 +5473,27 @@ "url": "https://opencollective.com/express" } }, + "node_modules/miniflare": { + "version": "4.20260708.1", + "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-4.20260708.1.tgz", + "integrity": "sha512-c94O9zRDISdqO18EHt6l0iF/fWgWt8p18PJvRsA/L/NJZ9Cfke3s/F5Blg1XXF7WDutVRzWVWy8Vy4LaT5ifsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspotcode/source-map-support": "0.8.1", + "sharp": "0.34.5", + "undici": "7.28.0", + "workerd": "1.20260708.1", + "ws": "8.21.0", + "youch": "4.1.0-beta.10" + }, + "bin": { + "miniflare": "bootstrap.js" + }, + "engines": { + "node": ">=22.0.0" + } + }, "node_modules/minimatch": { "version": "3.1.5", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", @@ -5876,6 +6603,51 @@ "dev": true, "license": "ISC" }, + "node_modules/sharp": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.5.tgz", + "integrity": "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==", + "dev": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "@img/colour": "^1.0.0", + "detect-libc": "^2.1.2", + "semver": "^7.7.3" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.34.5", + "@img/sharp-darwin-x64": "0.34.5", + "@img/sharp-libvips-darwin-arm64": "1.2.4", + "@img/sharp-libvips-darwin-x64": "1.2.4", + "@img/sharp-libvips-linux-arm": "1.2.4", + "@img/sharp-libvips-linux-arm64": "1.2.4", + "@img/sharp-libvips-linux-ppc64": "1.2.4", + "@img/sharp-libvips-linux-riscv64": "1.2.4", + "@img/sharp-libvips-linux-s390x": "1.2.4", + "@img/sharp-libvips-linux-x64": "1.2.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.2.4", + "@img/sharp-libvips-linuxmusl-x64": "1.2.4", + "@img/sharp-linux-arm": "0.34.5", + "@img/sharp-linux-arm64": "0.34.5", + "@img/sharp-linux-ppc64": "0.34.5", + "@img/sharp-linux-riscv64": "0.34.5", + "@img/sharp-linux-s390x": "0.34.5", + "@img/sharp-linux-x64": "0.34.5", + "@img/sharp-linuxmusl-arm64": "0.34.5", + "@img/sharp-linuxmusl-x64": "0.34.5", + "@img/sharp-wasm32": "0.34.5", + "@img/sharp-win32-arm64": "0.34.5", + "@img/sharp-win32-ia32": "0.34.5", + "@img/sharp-win32-x64": "0.34.5" + } + }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", @@ -7546,6 +8318,16 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/undici": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.28.0.tgz", + "integrity": "sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, "node_modules/undici-types": { "version": "5.26.5", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", @@ -7800,6 +8582,27 @@ "node": ">=0.10.0" } }, + "node_modules/workerd": { + "version": "1.20260708.1", + "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20260708.1.tgz", + "integrity": "sha512-WAK+Kt/VVCSldH2qSr8lx46XCJ4Q+bdlHNaFqUtOHthBEIB8C1N8HVW+VOLrxDoTCk0NGNv0zajnBeQK4JOB9w==", + "dev": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "bin": { + "workerd": "bin/workerd" + }, + "engines": { + "node": ">=16" + }, + "optionalDependencies": { + "@cloudflare/workerd-darwin-64": "1.20260708.1", + "@cloudflare/workerd-darwin-arm64": "1.20260708.1", + "@cloudflare/workerd-linux-64": "1.20260708.1", + "@cloudflare/workerd-linux-arm64": "1.20260708.1", + "@cloudflare/workerd-windows-64": "1.20260708.1" + } + }, "node_modules/wrap-ansi": { "version": "8.1.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", @@ -7962,6 +8765,45 @@ "funding": { "url": "https://github.com/sponsors/sindresorhus" } + }, + "node_modules/youch": { + "version": "4.1.0-beta.10", + "resolved": "https://registry.npmjs.org/youch/-/youch-4.1.0-beta.10.tgz", + "integrity": "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@poppinss/colors": "^4.1.5", + "@poppinss/dumper": "^0.6.4", + "@speed-highlight/core": "^1.2.7", + "cookie": "^1.0.2", + "youch-core": "^0.3.3" + } + }, + "node_modules/youch-core": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/youch-core/-/youch-core-0.3.3.tgz", + "integrity": "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@poppinss/exception": "^1.2.2", + "error-stack-parser-es": "^1.0.5" + } + }, + "node_modules/youch/node_modules/cookie": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", + "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } } } } diff --git a/package.json b/package.json index 6cd1cc4..b17be00 100644 --- a/package.json +++ b/package.json @@ -81,6 +81,7 @@ "test:dev": "vitest", "test:deno": "deno test --allow-net --allow-read --no-check test/deno/", "test:bun": "bun test test/bun/", + "test:edge": "tsx test/edge/run.ts", "typecheck": "tsc --noEmit -p tsconfig.json", "typecheck:bench": "tsc --noEmit -p bench/tsconfig.json", "lint": "eslint src", @@ -130,6 +131,7 @@ "express": "^5.2.1", "fastify": "^5.10.0", "graphql": "^16.9.0", + "miniflare": "^4.20260708.1", "prettier": "^3.9.4", "rxjs": "^7.8.2", "tsup": "^8.5.1", diff --git a/test/edge/run.ts b/test/edge/run.ts new file mode 100644 index 0000000..8ebd977 --- /dev/null +++ b/test/edge/run.ts @@ -0,0 +1,124 @@ +// Real Miniflare (workerd) integration test for edgeHandler: bundles test/edge/worker.ts +// for the Cloudflare Workers runtime and boots it in the actual workerd engine (via the +// `miniflare` npm package — no CF account/deploy needed), then round-trips HTTP + WS +// through the real graph. +// +// Run with: npm run test:edge +// +// NODEJS_COMPAT FRICTION (found by running this against real Miniflare — see +// project-docs/.superpowers/sdd/task-2-report.md for full detail): the barrel +// (`src/index.ts` -> `createApp` -> `src/app/index.ts` -> `src/http/server.ts`) statically +// imports Node's `http`/`https` as VALUES (for the Node `listen()`/`http.createServer` path), +// even though `edgeHandler`'s request path never touches them. workerd's `nodejs_compat` +// genuinely does NOT implement `node:http`/`node:https` (confirmed in isolation: `node:crypto`, +// `node:stream`, `node:net`, `node:tls`, `node:events`, `node:util`, `node:buffer` all load +// fine under the same flags/compat date; only `http`/`https` fail with +// "Uncaught Error: No such module 'node:http'" at worker LOAD time, regardless of +// compatibilityDate 2023-05-01..2024-11-01 or alias tweaks) — this is a real platform gap, +// not a bundler misconfiguration. +// +// To let this test actually exercise edgeHandler's real HTTP+WS behavior on workerd (rather +// than stopping at "the barrel doesn't load"), the two Node-only server builtins are stubbed +// at BUNDLE TIME (esbuild plugin below) with inert objects whose `createServer` throws if +// ever called. This only satisfies static module resolution for code edgeHandler never +// executes; it does not change src/edge.ts or core, and does not touch the WS assertion. +// It is a TEST-ONLY workaround, not proof that `node:http`/`node:https` work under workerd — +// they don't. See the report for the recommended follow-up (lazy-defer those imports behind +// `listen()` in src/app/index.ts / src/http/server.ts so the barrel is edge-safe without a +// bundle-time shim). +import { strict as assert } from 'node:assert'; +import { build, type Plugin } from 'esbuild'; +import { Miniflare } from 'miniflare'; + +const BUNDLE = 'test/edge/_worker.mjs'; + +// Stubs Node's `http`/`https` (unsupported by workerd's nodejs_compat) with inert modules. +// edgeHandler's request path never calls these; they exist in the barrel only for the Node +// `listen()` path. Any call would throw clearly rather than resolve to a wrong behavior. +const stubUnsupportedNodeServerModules: Plugin = { + name: 'stub-unsupported-node-server-modules', + setup(pluginBuild) { + pluginBuild.onResolve({ filter: /^(http|https)$/ }, (args) => ({ + path: args.path, + namespace: 'edge-test-stub', + })); + pluginBuild.onLoad({ filter: /.*/, namespace: 'edge-test-stub' }, (args) => ({ + contents: ` + function createServer() { + throw new Error(${JSON.stringify(args.path)} + '.createServer is not available in the edge runtime (no nodejs_compat support; edgeHandler never calls it)'); + } + export default { createServer }; + export { createServer }; + `, + loader: 'js', + })); + }, +}; + +async function main() { + // Bundle the worker for workerd: ESM, Node builtins left external + aliased to node:* + // so workerd's nodejs_compat provides them (not esbuild) — except http/https, which + // workerd genuinely doesn't implement (see comment above); those are stubbed instead. + await build({ + entryPoints: ['test/edge/worker.ts'], + bundle: true, + format: 'esm', + outfile: BUNDLE, + platform: 'browser', // workerd is not node; keep esbuild from injecting node shims + target: 'esnext', + // Leave Node builtins for workerd's nodejs_compat to resolve: + external: ['node:*'], + plugins: [stubUnsupportedNodeServerModules], + alias: { + crypto: 'node:crypto', + stream: 'node:stream', + zlib: 'node:zlib', + buffer: 'node:buffer', + events: 'node:events', + net: 'node:net', + tls: 'node:tls', + util: 'node:util', + }, + }); + + const mf = new Miniflare({ + modules: true, + scriptPath: BUNDLE, + compatibilityDate: '2024-11-01', + compatibilityFlags: ['nodejs_compat'], + }); + + try { + // HTTP + const httpRes = await mf.dispatchFetch('http://localhost/rt/hello'); + assert.equal(httpRes.status, 200); + assert.deepEqual(await httpRes.json(), { ok: true }); + + // WebSocket + const wsRes = await mf.dispatchFetch('http://localhost/rt/echo', { + headers: { Upgrade: 'websocket' }, + }); + assert.equal(wsRes.status, 101); + const ws = wsRes.webSocket; + assert.ok(ws, 'expected a client webSocket on the 101 response'); + ws.accept(); + const got = await new Promise((resolve, reject) => { + ws.addEventListener('message', (e: { data: unknown }) => { + resolve(String(e.data)); + ws.close(); + }); + ws.addEventListener('error', () => reject(new Error('ws error'))); + ws.send('hi'); + }); + assert.equal(got, 'echo:hi'); + + console.log('edge (workerd via miniflare): HTTP 200 + WS echo:hi — PASS'); + } finally { + await mf.dispose(); + } +} + +main().catch((err) => { + console.error(err); + process.exit(1); +}); diff --git a/test/edge/worker.ts b/test/edge/worker.ts new file mode 100644 index 0000000..33753b1 --- /dev/null +++ b/test/edge/worker.ts @@ -0,0 +1,27 @@ +// Worker entry for the real workerd (Miniflare) integration test. +// Mirrors test/deno/ws.test.ts's graph so HTTP + WebSocket behavior is proven +// identically across runtimes. Run via `npm run test:edge` (see test/edge/run.ts). +import { createApp, Route, Get, Ws, ctx, Module } from '../../src/index'; +import { edgeHandler } from '../../src/edge'; + +@Route('/rt') +class Rt { + @Get('/hello') + hello() { + return { ok: true }; + } + + @Ws('/echo') + echo(@ctx() { inbound }: any) { + return (async function* () { + for await (const msg of inbound) yield `echo:${msg}`; + })(); + } +} + +@Module({ mountpoint: '/', controllers: [Rt] }) +class M {} + +const app = createApp({ modules: [M] }); + +export default { fetch: edgeHandler(app) }; diff --git a/tsconfig.json b/tsconfig.json index 6dff172..8d268e0 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -15,5 +15,5 @@ "forceConsistentCasingInFileNames": true }, "include": ["src", "test", "example"], - "exclude": ["test/deno", "test/bun"] + "exclude": ["test/deno", "test/bun", "test/edge"] } diff --git a/vitest.config.ts b/vitest.config.ts index 48255af..32a48dc 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -7,6 +7,6 @@ export default defineConfig({ include: ['test/**/*.test.ts'], // test/deno/** holds Deno.test files run separately via `npm run test:deno`; // they use `npm:`/`jsr:` specifiers vitest can't resolve. - exclude: [...configDefaults.exclude, 'test/deno/**', 'test/bun/**'], + exclude: [...configDefaults.exclude, 'test/deno/**', 'test/bun/**', 'test/edge/**'], }, }); From 70925035d7ed7608bc4527ff8337ea22b05486c9 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 23:40:28 -0500 Subject: [PATCH 106/139] fix(http): lazy-load http/https so createApp is edge/workerd-safe; drop test shim Signed-off-by: Diego Resendez --- src/app/index.ts | 2 +- src/http/request.ts | 2 +- src/http/server.ts | 15 +++++++--- src/http/stream.ts | 2 +- src/http/types.ts | 2 +- src/http/ws.ts | 2 +- test/edge/run.ts | 72 ++++++++++++++------------------------------- 7 files changed, 38 insertions(+), 59 deletions(-) diff --git a/src/app/index.ts b/src/app/index.ts index 6976798..0d1c0b7 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -1,4 +1,4 @@ -import http from 'http'; +import type http from 'http'; import { Bus } from '../bus'; import { Container } from '../container'; import { topoSort, subgraphFor, GraphNode, nearest } from '../graph'; diff --git a/src/http/request.ts b/src/http/request.ts index 2eef0cd..b6fc751 100644 --- a/src/http/request.ts +++ b/src/http/request.ts @@ -1,4 +1,4 @@ -import http from 'http'; +import type http from 'http'; import { HttpError } from '../signals'; /** Reads the full request body, enforcing the max-bytes ceiling (throws 413 if exceeded). */ diff --git a/src/http/server.ts b/src/http/server.ts index 27ec76a..b54f2a4 100644 --- a/src/http/server.ts +++ b/src/http/server.ts @@ -1,5 +1,5 @@ -import http from 'http'; -import https from 'https'; +import type http from 'http'; +import type https from 'https'; import { renderError, type ErrorRequest } from '../transformers'; import { isHttpError, HttpError } from '../signals'; import type { Bus } from '../bus'; @@ -48,10 +48,17 @@ export function createHttpServer( const trustProxy = opts?.trustProxy ?? false; const handler = createRequestHandler({ routes, bus, opts, maxBody, trustProxy }); + // Node http/https are loaded lazily so importing createApp stays edge/workerd-safe + // (workerd's nodejs_compat provides no node:http/node:https). This path only runs under listen(). + // eslint-disable-next-line @typescript-eslint/no-require-imports + const nodeHttp = require('http') as typeof import('http'); + // eslint-disable-next-line @typescript-eslint/no-require-imports + const nodeHttps = require('https') as typeof import('https'); + // runtime-compatible; only @types differ (https.Server lacks the http-only timeout props) const server: http.Server = (opts?.tls - ? https.createServer(opts.tls as https.ServerOptions, handler) - : http.createServer(handler)) as unknown as http.Server; + ? nodeHttps.createServer(opts.tls as https.ServerOptions, handler) + : nodeHttp.createServer(handler)) as unknown as http.Server; server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000; server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000; server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000; diff --git a/src/http/stream.ts b/src/http/stream.ts index 1239459..9532fa2 100644 --- a/src/http/stream.ts +++ b/src/http/stream.ts @@ -1,4 +1,4 @@ -import http from 'http'; +import type http from 'http'; import { once } from 'events'; import { sseEncoder, ndjsonEncoder, StreamEncoder } from '../encoders'; import type { Transport } from '../metadata'; diff --git a/src/http/types.ts b/src/http/types.ts index ddd02db..a12c1e4 100644 --- a/src/http/types.ts +++ b/src/http/types.ts @@ -1,4 +1,4 @@ -import http from 'http'; +import type http from 'http'; import type { Transport } from '../metadata'; import type { PipelineResult } from '../pipeline'; import type { ErrorRenderer } from '../transformers'; diff --git a/src/http/ws.ts b/src/http/ws.ts index 5f0ae62..2f34b8a 100644 --- a/src/http/ws.ts +++ b/src/http/ws.ts @@ -1,4 +1,4 @@ -import http from 'http'; +import type http from 'http'; import { channel } from '../channel'; import type { Bus } from '../bus'; import { runWsConnection, matchWsRoute, type WsSocket, type WsRequest } from './ws-core'; diff --git a/test/edge/run.ts b/test/edge/run.ts index 8ebd977..58dc066 100644 --- a/test/edge/run.ts +++ b/test/edge/run.ts @@ -5,60 +5,32 @@ // // Run with: npm run test:edge // -// NODEJS_COMPAT FRICTION (found by running this against real Miniflare — see -// project-docs/.superpowers/sdd/task-2-report.md for full detail): the barrel -// (`src/index.ts` -> `createApp` -> `src/app/index.ts` -> `src/http/server.ts`) statically -// imports Node's `http`/`https` as VALUES (for the Node `listen()`/`http.createServer` path), -// even though `edgeHandler`'s request path never touches them. workerd's `nodejs_compat` -// genuinely does NOT implement `node:http`/`node:https` (confirmed in isolation: `node:crypto`, -// `node:stream`, `node:net`, `node:tls`, `node:events`, `node:util`, `node:buffer` all load -// fine under the same flags/compat date; only `http`/`https` fail with -// "Uncaught Error: No such module 'node:http'" at worker LOAD time, regardless of -// compatibilityDate 2023-05-01..2024-11-01 or alias tweaks) — this is a real platform gap, -// not a bundler misconfiguration. -// -// To let this test actually exercise edgeHandler's real HTTP+WS behavior on workerd (rather -// than stopping at "the barrel doesn't load"), the two Node-only server builtins are stubbed -// at BUNDLE TIME (esbuild plugin below) with inert objects whose `createServer` throws if -// ever called. This only satisfies static module resolution for code edgeHandler never -// executes; it does not change src/edge.ts or core, and does not touch the WS assertion. -// It is a TEST-ONLY workaround, not proof that `node:http`/`node:https` work under workerd — -// they don't. See the report for the recommended follow-up (lazy-defer those imports behind -// `listen()` in src/app/index.ts / src/http/server.ts so the barrel is edge-safe without a -// bundle-time shim). +// NODEJS_COMPAT: workerd's `nodejs_compat` genuinely does NOT implement `node:http`/ +// `node:https` (confirmed in isolation: `node:crypto`, `node:stream`, `node:net`, `node:tls`, +// `node:events`, `node:util`, `node:buffer` all load fine under the same flags/compat date; +// only `http`/`https` fail with "Uncaught Error: No such module 'node:http'" at worker LOAD +// time) — a real platform gap, not a bundler misconfiguration. The barrel used to statically +// VALUE-import `http`/`https` for the Node `listen()` path even though `edgeHandler` never +// touches them, which broke worker load with no shim. The fix (see src/http/server.ts, +// src/app/index.ts, and the other src/http/*.ts files) converts every `http`/`https` import +// to `import type` (zero runtime code) and lazy-`require()`s them only inside +// `createHttpServer`, which the edge path never calls. That means the real barrel now loads +// on workerd with no test-time stub — this run exercises it as-is. import { strict as assert } from 'node:assert'; -import { build, type Plugin } from 'esbuild'; +import { build } from 'esbuild'; import { Miniflare } from 'miniflare'; const BUNDLE = 'test/edge/_worker.mjs'; -// Stubs Node's `http`/`https` (unsupported by workerd's nodejs_compat) with inert modules. -// edgeHandler's request path never calls these; they exist in the barrel only for the Node -// `listen()` path. Any call would throw clearly rather than resolve to a wrong behavior. -const stubUnsupportedNodeServerModules: Plugin = { - name: 'stub-unsupported-node-server-modules', - setup(pluginBuild) { - pluginBuild.onResolve({ filter: /^(http|https)$/ }, (args) => ({ - path: args.path, - namespace: 'edge-test-stub', - })); - pluginBuild.onLoad({ filter: /.*/, namespace: 'edge-test-stub' }, (args) => ({ - contents: ` - function createServer() { - throw new Error(${JSON.stringify(args.path)} + '.createServer is not available in the edge runtime (no nodejs_compat support; edgeHandler never calls it)'); - } - export default { createServer }; - export { createServer }; - `, - loader: 'js', - })); - }, -}; - async function main() { // Bundle the worker for workerd: ESM, Node builtins left external + aliased to node:* - // so workerd's nodejs_compat provides them (not esbuild) — except http/https, which - // workerd genuinely doesn't implement (see comment above); those are stubbed instead. + // so workerd's nodejs_compat provides them (not esbuild). `http`/`https` are no longer + // imported as VALUES by the barrel at module-eval time (see comment above) — they're now + // `import type` (erased) plus a lazy `require()` reached only from `createHttpServer`, + // which `edgeHandler` never calls. esbuild still needs a resolution for that bare + // `require('http')`/`require('https')` text even though it's dead code on this path, so + // they're marked external here (left unresolved, exactly like the `node:*` builtins) rather + // than stubbed — no fake implementation is provided, and the real barrel is what's tested. await build({ entryPoints: ['test/edge/worker.ts'], bundle: true, @@ -66,9 +38,9 @@ async function main() { outfile: BUNDLE, platform: 'browser', // workerd is not node; keep esbuild from injecting node shims target: 'esnext', - // Leave Node builtins for workerd's nodejs_compat to resolve: - external: ['node:*'], - plugins: [stubUnsupportedNodeServerModules], + // Leave Node builtins for workerd's nodejs_compat to resolve; http/https are external + // too (unresolved, never called by edgeHandler) since workerd has no node:http/https. + external: ['node:*', 'http', 'https'], alias: { crypto: 'node:crypto', stream: 'node:stream', From cb4ecd68018bddc6e056d310a729f792de4665b0 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 23:45:27 -0500 Subject: [PATCH 107/139] =?UTF-8?q?docs:=20edgeHandler=20=E2=80=94=20WebSo?= =?UTF-8?q?cket=20on=20Cloudflare=20Workers=20/=20edge?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Diego Resendez --- CHANGELOG.md | 1 + website/src/content/docs/guides/runtimes.md | 46 ++++++++++++++++++--- 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0efc786..45124f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ green-tea uses calendar versioning: `YY.MM.PATCH`. (WebSocket and mesh remain Node-only). - **Deno adapter** (`@green-tea/core/deno`): `serveDeno(app)` runs HTTP + SSE + WebSocket on Deno. - **Bun adapter** (`@green-tea/core/bun`): `serveBun(app)` runs HTTP + SSE + WebSocket on Bun, reusing the neutral `app.upgrade` / `WsSocket` capability. WebSocket, rooms, and channels behave identically to Node and Deno. +- **Cloudflare Workers / edge adapter** (`@green-tea/core/edge`): `edgeHandler(app)` runs HTTP + SSE + WebSocket on workerd, reusing the neutral `app.upgrade` / `WsSocket` capability. Requires the `nodejs_compat` compatibility flag. Green Tea now runs on Node, Deno, Bun, and the edge — with identical WebSocket, rooms, and channel behaviour on all four. - **`app.upgrade(request, socket)`**: neutral WebSocket entry point for non-Node runtimes, built on a shared `WsSocket` capability. WebSocket logic is now runtime-agnostic (`src/http/ws-core.ts`). ### Changed diff --git a/website/src/content/docs/guides/runtimes.md b/website/src/content/docs/guides/runtimes.md index 7dd7470..c1bb622 100644 --- a/website/src/content/docs/guides/runtimes.md +++ b/website/src/content/docs/guides/runtimes.md @@ -25,9 +25,10 @@ export default { fetch: app.fetch }; **Node is the reference implementation** — every runtime returns the same status, headers, and body for the same request (enforced by a parity test suite). -**Not yet on edge runtimes:** WebSocket (`@Ws`) and mesh — still Node-only there; Deno and Bun -now have full WebSocket support via `serveDeno` and `serveBun` (see below). `app.listen()` and -TLS remain Node-only; on Deno/Bun/edge you get `app.fetch`. +**All four runtimes now have full WebSocket support:** Node, Deno, and Bun via `serveDeno` / +`serveBun`, and Cloudflare Workers / edge via `edgeHandler` (see below) — same graph, same +`@Ws` handlers, same rooms/channels everywhere. `app.listen()`, TLS, per-request timeouts, +and mesh remain Node-only; on Deno/Bun/edge you get `app.fetch` + the runtime's adapter. **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 @@ -54,8 +55,8 @@ run on Node. Behaviour matches the Node reference. **Advanced:** `app.upgrade(request, socket)` is the neutral primitive `serveDeno` uses. Any runtime can build a `WsSocket` capability (`inbound`, `abort`, `isOpen`, `send`, -`close`, `terminate`) and drive the graph — `serveBun` builds on the same primitive -(see below), and this is how future edge support will land. +`close`, `terminate`) and drive the graph — `serveBun` and `edgeHandler` build on the +same primitive (see below). **Still Node-only:** `app.listen()`, TLS, per-request timeouts, and mesh. On Deno you get `app.fetch` + `serveDeno`. @@ -81,3 +82,38 @@ run on Node and Deno. Behaviour matches the Node reference. **Still Node-only:** `app.listen()`, TLS, per-request timeouts, and mesh. On Bun you get `app.fetch` + `serveBun`. + +## Cloudflare Workers / edge + +`app.fetch` covers HTTP + SSE on every runtime. WebSocket needs a runtime-specific +upgrade, so Cloudflare Workers get a dedicated adapter at `@green-tea/core/edge`: + +```ts +import { createApp } from '@green-tea/core'; +import { edgeHandler } from '@green-tea/core/edge'; + +const app = createApp({ modules: [ChatModule] }); + +export default { fetch: edgeHandler(app) }; +``` + +`edgeHandler` routes normal requests through `app.fetch` and WebSocket upgrades through +`WebSocketPair` and `app.upgrade` — the same neutral primitive `serveDeno` and `serveBun` +use. Same graph, same `@Ws` handlers, same rooms/channels as Node/Deno/Bun; behaviour +matches the Node reference; validated on real workerd (Miniflare). + +**Requirement:** the Worker must enable the `nodejs_compat` compatibility flag — +`wrangler.toml`: + +```toml +compatibility_flags = ["nodejs_compat"] +compatibility_date = "2024-09-23" # or later +``` + +Green Tea's core statically imports Node built-ins that workerd only provides under +this flag; without it, the Worker fails to load. + +**Still Node-only:** `app.listen()`, TLS, per-request timeouts, and mesh. Cloudflare's +Durable Objects and WebSocket Hibernation are **not** used — `edgeHandler` accepts +WebSockets with the standard `WebSocketPair` model, so a Worker holds the connection +open for its lifetime rather than hibernating between messages. From df13a62d9306eac8ac23cd626aaf4b9826000d0c Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 10 Jul 2026 00:10:54 -0500 Subject: [PATCH 108/139] fix(app): serve /__graph__ and /__openapi__ over app.fetch (dev tools on all runtimes) Signed-off-by: Diego Resendez --- CHANGELOG.md | 5 +++++ src/app/index.ts | 17 +++++++++++++---- test/app.test.ts | 24 ++++++++++++++++++++++++ 3 files changed, 42 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 45124f7..82e9b68 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,11 @@ green-tea uses calendar versioning: `YY.MM.PATCH`. - **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`). +### Fixed +- The opt-in dev routes `/__graph__` (graph viewer) and `/__openapi__` are now + served over `app.fetch` too, so they work on every runtime (Deno/Bun/edge), + not only the Node `app.listen()` path. + ### Changed - App-scope providers now boot exactly once (memoized): a second `app.listen()` call no longer re-runs provider factories or their side effects. diff --git a/src/app/index.ts b/src/app/index.ts index 0d1c0b7..4a00cc0 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -119,6 +119,15 @@ export function createApp(opts: { info, ); + // Dev-only introspection routes (opt-in). Shared by BOTH listen() and app.fetch so the + // graph viewer + OpenAPI doc are served on every runtime (Node/Deno/Bun/edge), not Node alone. + const devRoutes = (): RouteDef[] => { + const routes: RouteDef[] = []; + if (opts.devGraph) routes.push(devGraphRoute(graph)); + if (opts.devOpenapi) routes.push(openApiRoute(openapi)); + return routes; + }; + const providedSeed = (plan: RoutePlan) => seedProviders(container, plan); const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan); @@ -147,6 +156,7 @@ export function createApp(opts: { { providedSeed, planSteps, bus, onError: opts.onError }, fetchOpts, bootAppProviders, + devRoutes, ); const upgradeFn = buildAppUpgrade( () => booted, @@ -179,9 +189,7 @@ export function createApp(opts: { deps, }); - const httpRoutes = buildHttpRoutes(routePlans, remoteRoutes, deps); - if (opts.devGraph) httpRoutes.push(devGraphRoute(graph)); - if (opts.devOpenapi) httpRoutes.push(openApiRoute(openapi)); + const httpRoutes = [...buildHttpRoutes(routePlans, remoteRoutes, deps), ...devRoutes()]; const wsRoutes = buildWsRoutes(routePlans, deps); server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { @@ -638,13 +646,14 @@ function buildAppFetch( deps: PipelineDeps, fetchOpts: HttpOptions, ensureBooted: () => Promise, + devRoutes: () => RouteDef[], ): (request: Request) => Promise { let handler: ((request: Request) => Promise) | undefined; return async (request: Request): Promise => { if (!handler) { if (!getBooted()) throw new Error('fetch() unavailable before listen() for mesh apps'); - handler = buildFetch(buildHttpRoutes(routePlans, [], deps), fetchOpts); + handler = buildFetch([...buildHttpRoutes(routePlans, [], deps), ...devRoutes()], fetchOpts); } await ensureBooted(); // idempotent: no-op if listen() already booted the providers diff --git a/test/app.test.ts b/test/app.test.ts index 4b52a50..fc944ad 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -398,6 +398,30 @@ describe('devGraph endpoint', () => { expect(res.status).toBe(404); s.close(); }); + + it('serves /__graph__ and /__openapi__ over app.fetch too (runtime-agnostic dev tools)', async () => { + @Route('/u') + class Ctl { + @Get('/me') me() { + return { ok: 1 }; + } + } + @Module({ mountpoint: '/api', controllers: [Ctl] }) + class M {} + const app = createApp({ modules: [M], devGraph: true, devOpenapi: true }); + + const graph = await app.fetch(new Request('http://x/__graph__')); + expect(graph.status).toBe(200); + expect(await graph.text()).toContain('cytoscape'); + + const openapi = await app.fetch(new Request('http://x/__openapi__')); + expect(openapi.status).toBe(200); + expect(((await openapi.json()) as { openapi: string }).openapi).toBe('3.1.0'); + + // still absent when the flags are off, on the fetch path too + const off = createApp({ modules: [M] }); + expect((await off.fetch(new Request('http://x/__graph__'))).status).toBe(404); + }); }); describe('graceful shutdown', () => { From da5cc936a37b10a79d0ec75f27ea170a259faf88 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 10 Jul 2026 14:26:57 -0500 Subject: [PATCH 109/139] feat(views): built-in template engine + content-type map Signed-off-by: Diego Resendez --- src/index.ts | 3 +++ src/views.ts | 46 ++++++++++++++++++++++++++++++++++++++++++++++ test/views.test.ts | 28 ++++++++++++++++++++++++++++ 3 files changed, 77 insertions(+) create mode 100644 src/views.ts create mode 100644 test/views.test.ts diff --git a/src/index.ts b/src/index.ts index eb4c42a..bc8a7ac 100644 --- a/src/index.ts +++ b/src/index.ts @@ -18,6 +18,9 @@ export type { GraphView } from './graph-viz'; export { buildOpenApi } from './openapi'; export type { OpenApiDoc, OpenApiInfo, OpenApiRoute } from './openapi'; +// Views +export { render } from './views'; + // Routing & decorators export { Provider, Step, Route, Get, Module, Transformer, Sse, Ws, Stream, Post, Put, Patch, Delete } from './metadata'; export type { Transport, HttpMethod } from './metadata'; diff --git a/src/views.ts b/src/views.ts new file mode 100644 index 0000000..3f6aa21 --- /dev/null +++ b/src/views.ts @@ -0,0 +1,46 @@ +// src/views.ts — HTML views: built-in templating, content-type map, and boot-time builders. +// fs/path are lazy-required inside functions so the barrel stays edge-loadable (workerd has no filesystem). + +/** Escape the five HTML-significant characters so interpolated data can't inject markup. */ +export function escapeHtml(s: string): string { + const map: Record = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }; + return s.replace(/[&<>"']/g, (c) => map[c]); +} + +function stringify(v: unknown): string { + return v === null || v === undefined ? '' : String(v); +} + +/** + * Minimal built-in template engine: `{{ key }}` interpolates HTML-escaped, `{{{ key }}}` raw, + * `{{ a.b }}` walks nested keys, a missing key renders empty. No loops/conditionals/partials. + */ +export function render(source: string, data: unknown): string { + const lookup = (key: string): unknown => + key.split('.').reduce((obj, k) => (obj === null || obj === undefined ? undefined : obj[k]), data); + return source + .replace(/\{\{\{\s*([\w.]+)\s*\}\}\}/g, (_, key) => stringify(lookup(key))) + .replace(/\{\{\s*([\w.]+)\s*\}\}/g, (_, key) => escapeHtml(stringify(lookup(key)))); +} + +const CONTENT_TYPES: Record = { + '.html': 'text/html; charset=utf-8', + '.css': 'text/css; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.mjs': 'text/javascript; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.svg': 'image/svg+xml', + '.png': 'image/png', + '.jpg': 'image/jpeg', + '.jpeg': 'image/jpeg', + '.gif': 'image/gif', + '.webp': 'image/webp', + '.ico': 'image/x-icon', + '.woff2': 'font/woff2', + '.txt': 'text/plain; charset=utf-8', +}; + +/** Content-type for a file extension (case-insensitive, leading dot); unknown → `application/octet-stream`. */ +export function contentTypeFor(ext: string): string { + return CONTENT_TYPES[ext.toLowerCase()] ?? 'application/octet-stream'; +} diff --git a/test/views.test.ts b/test/views.test.ts new file mode 100644 index 0000000..2523385 --- /dev/null +++ b/test/views.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest'; +import { render, escapeHtml, contentTypeFor } from '../src/views'; + +describe('escapeHtml', () => { + it('escapes the five HTML-significant characters', () => { + expect(escapeHtml(`&'`)).toBe('<a href="x">&''); + }); +}); + +describe('render', () => { + it('interpolates and HTML-escapes {{ x }} by default', () => { + expect(render('

{{ name }}

', { name: 'hi' })).toBe('

<b>hi</b>

'); + }); + it('leaves {{{ x }}} raw (unescaped)', () => { + expect(render('{{{ html }}}', { html: 'hi' })).toBe('hi'); + }); + it('resolves nested keys and renders missing keys as empty', () => { + expect(render('{{ user.name }}|{{ nope }}', { user: { name: 'Diego' } })).toBe('Diego|'); + }); +}); + +describe('contentTypeFor', () => { + it('maps known extensions and defaults unknown to octet-stream', () => { + expect(contentTypeFor('.css')).toBe('text/css; charset=utf-8'); + expect(contentTypeFor('.PNG')).toBe('image/png'); + expect(contentTypeFor('.xyz')).toBe('application/octet-stream'); + }); +}); From e1a2c3253b3c4be21aa7485b1cb1429076aa7e6b Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 10 Jul 2026 14:31:12 -0500 Subject: [PATCH 110/139] feat(views): @Html decorator and metadata Signed-off-by: Diego Resendez --- src/index.ts | 17 ++++++++++++++++- src/metadata.ts | 35 +++++++++++++++++++++++++++++++++++ test/metadata.test.ts | 21 +++++++++++++++++++++ 3 files changed, 72 insertions(+), 1 deletion(-) diff --git a/src/index.ts b/src/index.ts index bc8a7ac..de7e9c9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -22,7 +22,22 @@ export type { OpenApiDoc, OpenApiInfo, OpenApiRoute } from './openapi'; export { render } from './views'; // Routing & decorators -export { Provider, Step, Route, Get, Module, Transformer, Sse, Ws, Stream, Post, Put, Patch, Delete } from './metadata'; +export { + Provider, + Step, + Route, + Get, + Module, + Transformer, + Sse, + Ws, + Stream, + Post, + Put, + Patch, + Delete, + Html, +} from './metadata'; export type { Transport, HttpMethod } from './metadata'; export type { Plugin } from './plugin'; diff --git a/src/metadata.ts b/src/metadata.ts index 2bcab34..530dcff 100644 --- a/src/metadata.ts +++ b/src/metadata.ts @@ -5,6 +5,11 @@ export type Ctor = new (...args: any[]) => any; /** Serializes a handler's return value into an HTTP response envelope. */ export type TransformerFn = (value: unknown) => { status?: number; headers?: Record; body: string }; +/** Metadata attached by `@Html`: optional file path and whether it is a template. */ +export interface HtmlMeta { + path?: string; + template?: boolean; +} /** Metadata attached by `@Provider`: what it provides, what it needs, and its visibility. */ export interface ProviderMeta { provides: string; @@ -49,6 +54,7 @@ const K = { routes: Symbol('gt:routes'), module: Symbol('gt:module'), transformer: Symbol('gt:transformer'), + html: Symbol('gt:html'), }; /** Marks a class as a provider: a lazily-built dependency addressable by its `provides` key. */ @@ -147,6 +153,35 @@ export function Module(opts: ModuleOptions): ClassDecorator { }; } +/** + * Marks a buffered GET/POST handler as serving HTML. Bare `@Html` sends the handler's string return as + * `text/html`. `@Html('file.html')` serves that file (return ignored). `@Html('file.html', { template: true })` + * renders the file with the handler's returned data. Placement is validated at boot (buffered GET/POST only). + */ +export function Html(path: string, opts?: { template?: boolean }): MethodDecorator; +export function Html(target: object, propertyKey: string | symbol): void; + +export function Html(a: unknown, b?: unknown): MethodDecorator | void { + if (typeof a !== 'string') { + // Bare usage: TS calls (prototype, propertyKey, descriptor?). + Reflect.defineMetadata(K.html, {}, (a as { constructor: Ctor }).constructor, String(b)); + return; + } + + const path = a; + const opts = b as { template?: boolean } | undefined; + + return (target, propertyKey) => { + const meta: HtmlMeta = { path, template: opts?.template }; + Reflect.defineMetadata(K.html, meta, (target as { constructor: Ctor }).constructor, String(propertyKey)); + }; +} + +/** Reads the `@Html` metadata registered for a handler method, if any. */ +export function getHtmlMeta(cls: Ctor, methodName: string): HtmlMeta | undefined { + return Reflect.getMetadata(K.html, cls, methodName); +} + /** Reads the `@Provider` metadata off a class, if any. */ export function getProviderMeta(cls: Ctor): ProviderMeta | undefined { return Reflect.getMetadata(K.provider, cls); diff --git a/test/metadata.test.ts b/test/metadata.test.ts index 300d811..857d40f 100644 --- a/test/metadata.test.ts +++ b/test/metadata.test.ts @@ -74,3 +74,24 @@ describe('mesh export flags', () => { expect(byName.priv.export).toBe(false); }); }); + +import { Html, getHtmlMeta } from '../src/metadata'; + +describe('@Html', () => { + it('records empty meta for bare @Html', () => { + class A { @Html m() { return ''; } } + expect(getHtmlMeta(A, 'm')).toEqual({}); + }); + it('records path and template for called @Html', () => { + class B { + @Html('views/x.html') a() {} + @Html('views/y.html', { template: true }) c() { return {}; } + } + expect(getHtmlMeta(B, 'a')).toEqual({ path: 'views/x.html', template: undefined }); + expect(getHtmlMeta(B, 'c')).toEqual({ path: 'views/y.html', template: true }); + }); + it('returns undefined when @Html is absent', () => { + class C { m() {} } + expect(getHtmlMeta(C, 'm')).toBeUndefined(); + }); +}); From b8ebb9d04b91f84ee39091a0dd20af27d8ce0e3f Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 10 Jul 2026 14:36:40 -0500 Subject: [PATCH 111/139] feat(views): @Html string/file/template modes with boot validation Signed-off-by: Diego Resendez --- src/app/index.ts | 63 +++++++++++++++++++++++++++++++++++++---- src/views.ts | 47 ++++++++++++++++++++++++++++++ test/views-html.test.ts | 59 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 163 insertions(+), 6 deletions(-) create mode 100644 test/views-html.test.ts diff --git a/src/app/index.ts b/src/app/index.ts index 4a00cc0..27b7c2e 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -11,7 +11,19 @@ import { matchWsRoute, runWsConnection, type WsRequest, type WsSocket } from '.. import { isAsyncIterable } from '../channel'; import { JsonTransformer, type ErrorRenderer } from '../transformers'; import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin'; -import { Ctor, getModuleMeta, getProviderMeta, getStepMeta, getRoutes, getTransformer, joinPath } from '../metadata'; +import { + Ctor, + getModuleMeta, + getProviderMeta, + getStepMeta, + getRoutes, + getTransformer, + getHtmlMeta, + joinPath, + type RouteMeta, + type TransformerFn, +} from '../metadata'; +import { buildHtmlTransformer, type ViewsContext } from '../views'; import { getArgs, getHandlerNeeds, resolveArgs } from '../params'; import { buildOpenApi, type OpenApiInfo } from '../openapi'; import { connectLink, type Link } from '../mesh/link'; @@ -69,6 +81,10 @@ export function createApp(opts: { bodyDuplicates?: 'array' | 'last'; /** Render errors your own way (HTML, custom JSON, …); return a response or undefined to fall back to JSON. */ onError?: ErrorRenderer; + /** Base directory `@Html('file.html')` paths resolve against (default: `process.cwd()`). */ + views?: string; + /** Bring-your-own template engine for `@Html(..., { template: true })`; defaults to the built-in `render`. */ + viewEngine?: (source: string, data: unknown) => string; /** Opt in to alpha features whose API may still change. Currently gates `mesh`. */ experimental?: boolean; }): App { @@ -86,7 +102,8 @@ export function createApp(opts: { const degradedProviders: string[] = []; // optional providers that failed to boot (running degraded) // Collect declarations from modules, then splice in plugin- and built-in-provided nodes. - const registry = collectModules(opts.modules); + const viewsCtx: ViewsContext = { views: opts.views, viewEngine: opts.viewEngine }; + const registry = collectModules(opts.modules, viewsCtx); const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry; mountPlugins(opts.plugins, bus, registry); provideBuiltins(registry); @@ -278,7 +295,13 @@ function collectSteps(steps: Ctor[], origin: string, registry: Registry): void { } /** Registers each `@Route` handler on a module's controllers as a {@link RoutePlan}. */ -function collectControllers(controllers: Ctor[], mountpoint: string, origin: string, registry: Registry): void { +function collectControllers( + controllers: Ctor[], + mountpoint: string, + origin: string, + registry: Registry, + viewsCtx: ViewsContext, +): void { for (const ControllerClass of controllers) { for (const route of getRoutes(ControllerClass)) { const instance: any = new ControllerClass(); @@ -290,6 +313,8 @@ function collectControllers(controllers: Ctor[], mountpoint: string, origin: str registry.exportedRoutes.push({ method: route.method, pattern }); } + const transformer = resolveTransformer(ControllerClass, route, pattern, viewsCtx); + registry.routePlans.push({ pattern, method: route.method, @@ -300,7 +325,7 @@ function collectControllers(controllers: Ctor[], mountpoint: string, origin: str handlerName: route.handlerName, needs: getHandlerNeeds(argSpecs), run: async (context: any) => instance[route.handlerName](...(await resolveArgs(argSpecs, context))), - transformer: getTransformer(ControllerClass, route.handlerName) ?? JsonTransformer, + transformer, duplicates: route.duplicates, maxBodyBytes: route.maxBodyBytes, maxParts: route.maxParts, @@ -310,8 +335,34 @@ function collectControllers(controllers: Ctor[], mountpoint: string, origin: str } } +/** + * Resolves the response transformer for a route: `@Html` metadata builds an HTML transformer (after + * validating placement — buffered GET/POST only, and not combined with `@Transformer`); otherwise the + * user's `@Transformer` wins, falling back to {@link JsonTransformer}. + */ +function resolveTransformer( + ControllerClass: Ctor, + route: RouteMeta, + pattern: string, + viewsCtx: ViewsContext, +): TransformerFn { + const html = getHtmlMeta(ControllerClass, route.handlerName); + const userTransformer = getTransformer(ControllerClass, route.handlerName); + if (!html) return userTransformer ?? JsonTransformer; + + if (route.transport !== 'buffer' || (route.method !== 'GET' && route.method !== 'POST')) { + throw new Error( + `@Html on ${route.method} ${pattern} is not allowed — @Html only supports buffered GET/POST routes (not SSE/WS/PUT/PATCH/DELETE)`, + ); + } + + if (userTransformer) throw new Error(`@Html and @Transformer on ${pattern} conflict — use one`); + + return buildHtmlTransformer(html, viewsCtx); +} + /** Reads every module's metadata into a fresh {@link Registry} of graph nodes, runners and exports. */ -function collectModules(modules: Ctor[]): Registry { +function collectModules(modules: Ctor[], viewsCtx: ViewsContext): Registry { const registry = emptyRegistry(); for (const mod of modules) { @@ -320,7 +371,7 @@ function collectModules(modules: Ctor[]): Registry { const origin = `module:${mod.name}`; collectProviders(moduleMeta.providers ?? [], origin, registry); collectSteps(moduleMeta.steps ?? [], origin, registry); - collectControllers(moduleMeta.controllers ?? [], moduleMeta.mountpoint, origin, registry); + collectControllers(moduleMeta.controllers ?? [], moduleMeta.mountpoint, origin, registry, viewsCtx); } return registry; diff --git a/src/views.ts b/src/views.ts index 3f6aa21..436c8b2 100644 --- a/src/views.ts +++ b/src/views.ts @@ -1,6 +1,9 @@ // src/views.ts — HTML views: built-in templating, content-type map, and boot-time builders. // fs/path are lazy-required inside functions so the barrel stays edge-loadable (workerd has no filesystem). +import type { TransformerFn } from './metadata'; +import type { HtmlMeta } from './metadata'; + /** Escape the five HTML-significant characters so interpolated data can't inject markup. */ export function escapeHtml(s: string): string { const map: Record = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }; @@ -44,3 +47,47 @@ const CONTENT_TYPES: Record = { export function contentTypeFor(ext: string): string { return CONTENT_TYPES[ext.toLowerCase()] ?? 'application/octet-stream'; } + +const HTML_HEADERS = { 'content-type': 'text/html; charset=utf-8' } as const; + +/** Boot-time context for building `@Html` transformers: the views base dir and an optional BYO engine. */ +export interface ViewsContext { + views?: string; + viewEngine?: (source: string, data: unknown) => string; +} + +/** Reads a view file at boot (lazy fs). Relative paths resolve against `views` (default cwd); absolute as-is. + * node:fs/node:path are loaded lazily so importing the barrel stays edge/workerd-safe + * (workerd's nodejs_compat provides no filesystem). This path only runs for path/template `@Html` modes. */ +function readViewFile(views: string | undefined, path: string): string { + // eslint-disable-next-line @typescript-eslint/no-require-imports + const nodePath = require('node:path') as typeof import('node:path'); + // eslint-disable-next-line @typescript-eslint/no-require-imports + const fs = require('node:fs') as typeof import('node:fs'); + const base = views ?? process.cwd(); + const full = nodePath.isAbsolute(path) ? path : nodePath.resolve(base, path); + + try { + return fs.readFileSync(full, 'utf8'); + } catch (err) { + throw new Error( + `@Html('${path}') could not read '${full}' — on a runtime without a filesystem (edge), return a string from @Html instead. (${(err as Error).message})`, + ); + } +} + +/** Turns `@Html` metadata into a response transformer at boot. String mode is fs-free; path/template modes read+cache the file. */ +export function buildHtmlTransformer(meta: HtmlMeta, ctx: ViewsContext): TransformerFn { + if (!meta.path) { + return (value) => ({ status: 200, headers: { ...HTML_HEADERS }, body: String(value) }); + } + + const source = readViewFile(ctx.views, meta.path); + + if (meta.template) { + const engine = ctx.viewEngine ?? render; + return (value) => ({ status: 200, headers: { ...HTML_HEADERS }, body: engine(source, value) }); + } + + return () => ({ status: 200, headers: { ...HTML_HEADERS }, body: source }); +} diff --git a/test/views-html.test.ts b/test/views-html.test.ts new file mode 100644 index 0000000..72a165f --- /dev/null +++ b/test/views-html.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from 'vitest'; +import { writeFileSync, mkdirSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { createApp, Route, Get, Post, Sse, Transformer, Html, Module } from '../src/index'; + +const dir = join(tmpdir(), 'gt-views-test'); +mkdirSync(dir, { recursive: true }); +writeFileSync(join(dir, 'dash.html'), '

Dash

'); +writeFileSync(join(dir, 'user.html'), '

Hi {{ name }}

'); + +@Route('/') +class Views { + @Get('/str') @Html str() { return '

inline

'; } + @Get('/dash') @Html('dash.html') dash() {} + @Get('/user') @Html('user.html', { template: true }) user() { return { name: 'D' }; } +} +@Module({ mountpoint: '/', controllers: [Views] }) +class M {} +const app = createApp({ modules: [M], views: dir }); + +describe('@Html modes', () => { + it('string mode sends the handler return as text/html', async () => { + const res = await app.fetch(new Request('http://x/str')); + expect(res.headers.get('content-type')).toBe('text/html; charset=utf-8'); + expect(await res.text()).toBe('

inline

'); + }); + it('path mode serves the file and ignores the return', async () => { + expect(await (await app.fetch(new Request('http://x/dash'))).text()).toBe('

Dash

'); + }); + it('template mode renders the file with returned data, escaping by default', async () => { + expect(await (await app.fetch(new Request('http://x/user'))).text()).toBe('

Hi <b>D</b>

'); + }); +}); + +describe('@Html boot validation', () => { + it('rejects @Html on a streaming (SSE) route', () => { + @Route('/') class Bad { @Sse('/s') @Html s() { return (async function* () {})(); } } + @Module({ mountpoint: '/', controllers: [Bad] }) class BM {} + expect(() => createApp({ modules: [BM] })).toThrow(/@Html/); + }); + it('rejects @Html combined with @Transformer', () => { + const t = (v: unknown) => ({ status: 200, headers: {}, body: String(v) }); + @Route('/') class Bad2 { @Get('/g') @Html @Transformer(t) g() { return ''; } } + @Module({ mountpoint: '/', controllers: [Bad2] }) class BM2 {} + expect(() => createApp({ modules: [BM2] })).toThrow(/@Html and @Transformer/); + }); +}); + +describe('viewEngine override', () => { + it('uses a bring-your-own engine for template mode', async () => { + const app2 = createApp({ + modules: [M], + views: dir, + viewEngine: (source, data: any) => source.replace('{{ name }}', `RAW:${data.name}`), + }); + expect(await (await app2.fetch(new Request('http://x/user'))).text()).toBe('

Hi RAW:D

'); + }); +}); From ad3a06f05742e222991a80faf40eb3b0fd4d74a0 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 10 Jul 2026 14:42:20 -0500 Subject: [PATCH 112/139] feat(views): zero-config static directory serving Signed-off-by: Diego Resendez --- src/app/index.ts | 8 +++++- src/http/core.ts | 12 +++++++++ src/http/types.ts | 2 ++ src/views.ts | 54 ++++++++++++++++++++++++++++++++++++++ test/views-static.test.ts | 55 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 130 insertions(+), 1 deletion(-) create mode 100644 test/views-static.test.ts diff --git a/src/app/index.ts b/src/app/index.ts index 27b7c2e..18ce2a1 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -23,7 +23,7 @@ import { type RouteMeta, type TransformerFn, } from '../metadata'; -import { buildHtmlTransformer, type ViewsContext } from '../views'; +import { buildHtmlTransformer, buildStaticResolver, type ViewsContext } from '../views'; import { getArgs, getHandlerNeeds, resolveArgs } from '../params'; import { buildOpenApi, type OpenApiInfo } from '../openapi'; import { connectLink, type Link } from '../mesh/link'; @@ -85,6 +85,8 @@ export function createApp(opts: { views?: string; /** Bring-your-own template engine for `@Html(..., { template: true })`; defaults to the built-in `render`. */ viewEngine?: (source: string, data: unknown) => string; + /** Serve a static directory as a GET/HEAD fallback (after declared routes, before 404). `true` → `./public`. */ + static?: boolean | string; /** Opt in to alpha features whose API may still change. Currently gates `mesh`. */ experimental?: boolean; }): App { @@ -158,6 +160,8 @@ export function createApp(opts: { degradedProviders, ); + const staticResolver = opts.static ? buildStaticResolver(opts.static) : undefined; + const fetchOpts: HttpOptions = { limits: opts.limits, tls: opts.tls, @@ -166,6 +170,7 @@ export function createApp(opts: { cors: opts.cors, bodyDuplicates: opts.bodyDuplicates, onError: opts.onError, + static: staticResolver, }; const fetchFn = buildAppFetch( () => booted, @@ -218,6 +223,7 @@ export function createApp(opts: { cors: opts.cors, bodyDuplicates: opts.bodyDuplicates, onError: opts.onError, + static: staticResolver, }); server.on('close', () => closeLinks(meshLinks)); await new Promise((resolve) => server!.listen(port, resolve)); diff --git a/src/http/core.ts b/src/http/core.ts index a6771bb..0a4c4fe 100644 --- a/src/http/core.ts +++ b/src/http/core.ts @@ -69,6 +69,18 @@ export async function handle( const matched = matchRoute(routes, req.method, path); if (!matched) { + if ((req.method === 'GET' || req.method === 'HEAD') && opts?.static) { + const hit = await opts.static(path); + + if (hit) { + const body = req.method === 'HEAD' ? '' : hit.body; + return { + injected, + outcome: { kind: 'buffered', status: 200, headers: { 'content-type': hit.contentType }, body }, + }; + } + } + // Path matches a route under a different method → 405 with Allow; otherwise 404. const allow = allowedMethods(routes, path); const err = allow.length ? new HttpError(405, 'Method Not Allowed') : new NotFound('Not Found'); diff --git a/src/http/types.ts b/src/http/types.ts index a12c1e4..5e5f444 100644 --- a/src/http/types.ts +++ b/src/http/types.ts @@ -4,6 +4,7 @@ import type { PipelineResult } from '../pipeline'; import type { ErrorRenderer } from '../transformers'; import type { TlsOptions, SecurityOptions, CorsOptions } from '../security'; import type { WsRequest } from './ws-core'; +import type { StaticResolver } from '../views'; /** Per-request size and timeout ceilings applied by the server. */ export interface RequestLimits { @@ -24,6 +25,7 @@ export interface HttpOptions { cors?: CorsOptions; bodyDuplicates?: 'array' | 'last'; onError?: ErrorRenderer; + static?: StaticResolver; } /** Handler for a matched HTTP route; receives a normalized request and resolves to a pipeline result. */ diff --git a/src/views.ts b/src/views.ts index 436c8b2..210ab9c 100644 --- a/src/views.ts +++ b/src/views.ts @@ -76,6 +76,60 @@ function readViewFile(views: string | undefined, path: string): string { } } +/** A static-file hit: the raw bytes and the content-type to send. */ +export interface StaticHit { + body: Buffer; + contentType: string; +} + +/** Resolves a URL path to a static file under a fixed root, or `undefined` for a miss. */ +export type StaticResolver = (urlPath: string) => Promise; + +/** + * Builds a static-file resolver rooted at `root` (`true` → `./public`). Requires a filesystem: throws at + * boot on a runtime without one (edge). Path-traversal-safe — a resolved path outside the root is a miss. + */ +export function buildStaticResolver(root: string | true): StaticResolver { + let fs: typeof import('node:fs'); + let nodePath: typeof import('node:path'); + + try { + // eslint-disable-next-line @typescript-eslint/no-require-imports + fs = require('node:fs'); + // eslint-disable-next-line @typescript-eslint/no-require-imports + nodePath = require('node:path'); + } catch { + throw new Error( + '`static` needs a filesystem and is unavailable on this runtime (edge). Remove it or serve assets from a CDN.', + ); + } + + const abs = nodePath.resolve(process.cwd(), root === true ? 'public' : root); + + return async (urlPath) => { + let rel: string; + + try { + rel = decodeURIComponent(urlPath.split('?')[0]); + } catch { + return undefined; + } + + if (rel === '' || rel.endsWith('/')) rel += 'index.html'; + const full = nodePath.resolve(abs, '.' + (rel.startsWith('/') ? rel : '/' + rel)); + if (full !== abs && !full.startsWith(abs + nodePath.sep)) return undefined; // traversal guard + + try { + const stat = await fs.promises.stat(full); + const target = stat.isDirectory() ? nodePath.join(full, 'index.html') : full; + const body = await fs.promises.readFile(target); + return { body, contentType: contentTypeFor(nodePath.extname(target)) }; + } catch { + return undefined; + } + }; +} + /** Turns `@Html` metadata into a response transformer at boot. String mode is fs-free; path/template modes read+cache the file. */ export function buildHtmlTransformer(meta: HtmlMeta, ctx: ViewsContext): TransformerFn { if (!meta.path) { diff --git a/test/views-static.test.ts b/test/views-static.test.ts new file mode 100644 index 0000000..80be5ba --- /dev/null +++ b/test/views-static.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from 'vitest'; +import { writeFileSync, mkdirSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { createApp, Route, Get, Module } from '../src/index'; +import { buildStaticResolver } from '../src/views'; + +const root = join(tmpdir(), 'gt-static-test'); +mkdirSync(root, { recursive: true }); +writeFileSync(join(root, 'index.html'), '

Home

'); +writeFileSync(join(root, 'app.css'), 'body{}'); +writeFileSync(join(tmpdir(), 'gt-secret.txt'), 'TOP SECRET'); + +@Route('/api') +class Api { + @Get('/ping') + ping() { + return { ok: true }; + } +} +@Module({ mountpoint: '/', controllers: [Api] }) +class M {} +const app = createApp({ modules: [M], static: root }); + +describe('static serving', () => { + it('serves a file by path with its content-type', async () => { + const res = await app.fetch(new Request('http://x/app.css')); + expect(res.status).toBe(200); + expect(res.headers.get('content-type')).toBe('text/css; charset=utf-8'); + expect(await res.text()).toBe('body{}'); + }); + it('serves index.html for /', async () => { + expect(await (await app.fetch(new Request('http://x/'))).text()).toBe('

Home

'); + }); + it('declared routes win over static', async () => { + expect(await (await app.fetch(new Request('http://x/api/ping'))).json()).toEqual({ ok: true }); + }); + it('returns 404 for a missing file', async () => { + expect((await app.fetch(new Request('http://x/nope.html'))).status).toBe(404); + }); + it('rejects path traversal', async () => { + const res = await app.fetch(new Request('http://x/../gt-secret.txt')); + expect(res.status).toBe(404); + }); + it('answers HEAD with headers and no body', async () => { + const res = await app.fetch(new Request('http://x/app.css', { method: 'HEAD' })); + expect(res.status).toBe(200); + expect(await res.text()).toBe(''); + }); + it('resolver refuses to escape its root', async () => { + const resolve = buildStaticResolver(root); + expect(await resolve('/../gt-secret.txt')).toBeUndefined(); + expect(await resolve('/%2e%2e/gt-secret.txt')).toBeUndefined(); + }); +}); From 289ca5f8ff333fb1b26c1ced33bcecdec422cd32 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 10 Jul 2026 14:50:06 -0500 Subject: [PATCH 113/139] docs(views): @Html, templating, and static serving guide Signed-off-by: Diego Resendez --- CHANGELOG.md | 4 + website/astro.config.mjs | 1 + website/src/content/docs/guides/html.md | 152 ++++++++++++++++++++ website/src/content/docs/guides/runtimes.md | 15 ++ 4 files changed, 172 insertions(+) create mode 100644 website/src/content/docs/guides/html.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 82e9b68..70114e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,10 @@ green-tea uses calendar versioning: `YY.MM.PATCH`. ## [Unreleased] ### Added +- **HTML / views:** `@Html` decorator (string, file, and template modes), a zero-dep built-in + template engine (`{{ }}` escaped / `{{{ }}}` raw, exported as `render`) with a `viewEngine` + bring-your-own hook, and zero-config `static` directory serving (`createApp({ static: true })`). + File and static serving require a filesystem (Node/Deno/Bun); string-mode `@Html` runs everywhere. - **`app.fetch(request): Promise`** — a Web-Standards handler so the same app runs HTTP and SSE on Deno/Bun/edge runtimes via the Fetch API (WebSocket and mesh remain Node-only). diff --git a/website/astro.config.mjs b/website/astro.config.mjs index db488a6..31175f9 100644 --- a/website/astro.config.mjs +++ b/website/astro.config.mjs @@ -37,6 +37,7 @@ export default defineConfig({ { label: 'Error handling', slug: 'guides/errors' }, { label: 'Streaming & real-time', slug: 'guides/streaming' }, { label: 'File uploads', slug: 'guides/uploads' }, + { label: 'HTML & views', slug: 'guides/html' }, { label: 'Transport security', slug: 'guides/security' }, { label: 'Plugins & observability', slug: 'guides/plugins' }, { label: 'Graph introspection', slug: 'guides/introspection' }, diff --git a/website/src/content/docs/guides/html.md b/website/src/content/docs/guides/html.md new file mode 100644 index 0000000..823f619 --- /dev/null +++ b/website/src/content/docs/guides/html.md @@ -0,0 +1,152 @@ +--- +title: HTML & views +description: "The @Html decorator, the built-in template engine, and zero-config static file serving." +--- + +Most of green-tea assumes JSON, but not every route is an API endpoint. `@Html` marks a handler as serving HTML instead of going through the JSON transformer — a string, a file, or a file rendered with data. Add a static directory on top and you've got a small server-rendered site without reaching for a template framework. + +## `@Html` — three modes + +### 1. Return a string — every runtime + +Bare `@Html` sends the handler's return value as `text/html; charset=utf-8`. No filesystem involved, so this mode runs on Node, Deno, Bun, and the edge. + +```typescript +import { Route, Get, Html } from '@green-tea/core'; + +@Route('/') +class PageController { + @Get('/') + @Html + home() { + return '

Hello from green-tea

'; + } +} +``` + +### 2. Serve a file — Node/Deno/Bun + +`@Html('file.html')` reads the file at boot, caches it, and serves it verbatim — the handler still runs (for side effects, guards, etc.) but its return value is ignored. + +```typescript +@Route('/about') +class AboutController { + @Get('/') + @Html('about.html') + about() {} +} +``` + +Reading a file needs a filesystem, so this mode is Node/Deno/Bun only — see [Runtimes](/guides/runtimes/) for the edge alternative. + +### 3. Render a template — Node/Deno/Bun + +`@Html('file.html', { template: true })` reads the file at boot and renders it with whatever object the handler returns, on every request. + +```typescript +@Route('/user') +class UserController { + @Get('/:id') + @Html('user.html', { template: true }) + show(@param('id') id: string) { + return { name: lookupName(id) }; + } +} +``` + +`user.html`: + +```html +

Hi {{ name }}

+``` + +Same filesystem requirement as file mode: Node/Deno/Bun only. + +## The `views` base directory + +`@Html('file.html')` paths resolve against `createApp({ views })` — a relative path joins `views`, an absolute path is used as-is (handy for a template stored outside the project, e.g. on an NFS mount). `views` defaults to `process.cwd()` when unset. + +```typescript +const app = createApp({ modules: [ApiModule], views: 'templates' }); +// @Html('about.html') -> /templates/about.html +// @Html('/srv/shared/about.html') -> /srv/shared/about.html (absolute, used as-is) +``` + +Files are read once, at boot — not on every request. + +## The built-in template engine + +Template mode renders with a small, dependency-free engine, also exported as `render` if you want to call it directly: + +```typescript +import { render } from '@green-tea/core'; + +render('

{{ name }}

', { name: 'hi' }); +// '

<b>hi</b>

' — {{ x }} HTML-escapes + +render('{{{ html }}}', { html: 'hi' }); +// 'hi' — {{{ x }}} is raw, unescaped + +render('{{ user.name }} / {{ nope }}', { user: { name: 'Diego' } }); +// 'Diego / ' — {{ a.b }} walks nested keys; a missing key renders empty +``` + +That's the whole engine: interpolation, escaped or raw, with dotted-key lookup. No loops, conditionals, or partials — reach for `viewEngine` below if you need those. + +## Bring your own engine — `viewEngine` + +`createApp({ viewEngine })` swaps in any `(source, data) => string` function for template mode — EJS, Handlebars, or your own: + +```typescript +import ejs from 'ejs'; + +const app = createApp({ + modules: [ApiModule], + views: 'templates', + viewEngine: (source, data) => ejs.render(source, data as object), +}); +``` + +`viewEngine` only affects `@Html(..., { template: true })`; string and plain file modes are unaffected. + +## Static files — `createApp({ static })` + +`static` serves a directory as a GET/HEAD fallback, tried after your declared routes and before a `404`: + +```typescript +const app = createApp({ modules: [ApiModule], static: true }); // ./public, relative to cwd +const app2 = createApp({ modules: [ApiModule], static: 'assets' }); // ./assets, relative to cwd +const app3 = createApp({ modules: [ApiModule], static: '/srv/site' }); // absolute, used as-is +``` + +- Files are served at their URL path; content-type is inferred from the extension. +- `/` (and any directory-shaped path) resolves to `index.html`. +- Only `GET` and `HEAD` are handled — other methods fall through. +- **Declared routes always win.** Static is only consulted when nothing matched, so `@Get('/api/ping')` is never shadowed by a file at `public/api/ping`. +- Path traversal (`../`, encoded or not) is rejected — a request can't escape the static root. + +Like the file/template modes of `@Html`, `static` needs a filesystem: it's Node/Deno/Bun only. Configuring it on an edge runtime throws at `createApp()` time — see [Runtimes](/guides/runtimes/). + +## The boot rule + +`@Html` only supports **buffered `GET`/`POST`** routes. Boot fails fast rather than misbehaving at request time: + +```typescript +@Sse('/ticks') +@Html +ticks() { /* ... */ } +// throws at createApp(): "@Html on GET /ticks is not allowed — +// @Html only supports buffered GET/POST routes (not SSE/WS/PUT/PATCH/DELETE)" +``` + +`@Html` and `@Transformer` also can't be combined on the same handler — pick one: + +```typescript +@Get('/g') +@Html +@Transformer(myTransformer) +g() { /* ... */ } +// throws at createApp(): "@Html and @Transformer on /g conflict — use one" +``` + +Both checks run once, at boot, alongside the rest of the route validation — never per-request. diff --git a/website/src/content/docs/guides/runtimes.md b/website/src/content/docs/guides/runtimes.md index c1bb622..e2f8c73 100644 --- a/website/src/content/docs/guides/runtimes.md +++ b/website/src/content/docs/guides/runtimes.md @@ -117,3 +117,18 @@ this flag; without it, the Worker fails to load. Durable Objects and WebSocket Hibernation are **not** used — `edgeHandler` accepts WebSockets with the standard `WebSocketPair` model, so a Worker holds the connection open for its lifetime rather than hibernating between messages. + +## Filesystem features — Node/Deno/Bun only + +A few [HTML & views](/guides/html/) features read from disk, so they need a runtime with +a filesystem: + +- `@Html('file.html')` — reads and caches the file at boot. +- `@Html('file.html', { template: true })` — same, then renders it per request. +- `createApp({ static })` — serves a directory of files. + +All three throw at boot (`createApp()`/route-build time) on a runtime without a +filesystem, rather than failing per-request. On the edge, use bare `@Html` returning a +string instead — pair it with the exported `render` over a template string you `import` +as a module (so it ships in the bundle, no disk read), and serve other assets (images, +CSS, JS) from a CDN in front of the Worker. From 2d6306b318c8022b3a2c35304094e4fdeb8e3dab Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 10 Jul 2026 14:58:56 -0500 Subject: [PATCH 114/139] docs(views): reference pages, guide footgun note, drop unused test import Signed-off-by: Diego Resendez --- test/views-html.test.ts | 2 +- website/src/content/docs/guides/html.md | 6 ++++++ website/src/content/docs/reference/createapp.md | 3 +++ website/src/content/docs/reference/decorators.md | 12 ++++++++++++ 4 files changed, 22 insertions(+), 1 deletion(-) diff --git a/test/views-html.test.ts b/test/views-html.test.ts index 72a165f..7eafeb1 100644 --- a/test/views-html.test.ts +++ b/test/views-html.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest'; import { writeFileSync, mkdirSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; -import { createApp, Route, Get, Post, Sse, Transformer, Html, Module } from '../src/index'; +import { createApp, Route, Get, Sse, Transformer, Html, Module } from '../src/index'; const dir = join(tmpdir(), 'gt-views-test'); mkdirSync(dir, { recursive: true }); diff --git a/website/src/content/docs/guides/html.md b/website/src/content/docs/guides/html.md index 823f619..2914c37 100644 --- a/website/src/content/docs/guides/html.md +++ b/website/src/content/docs/guides/html.md @@ -62,6 +62,12 @@ 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. +::: + ## The `views` base directory `@Html('file.html')` paths resolve against `createApp({ views })` — a relative path joins `views`, an absolute path is used as-is (handy for a template stored outside the project, e.g. on an NFS mount). `views` defaults to `process.cwd()` when unset. diff --git a/website/src/content/docs/reference/createapp.md b/website/src/content/docs/reference/createapp.md index 2bb4e26..9a78f67 100644 --- a/website/src/content/docs/reference/createapp.md +++ b/website/src/content/docs/reference/createapp.md @@ -23,6 +23,9 @@ const app = createApp(options); | `cors` | `CorsOptions` | — | CORS handling | | `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 | +| `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/)) | +| `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/)) | +| `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/)) | | `mesh` | `MeshConfig` | — | distributed DI — **requires `experimental: true`** ([mesh](/guides/mesh/)) | | `experimental` | `boolean` | `false` | opt in to alpha features (currently gates `mesh`) | diff --git a/website/src/content/docs/reference/decorators.md b/website/src/content/docs/reference/decorators.md index d0d60f4..c3233a5 100644 --- a/website/src/content/docs/reference/decorators.md +++ b/website/src/content/docs/reference/decorators.md @@ -46,6 +46,18 @@ A request-scope transform that merges keys into the context. Same options as `@P Method decorator. Turns a handler's return value into `{ status?, headers?, body }`. `JsonTransformer` is the default. +### `@Html` / `@Html(path, opts?)` + +Method decorator. Marks a buffered `GET`/`POST` handler as serving HTML instead of going through the JSON transformer. Three modes ([details](/guides/html/)): + +| Form | Behavior | +|---|---| +| `@Html` (bare) | sends the handler's returned string as `text/html` | +| `@Html('file.html')` | serves that file verbatim; the handler's return value is ignored | +| `@Html('file.html', { template: true })` | renders the file with the handler's returned data, via the built-in `render` engine or `viewEngine` ([createApp](/reference/createapp/)) | + +Only buffered `GET`/`POST` routes are supported, and `@Html` can't be combined with `@Transformer` on the same handler — both are validated at boot, not per-request. + ## Routes Method decorators on a controller. All accept `(path, opts?)` where `opts = { export?: boolean, duplicates?: 'array' | 'last', maxBodyBytes?: number, maxParts?: number }`. `maxBodyBytes` / `maxParts` override the server-wide [`limits`](/reference/createapp/) for this route only. From f613a6427be23d01b9d56d3a194f3a4af18158f1 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 10 Jul 2026 15:55:22 -0500 Subject: [PATCH 115/139] 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 116/139] 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 117/139] 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 118/139] 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 119/139] =?UTF-8?q?docs(transport):=20reword=20homepage=20?= =?UTF-8?q?hero=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. From 922700674c7629d650d4fc6b2a4213a31e4ee77c Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 15 Jul 2026 13:33:47 -0500 Subject: [PATCH 120/139] fix(bus): emit step events for ws and mesh routes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/app/index.ts | 47 ++++++++++------------ src/pipeline.ts | 27 +++++++++---- test/app-upgrade.test.ts | 39 +++++++++++++++++- website/src/content/docs/guides/plugins.md | 2 +- 4 files changed, 81 insertions(+), 34 deletions(-) diff --git a/src/app/index.ts b/src/app/index.ts index a624c6e..13ae295 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -3,7 +3,7 @@ import { Bus } from '../bus'; import { Container } from '../container'; import { topoSort, subgraphFor, GraphNode, nearest } from '../graph'; import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz'; -import { runPipeline, PipelineStep } from '../pipeline'; +import { runPipeline, runSteps, PipelineStep } from '../pipeline'; import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http'; import type { HttpOptions } from '../http'; import { buildFetch } from '../http/web'; @@ -606,15 +606,13 @@ function buildMeshControl( const resolveScope = async (name: string, env: RequestEnvelope): Promise => { // 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) - 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 runner = runners.get(step.name)!; - context = { ...context, ...(await runner(context)) }; - } + const steps = orderedSteps.map((step) => ({ name: step.name, origin: step.origin, run: runners.get(step.name)! })); + const context = await runSteps(steps, seed, bus); return context[name]; }; @@ -788,7 +786,7 @@ function openApiRoute(openapi: () => unknown): RouteDef { /** Compiles every ws/negotiate route plan into a WebSocket route that seeds context and runs its steps + handler. */ function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[] { - const { providedSeed, planSteps } = deps; + const { providedSeed, planSteps, bus } = deps; return routePlans .filter((plan) => plan.transport === 'ws' || plan.transport === 'negotiate') @@ -798,23 +796,22 @@ function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[ const provided = await providedSeed(plan); // ws upgrades carry the neutral WsRequest (protocol/ip pre-derived by the runtime adapter); // trustProxy derivation for ws is out of scope here - // context is intentionally `any`: each step merges arbitrary keys into it - let context: any = { - ...provided, - req, - params, - query: parseQuery(req.url ?? ''), - body: undefined, - headers: req.headers, - inbound, - abort, - protocol: req.protocol, - ip: req.ip, - }; - - for (const step of planSteps(plan)) { - context = { ...context, ...(await step.run(context)) }; - } + const context = await runSteps( + planSteps(plan), + { + ...provided, + req, + params, + query: parseQuery(req.url ?? ''), + body: undefined, + headers: req.headers, + inbound, + abort, + protocol: req.protocol, + ip: req.ip, + }, + bus, + ); const result = await plan.run(context); if (!isAsyncIterable(result)) throw new Error(`@Ws handler '${plan.handlerName}' must return an AsyncIterable`); diff --git a/src/pipeline.ts b/src/pipeline.ts index 46a303f..1003e49 100644 --- a/src/pipeline.ts +++ b/src/pipeline.ts @@ -40,6 +40,25 @@ export function isStreamResult(result: PipelineResult): result is StreamResult { return 'stream' in result; } +/** + * Run `steps` in order, merging each step's output into the context and emitting + * `request:step:enter`/`leave` on the bus. The single place steps are executed — every + * transport (HTTP, ws, mesh) goes through here so observability is uniform by construction. + */ +export async function runSteps(steps: PipelineStep[], seed: Record, bus: Bus): Promise { + // context is intentionally `any`: each step merges arbitrary keys into the accumulator + let 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); + context = { ...context, ...output }; + bus.emit('request:step:leave', { name: step.name, scope: step.origin }); + } + + return context; +} + /** * Run `steps` in order over a context seeded from `seed`, then invoke `handler`. * An async-iterable handler result becomes a stream; anything else is run through `transformer`. @@ -59,13 +78,7 @@ export async function runPipeline(args: { let context: any = { ...seed }; try { - for (const step of steps) { - 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 }); - } - + context = await runSteps(steps, context, bus); const result = await handler(context); const streaming = isAsyncIterable(result); const contract = TRANSPORT_RETURN[transport]; diff --git a/test/app-upgrade.test.ts b/test/app-upgrade.test.ts index ebad14c..1e1f26b 100644 --- a/test/app-upgrade.test.ts +++ b/test/app-upgrade.test.ts @@ -1,5 +1,5 @@ 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 type { WsSocket, WsRequest } from '../src/http/ws-core'; @@ -16,6 +16,24 @@ class Rt { class M {} const app = createApp({ modules: [M] }); +@Step({ provides: 'tag' }) +class Tagger { + run() { + return { tag: 't' }; + } +} +@Route('/tagged') +class TaggedCtl { + @Ws('/echo') + echo(@needs('tag') tag: string, @ctx() { inbound }: any) { + return (async function* () { + for await (const msg of inbound) yield `${tag}:${msg}`; + })(); + } +} +@Module({ mountpoint: '/', steps: [Tagger], controllers: [TaggedCtl] }) +class Tagged {} + function fakeSocket() { const inbound = channel(); const ac = new AbortController(); @@ -46,6 +64,25 @@ describe('app.upgrade', () => { expect(sent).toEqual(['echo:hi']); }); + it('emits request:step:enter/leave for ws steps, like HTTP routes do', async () => { + const seen: string[] = []; + const logger = (api: any) => { + api.bus.on('request:step:enter', (p: any) => seen.push(`enter:${p.name}`)); + api.bus.on('request:step:leave', (p: any) => seen.push(`leave:${p.name}`)); + }; + const wsApp = createApp({ modules: [Tagged], plugins: [logger] }); + const { socket, inbound, sent } = fakeSocket(); + const req: WsRequest = { url: '/tagged/echo', headers: {}, protocol: 'http', ip: '' }; + const run = wsApp.upgrade(req, socket); + await new Promise((resolve) => setTimeout(resolve, 0)); + inbound.push('hi'); + inbound.close(); + await run; + + expect(sent).toEqual(['t:hi']); + expect(seen).toEqual(['enter:tag', 'leave:tag']); + }); + it('closes 1008 on an unknown ws path', async () => { const { socket } = fakeSocket(); let closedCode: number | undefined; diff --git a/website/src/content/docs/guides/plugins.md b/website/src/content/docs/guides/plugins.md index f3b647a..d6d7a89 100644 --- a/website/src/content/docs/guides/plugins.md +++ b/website/src/content/docs/guides/plugins.md @@ -42,7 +42,7 @@ mesh activity without touching the pipeline itself: ```typescript api.bus.on('boot:provider:ready', (p: any) => { /* ... */ }); api.bus.on('request:step:enter', (p: any) => { /* ... */ }); -api.bus.on('request:step:exit', (p: any) => { /* ... */ }); +api.bus.on('request:step:leave', (p: any) => { /* ... */ }); ``` The full event vocabulary: From 9421b102d99ee4e5771b4672b51eb65fd4091752 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 15 Jul 2026 13:33:50 -0500 Subject: [PATCH 121/139] refactor(adapters): share ws plumbing across bun/deno/edge MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/bun.ts | 69 +++++------------------- src/deno.ts | 89 +++--------------------------- src/edge.ts | 80 ++------------------------- src/http/ws-adapter.ts | 120 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 144 insertions(+), 214 deletions(-) create mode 100644 src/http/ws-adapter.ts diff --git a/src/bun.ts b/src/bun.ts index 9169db7..4656034 100644 --- a/src/bun.ts +++ b/src/bun.ts @@ -2,6 +2,7 @@ import { channel } from './channel'; import type { Channel } from './channel'; import type { App } from './app/types'; import type { WsSocket, WsRequest } from './http/ws-core'; +import { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter'; // Minimal ambient for the Bun globals we use — avoids a @types/bun devDep. // Mirrors the real Bun.serve / server.upgrade / ServerWebSocket signatures we call. @@ -33,8 +34,6 @@ interface BunServeOptions { type BunServeShortOptions = { port?: number; hostname?: string }; 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. */ interface BunConnData { wsReq: WsRequest; @@ -42,48 +41,15 @@ interface BunConnData { ac: AbortController; } -/** Builds a neutral WsRequest from a Bun request + server (for the client IP). */ -function toWsRequest(request: Request, server: BunServer): WsRequest { - const url = new URL(request.url); - const headers: Record = {}; - 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. */ +/** + * Wraps a Bun ServerWebSocket as a neutral WsSocket. Unlike Deno/edge, Bun delivers socket + * events to a server-level handler rather than the socket, so the channel and abort are + * created during the upgrade and stashed on ws.data — there is nothing here to wire up. + */ function bunSocket(ws: BunServerWebSocket): WsSocket { const { inbound, ac } = ws.data as BunConnData; - return { - inbound, - abort: ac.signal, - get isOpen() { - return ws.readyState === 1; // 1 = OPEN - }, - send: (data) => { - ws.send(data); - }, - close: (code, reason) => { - try { - ws.close(code, reason); - } catch { - /* already closed */ - } - }, - terminate: () => { - try { - (ws.terminate ?? ws.close).call(ws); - } catch { - /* already closed */ - } - }, - }; + + return neutralSocket(ws, inbound, ac); } /** @@ -98,7 +64,8 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServer { if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { const inbound = channel(); 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; return new Response('WebSocket upgrade failed', { status: 400 }); } @@ -108,21 +75,13 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServer { websocket: { open(ws) { 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 - // could crash the Bun process. - void app.upgrade(wsReq, bunSocket(ws)).catch(() => { - try { - ws.close(1011, 'internal error'); - } catch { - /* already closed */ - } - }); + + void upgradeSafely(app, wsReq, bunSocket(ws)); }, message(ws, message) { 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) { const { inbound, ac } = ws.data as BunConnData; diff --git a/src/deno.ts b/src/deno.ts index eafe6dc..f73e80a 100644 --- a/src/deno.ts +++ b/src/deno.ts @@ -1,23 +1,11 @@ -import { channel } from './channel'; 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) -// 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 WebSocketEventMap { - message: { data: string | ArrayBuffer }; - close: object; - error: object; -} -interface WebSocket { - readonly readyState: number; +// doesn't declare a global `WebSocket` either — so we ambient-declare just the shape we use. +interface WebSocket extends EventfulSocket { binaryType: string; - send(data: string): void; - close(code?: number, reason?: string): void; - addEventListener(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. // Mirrors the real Deno.serve / Deno.upgradeWebSocket signatures we call. @@ -40,63 +28,6 @@ declare const Deno: { 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 = {}; - 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(); - 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. * WebSocket messages flow through app.upgrade over the shared neutral core. @@ -105,17 +36,9 @@ export function serveDeno(app: App, options?: DenoServeOptions): DenoHttpServer return Deno.serve(options ?? {}, (request, info) => { if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { const { socket, response } = Deno.upgradeWebSocket(request); - // Fire-and-forget: the upgrade response must be returned synchronously while - // the graph runs. app.upgrade can reject BEFORE runWsConnection's own try/catch - // (mesh-before-listen throw, or a provider boot failure), so guard the call here — - // 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 */ - } - }); + socket.binaryType = 'arraybuffer'; // deliver binary frames as ArrayBuffer, which decodeMessage expects + // fire-and-forget: the 101 response must be returned synchronously while the graph runs + void upgradeSafely(app, toWsRequest(request, info.remoteAddr.hostname), eventSocket(socket)); return response; } diff --git a/src/edge.ts b/src/edge.ts index ec4780c..a064aa2 100644 --- a/src/edge.ts +++ b/src/edge.ts @@ -1,83 +1,16 @@ -import { channel } from './channel'; 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. // Declares only what we call; mirrors the real workerd signatures. -interface EdgeWebSocket { +interface EdgeWebSocket extends EventfulSocket { 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 { waitUntil(promise: Promise): void; } 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 = {}; - 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. * 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') { const [client, server] = Object.values(new WebSocketPair()) as [EdgeWebSocket, EdgeWebSocket]; server.accept(); - const lifecycle = app.upgrade(toWsRequest(request), edgeSocket(server)).catch(() => { - try { - server.close(1011, 'internal error'); - } catch { - /* already closed */ - } - }); + const wsReq = toWsRequest(request, request.headers.get('cf-connecting-ip') ?? ''); + const lifecycle = upgradeSafely(app, wsReq, eventSocket(server)); if (ctx?.waitUntil) ctx.waitUntil(lifecycle); else void lifecycle; diff --git a/src/http/ws-adapter.ts b/src/http/ws-adapter.ts new file mode 100644 index 0000000..8e024c0 --- /dev/null +++ b/src/http/ws-adapter.ts @@ -0,0 +1,120 @@ +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 = {}; + 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: 'message' | 'close' | 'error', + listener: (event: { data?: string | ArrayBuffer }) => 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(); + 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 & { terminate?(): void }, + inbound: ReturnType>, + 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 */ + } + }, + }; +} + +/** + * 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 { + return app.upgrade(request, socket).catch(() => { + socket.close(1011, 'internal error'); // neutral close already swallows throws + }); +} From d56eeafcd8354f95f9518303902ca1bd08933ddb Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 15 Jul 2026 13:33:52 -0500 Subject: [PATCH 122/139] 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 --- src/http/stream.ts | 22 ++++++++++++++++++---- src/mesh/link.ts | 17 +++++------------ src/openapi.ts | 38 +++++++++++++++++++++++--------------- src/signals.ts | 9 +++++++-- src/transformers.ts | 5 ++--- 5 files changed, 55 insertions(+), 36 deletions(-) diff --git a/src/http/stream.ts b/src/http/stream.ts index 9532fa2..f34783c 100644 --- a/src/http/stream.ts +++ b/src/http/stream.ts @@ -6,11 +6,25 @@ import type { Bus } from '../bus'; 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 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 { - if (transport === 'sse') return sseEncoder; - if (transport === 'ndjson') return ndjsonEncoder; - return accept.includes('text/event-stream') ? sseEncoder : ndjsonEncoder; + const pick = STREAM_ENCODERS[transport]; + if (!pick) throw new Error(`transport '${transport}' does not produce an HTTP stream`); + + return pick(accept); } /** Pipes an async-iterable result to the response as an HTTP stream, with keep-alive pings and backpressure handling. */ diff --git a/src/mesh/link.ts b/src/mesh/link.ts index 397364a..e946e65 100644 --- a/src/mesh/link.ts +++ b/src/mesh/link.ts @@ -2,8 +2,6 @@ import type { Bus } from '../bus'; import { HttpError } from '../signals'; import { encode, decode, type Manifest, type RequestEnvelope, type Frame } from './protocol'; -let connSeq = 0; // module-level: deterministic unique connection-id prefix (no Date.now/Math.random) - /** Client handle to a remote mesh server: its manifest, an RPC caller, and a close(). */ export interface Link { manifest: Manifest; @@ -56,19 +54,15 @@ function sendRpc( } /** Assemble the client-facing Link once the manifest arrives. */ -function buildLink( - ws: any, - pending: Map, - manifest: Manifest, - connId: string, - timeoutMs: number, -): Link { +function buildLink(ws: any, pending: Map, manifest: Manifest, timeoutMs: number): Link { + // ids only need to be unique within this link: `pending` is per-connection, so a + // per-link counter suffices (no module-global sequence, no test-order coupling). let counter = 0; return { manifest, rpc(kind, name, ctx) { - const id = `${connId}:${counter++}`; + const id = String(counter++); return sendRpc(ws, pending, id, kind, name, ctx, timeoutMs); }, @@ -103,7 +97,6 @@ export function connectLink(args: { url: string; secret: string; timeoutMs?: num const WS = loadWs(); const ws = new WS(args.url); const pending = new Map(); - const connId = `c${connSeq++}`; let manifest: Manifest | undefined; return new Promise((resolve, reject) => { @@ -134,7 +127,7 @@ export function connectLink(args: { url: string; secret: string; timeoutMs?: num manifest = { scopes: frame.scopes, routes: frame.routes }; clearTimeout(connectTimer); args.bus?.emit('mesh:connect', { name: args.url }); - resolve(buildLink(ws, pending, manifest, connId, timeoutMs)); + resolve(buildLink(ws, pending, manifest, timeoutMs)); return; } diff --git a/src/openapi.ts b/src/openapi.ts index 7eba251..4acf4f4 100644 --- a/src/openapi.ts +++ b/src/openapi.ts @@ -1,10 +1,11 @@ import type { ArgSpec } from './params'; +import type { Transport } from './metadata'; /** Minimal per-route input the OpenAPI projection needs, derived from a route plan. */ export interface OpenApiRoute { method: string; pattern: string; - transport: string; + transport: Transport; args: ArgSpec[]; } @@ -55,17 +56,23 @@ function argParams(args: ArgSpec[]): Parameter[] { return params; } -/** The success/error responses documented for a route, keyed by transport and whether any input is validated. */ -function responses(route: OpenApiRoute): Record { - const result: Record = {}; +/** + * The documented `200` per transport. `ws` is absent by construction — ws routes are not + * HTTP request/response and are filtered out before this runs. A new transport adds a row, + * and the compiler fails until it does. + */ +type HttpTransport = Exclude; - if (route.transport === 'sse') { - result['200'] = { description: 'Event stream', content: { 'text/event-stream': {} } }; - } else if (route.transport === 'ndjson' || route.transport === 'negotiate') { - result['200'] = { description: 'Stream', content: { 'application/x-ndjson': {} } }; - } else { - result['200'] = { description: 'OK', content: { 'application/json': { schema: {} } } }; - } +const TRANSPORT_OK: Record> = { + buffer: { description: 'OK', content: { 'application/json': { schema: {} } } }, + sse: { description: 'Event stream', content: { 'text/event-stream': {} } }, + ndjson: { description: 'Stream', content: { 'application/x-ndjson': {} } }, + negotiate: { description: 'Stream', content: { 'application/x-ndjson': {} } }, +}; + +/** The success/error responses documented for a route, keyed by transport and whether any input is validated. */ +function responses(route: OpenApiRoute, transport: HttpTransport): Record { + const result: Record = { '200': TRANSPORT_OK[transport] }; if (route.args.some((arg) => arg.schema)) result['422'] = { description: 'Validation failed' }; result['500'] = { description: 'Internal Server Error' }; @@ -73,9 +80,9 @@ function responses(route: OpenApiRoute): Record { } /** Builds a single OpenAPI operation object for a route. */ -function operation(route: OpenApiRoute): Record { +function operation(route: OpenApiRoute, transport: HttpTransport): Record { const parameters = [...pathParams(route.pattern), ...argParams(route.args)]; - const op: Record = { responses: responses(route) }; + const op: Record = { responses: responses(route, transport) }; if (parameters.length) op.parameters = parameters; @@ -95,9 +102,10 @@ export function buildOpenApi(routes: OpenApiRoute[], info?: OpenApiInfo): OpenAp const paths: Record> = {}; 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); - (paths[path] ??= {})[route.method.toLowerCase()] = operation(route); + (paths[path] ??= {})[route.method.toLowerCase()] = operation(route, transport); } return { diff --git a/src/signals.ts b/src/signals.ts index 29f5507..c34dfc1 100644 --- a/src/signals.ts +++ b/src/signals.ts @@ -1,11 +1,16 @@ 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 { constructor( readonly status: number, message?: string, readonly body?: unknown, + readonly headers?: Record, ) { super(message ?? `HTTP ${status}`); this.name = new.target.name; @@ -36,7 +41,7 @@ export class NotModified extends HttpError { /** 302 redirect to `location`. */ export class Redirect extends HttpError { constructor(readonly location: string) { - super(302); + super(302, undefined, undefined, { location }); } } diff --git a/src/transformers.ts b/src/transformers.ts index 328783b..eac5c81 100644 --- a/src/transformers.ts +++ b/src/transformers.ts @@ -1,4 +1,4 @@ -import { isHttpError, Redirect, ValidationError } from './signals'; +import { isHttpError, ValidationError } from './signals'; import type { TransformerFn } from './metadata'; import { flattenPath } from './standard-schema'; @@ -47,8 +47,7 @@ export function errorToResponse(error: unknown): ErrorResponse { } if (isHttpError(error)) { - const headers: Record = { 'content-type': 'application/json' }; - if (error instanceof Redirect) headers.location = error.location; + const headers = { 'content-type': 'application/json', ...error.headers }; const payload = error.body !== undefined ? error.body : { error: error.message }; return { status: error.status, headers, body: JSON.stringify(payload) }; } From dd0ea91a1bb7753a9f7f286765e291e774b4ff91 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 15 Jul 2026 14:47:35 -0500 Subject: [PATCH 123/139] feat(mesh): version the wire protocol and validate frame shapes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/mesh/link.ts | 17 +++++++-- src/mesh/protocol.ts | 67 +++++++++++++++++++++++++++++------ src/mesh/teapot.ts | 50 ++++++++++++++++++++++----- test/mesh/link.test.ts | 40 +++++++++++++++++++-- test/mesh/protocol.test.ts | 71 ++++++++++++++++++++++++++++++++++---- test/mesh/teapot.test.ts | 36 ++++++++++++++----- 6 files changed, 243 insertions(+), 38 deletions(-) diff --git a/src/mesh/link.ts b/src/mesh/link.ts index e946e65..caa6f6c 100644 --- a/src/mesh/link.ts +++ b/src/mesh/link.ts @@ -1,6 +1,6 @@ import type { Bus } from '../bus'; import { HttpError } from '../signals'; -import { encode, decode, type Manifest, type RequestEnvelope, type Frame } from './protocol'; +import { encode, decode, MESH_PROTOCOL_VERSION, type Manifest, type RequestEnvelope, type Frame } from './protocol'; /** Client handle to a remote mesh server: its manifest, an RPC caller, and a close(). */ export interface Link { @@ -105,7 +105,7 @@ export function connectLink(args: { url: string; secret: string; timeoutMs?: num reject(new Error(`mesh connect timeout: ${args.url}`)); }, timeoutMs); - ws.on('open', () => ws.send(encode({ type: 'hello', secret: args.secret }))); + ws.on('open', () => ws.send(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: args.secret }))); ws.on('error', (error: unknown) => reject(error)); ws.on('close', () => { clearTimeout(connectTimer); @@ -124,8 +124,19 @@ export function connectLink(args: { url: string; secret: string; timeoutMs?: num } if (frame.type === 'manifest') { - manifest = { scopes: frame.scopes, routes: frame.routes }; clearTimeout(connectTimer); + + if (frame.v !== MESH_PROTOCOL_VERSION) { + ws.close(); + reject( + new Error( + `mesh protocol version mismatch at ${args.url}: teapot speaks v${frame.v}, this teacup speaks v${MESH_PROTOCOL_VERSION}`, + ), + ); + return; + } + + manifest = { scopes: frame.scopes, routes: frame.routes }; args.bus?.emit('mesh:connect', { name: args.url }); resolve(buildLink(ws, pending, manifest, timeoutMs)); return; diff --git a/src/mesh/protocol.ts b/src/mesh/protocol.ts index e2731b2..5f4b82b 100644 --- a/src/mesh/protocol.ts +++ b/src/mesh/protocol.ts @@ -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. */ export interface RequestEnvelope { method: string; @@ -23,28 +31,67 @@ export interface Manifest { 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`. */ export type Frame = - | { type: 'hello'; secret: string } - | { type: 'manifest'; scopes: ScopeEntry[]; routes: RouteEntry[] } + | { type: 'hello'; v: number; secret: string } + | { type: 'manifest'; v: number; scopes: ScopeEntry[]; routes: RouteEntry[] } | { type: 'rpc-req'; id: string; kind: 'scope' | 'route'; name: string; ctx: RequestEnvelope } | { type: 'rpc-res'; id: string; ok: true; result: unknown } | { type: 'rpc-res'; id: string; ok: false; error: { message: string; status?: number } }; -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, 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 = { + 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'); + }, +}; /** Serialize a frame to a JSON wire string. */ export function encode(frame: Frame): string { return JSON.stringify(frame); } -/** Parse a wire string into a frame, throwing if the `type` tag is unknown. */ +/** Parse a wire string into a frame, throwing if the `type` tag is unknown or the shape is malformed. */ export function decode(json: string): Frame { - const parsed = JSON.parse(json) as { type?: unknown }; + const parsed = JSON.parse(json) as Record; + 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)) { - throw new Error(`unknown frame type: ${String(parsed.type)}`); - } + if (!check) throw new Error(`unknown frame type: ${String(type)}`); - return parsed as Frame; + check(parsed, (why) => { + throw new Error(`malformed ${String(type)} frame: ${why}`); + }); + + return parsed as unknown as Frame; } diff --git a/src/mesh/teapot.ts b/src/mesh/teapot.ts index b7922fa..6561bbf 100644 --- a/src/mesh/teapot.ts +++ b/src/mesh/teapot.ts @@ -2,7 +2,15 @@ import crypto from 'crypto'; import type { Bus } from '../bus'; import type { ResponseShape } from '../pipeline'; import { isHttpError } from '../signals'; -import { encode, decode, type Manifest, type RequestEnvelope, type RouteEntry, type Frame } from './protocol'; +import { + encode, + decode, + MESH_PROTOCOL_VERSION, + type Manifest, + type RequestEnvelope, + type RouteEntry, + type Frame, +} from './protocol'; /** WebSocket path where a teapot exposes its mesh control channel. */ export const MESH_CONTROL_PATH = '/__mesh__/control'; @@ -49,18 +57,44 @@ function notExported(name: string): Error { return error; } -/** Validate an unauthenticated hello frame; reply with the manifest on success or close on mismatch. */ +/** + * Validate an unauthenticated hello frame; reply with the manifest on success or close on mismatch. + * The version is checked *before* the secret: a skewed peer is not an auth failure, and telling it + * "wrong secret" would send its operator hunting the wrong bug. + */ function handleHandshake(ws: any, frame: Frame, deps: MeshControlDeps): boolean { - if (frame.type === 'hello' && safeEqual(frame.secret, deps.secret)) { - ws.send(encode({ type: 'manifest', scopes: deps.manifest.scopes, routes: deps.manifest.routes })); - deps.bus?.emit('mesh:connect', { name: 'teapot' }); + if (frame.type !== 'hello') { + ws.close(1008); - return true; + return false; } - ws.close(1008); + if (frame.v !== MESH_PROTOCOL_VERSION) { + ws.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)) { + ws.close(1008); + + return false; + } + + ws.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. */ diff --git a/test/mesh/link.test.ts b/test/mesh/link.test.ts index 69bdd18..888aafd 100644 --- a/test/mesh/link.test.ts +++ b/test/mesh/link.test.ts @@ -1,7 +1,9 @@ import { describe, it, expect } from 'vitest'; import { WebSocketServer } from 'ws'; import { connectLink } from '../../src/mesh/link'; -import { encode, decode } from '../../src/mesh/protocol'; +import { encode, decode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol'; + +const V = MESH_PROTOCOL_VERSION; const env = { method: 'GET', params: {}, query: {}, body: undefined, headers: {} }; @@ -13,7 +15,7 @@ function startTeapot(secret = 'good') { ws.on('message', (d) => { const f = decode(d.toString()); 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); return; } @@ -33,7 +35,7 @@ function startSilentTeapot(secret = 'good') { wss.on('connection', (ws) => { ws.on('message', (d) => { 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 }); }); @@ -41,7 +43,39 @@ function startSilentTeapot(secret = 'good') { 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() }; +} + 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 () => { const t = startTeapot(); const link = await connectLink({ url: t.url, secret: 'good' }); diff --git a/test/mesh/protocol.test.ts b/test/mesh/protocol.test.ts index f390593..029fe06 100644 --- a/test/mesh/protocol.test.ts +++ b/test/mesh/protocol.test.ts @@ -1,16 +1,22 @@ 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 V = MESH_PROTOCOL_VERSION; describe('protocol codec', () => { it('round-trips each frame type', () => { const frames: Frame[] = [ - { type: 'hello', 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: 'rpc-res', id: 'c1:1', ok: true, result: { id: 'u1' } }, - { type: 'rpc-res', id: 'c1:2', ok: false, error: { message: 'no', status: 401 } }, + { type: 'hello', v: V, secret: 's3cr3t' }, + { + type: 'manifest', + v: V, + 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); }); @@ -22,4 +28,57 @@ describe('protocol codec', () => { it('throws on unknown frame type', () => { 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); + }); }); diff --git a/test/mesh/teapot.test.ts b/test/mesh/teapot.test.ts index 3ed2746..b2194ce 100644 --- a/test/mesh/teapot.test.ts +++ b/test/mesh/teapot.test.ts @@ -1,7 +1,9 @@ import { describe, it, expect, vi } from 'vitest'; import { EventEmitter } from 'events'; import { buildManifest, createMeshControl } from '../../src/mesh/teapot'; -import { encode, decode } from '../../src/mesh/protocol'; +import { encode, decode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol'; + +const V = MESH_PROTOCOL_VERSION; import { Unauthorized } from '../../src/signals'; const fakeWs = () => { @@ -36,15 +38,33 @@ describe('createMeshControl', () => { it('rejects a bad secret and closes', () => { const ws = fakeWs(); make().handle(ws); - ws.emit('message', encode({ type: 'hello', secret: 'wrong' })); + ws.emit('message', encode({ type: 'hello', v: V, secret: 'wrong' })); expect(ws.close).toHaveBeenCalledWith(1008); expect(ws.sent).toEqual([]); }); - it('answers a good hello with the manifest', () => { + it('answers a good hello with the manifest, stamped with the protocol version', () => { const ws = fakeWs(); make().handle(ws); - ws.emit('message', encode({ type: 'hello', secret: 'good' })); - expect(ws.sent[0]).toMatchObject({ type: 'manifest', scopes: manifest.scopes }); + ws.emit('message', encode({ type: 'hello', v: V, secret: 'good' })); + expect(ws.sent[0]).toMatchObject({ type: 'manifest', v: V, scopes: manifest.scopes }); + }); + + it('rejects a version-skewed peer before checking its secret, naming both versions', () => { + const ws = fakeWs(); make().handle(ws); + // correct secret, wrong protocol: must still be refused — and not as an auth failure + ws.emit('message', encode({ type: 'hello', v: V + 1, secret: 'good' } as any)); + expect(ws.sent).toEqual([]); + const [code, reason] = ws.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', () => { + const ws = fakeWs(); make().handle(ws); + ws.emit('message', encode({ type: 'hello', v: V + 1, secret: 'wrong' } as any)); + expect(ws.sent).toEqual([]); + expect(ws.close).toHaveBeenCalled(); }); it('does NOT process rpc before handshake', async () => { @@ -56,7 +76,7 @@ describe('createMeshControl', () => { it('resolves an exported scope after handshake', async () => { const ws = fakeWs(); make().handle(ws); - ws.emit('message', encode({ type: 'hello', secret: 'good' })); + ws.emit('message', encode({ type: 'hello', v: V, secret: 'good' })); ws.emit('message', encode({ type: 'rpc-req', id: '7', kind: 'scope', name: 'config', ctx: {} as any })); await new Promise((r) => setTimeout(r, 5)); expect(ws.sent.find((f: any) => f.type === 'rpc-res')).toEqual({ type: 'rpc-res', id: '7', ok: true, result: { resolved: 'config' } }); @@ -64,7 +84,7 @@ describe('createMeshControl', () => { it('rejects an unexported scope', async () => { const ws = fakeWs(); make().handle(ws); - ws.emit('message', encode({ type: 'hello', secret: 'good' })); + ws.emit('message', encode({ type: 'hello', v: V, secret: 'good' })); ws.emit('message', encode({ type: 'rpc-req', id: '8', kind: 'scope', name: 'secretsvc', ctx: {} as any })); await new Promise((r) => setTimeout(r, 5)); const res: any = ws.sent.find((f: any) => f.type === 'rpc-res'); @@ -75,7 +95,7 @@ describe('createMeshControl', () => { it('propagates a thrown HttpError status in the error frame', async () => { const ws = fakeWs(); make({ resolveScope: async () => { throw new Unauthorized('nope'); } }).handle(ws); - ws.emit('message', encode({ type: 'hello', secret: 'good' })); + ws.emit('message', encode({ type: 'hello', v: V, secret: 'good' })); ws.emit('message', encode({ type: 'rpc-req', id: '9', kind: 'scope', name: 'config', ctx: {} as any })); await new Promise((r) => setTimeout(r, 5)); const res: any = ws.sent.find((f: any) => f.type === 'rpc-res'); From 87772868abaf218f57401f307dadffef2bb167ad Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 15 Jul 2026 14:53:07 -0500 Subject: [PATCH 124/139] refactor(mesh): import node:crypto explicitly in the teapot MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/mesh/teapot.ts | 90 +++++++++++++++++++++++++++++----------------- 1 file changed, 57 insertions(+), 33 deletions(-) diff --git a/src/mesh/teapot.ts b/src/mesh/teapot.ts index 6561bbf..f453633 100644 --- a/src/mesh/teapot.ts +++ b/src/mesh/teapot.ts @@ -1,5 +1,9 @@ -import crypto from 'crypto'; +// node: prefix, not a bare specifier: this is the mesh auth path, and on Deno/Bun a bare +// 'crypto' leans on node-compat resolution heuristics. Buffer + timingSafeEqual resolve +// under node-compat on both; edge/workerd is out of scope (see the cross-runtime spec). +import crypto from 'node:crypto'; import type { Bus } from '../bus'; +import type { WsSocket } from '../http/ws-core'; import type { ResponseShape } from '../pipeline'; import { isHttpError } from '../signals'; import { @@ -62,15 +66,15 @@ function notExported(name: string): Error { * The version is checked *before* the secret: a skewed peer is not an auth failure, and telling it * "wrong secret" would send its operator hunting the wrong bug. */ -function handleHandshake(ws: any, frame: Frame, deps: MeshControlDeps): boolean { +function handleHandshake(socket: WsSocket, frame: Frame, deps: MeshControlDeps): boolean { if (frame.type !== 'hello') { - ws.close(1008); + socket.close(1008); return false; } if (frame.v !== MESH_PROTOCOL_VERSION) { - ws.close( + socket.close( 1008, `mesh protocol version mismatch: peer speaks v${frame.v}, this teapot speaks v${MESH_PROTOCOL_VERSION}`, ); @@ -79,12 +83,12 @@ function handleHandshake(ws: any, frame: Frame, deps: MeshControlDeps): boolean } if (!safeEqual(frame.secret, deps.secret)) { - ws.close(1008); + socket.close(1008); return false; } - ws.send( + socket.send( encode({ type: 'manifest', v: MESH_PROTOCOL_VERSION, @@ -119,7 +123,7 @@ function resolveRpc( /** Serve one authenticated rpc-req: resolve it and frame the ok/error response back to the peer. */ async function handleRpc( - ws: any, + socket: WsSocket, frame: RpcReqFrame, deps: MeshControlDeps, exportedScopes: Set, @@ -130,44 +134,64 @@ async function handleRpc( try { 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) { const status = isHttpError(err) ? err.status : ((err as any)?.status ?? 500); deps.bus?.emit('mesh:rpc:error', { name, error: err }); - ws.send(encode({ type: 'rpc-res', id, ok: false, error: { message: (err as Error).message, status } })); + 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. */ -export function createMeshControl(deps: MeshControlDeps): { path: string; handle: (ws: any) => void } { +/** Drive one control connection to completion: handshake, then serve RPCs until the socket ends. */ +async function serveFrames( + socket: WsSocket, + deps: MeshControlDeps, + exportedScopes: Set, + exportedRoutes: Set, +): Promise { + 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; + } + + 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) => void } { const exportedScopes = new Set(deps.manifest.scopes.map((scope) => scope.token)); const exportedRoutes = new Set(deps.manifest.routes.map((route) => `${route.method} ${route.pattern}`)); return { path: MESH_CONTROL_PATH, - handle(ws: any) { - let authed = false; - ws.on('message', async (data: unknown) => { - let frame: Frame; - - try { - frame = decode(String(data)); - } catch { - return; - } - - if (!authed) { - 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' })); + handle(socket: WsSocket) { + // `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. + void serveFrames(socket, deps, exportedScopes, exportedRoutes); }, }; } From 71b59e7c25b8a9da1bda1d693f06123a3a58c22d Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 15 Jul 2026 14:53:09 -0500 Subject: [PATCH 125/139] refactor(mesh): serve the control channel over the neutral WsSocket MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/http/types.ts | 9 +- src/http/ws.ts | 4 +- test/mesh/teapot.test.ts | 173 +++++++++++++++++++++++++++------------ 3 files changed, 128 insertions(+), 58 deletions(-) diff --git a/src/http/types.ts b/src/http/types.ts index 5e5f444..4526f69 100644 --- a/src/http/types.ts +++ b/src/http/types.ts @@ -1,9 +1,8 @@ -import type http from 'http'; import type { Transport } from '../metadata'; import type { PipelineResult } from '../pipeline'; import type { ErrorRenderer } from '../transformers'; import type { TlsOptions, SecurityOptions, CorsOptions } from '../security'; -import type { WsRequest } from './ws-core'; +import type { WsRequest, WsSocket } from './ws-core'; import type { StaticResolver } from '../views'; /** Per-request size and timeout ceilings applied by the server. */ @@ -74,5 +73,9 @@ export interface WsRouteDef { /** Hook for a mesh gateway to take over WebSocket upgrades on a fixed path. */ export interface MeshControl { 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. + */ + handle(socket: WsSocket): void; } diff --git a/src/http/ws.ts b/src/http/ws.ts index 2f34b8a..1665ada 100644 --- a/src/http/ws.ts +++ b/src/http/ws.ts @@ -38,7 +38,9 @@ function handleMeshUpgrade( 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. + wss.handleUpgrade(req, socket, head, (ws: any) => meshControl.handle(nodeSocket(ws))); return true; } diff --git a/test/mesh/teapot.test.ts b/test/mesh/teapot.test.ts index b2194ce..50f92fb 100644 --- a/test/mesh/teapot.test.ts +++ b/test/mesh/teapot.test.ts @@ -1,17 +1,45 @@ import { describe, it, expect, vi } from 'vitest'; -import { EventEmitter } from 'events'; import { buildManifest, createMeshControl } from '../../src/mesh/teapot'; import { encode, decode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol'; - -const V = MESH_PROTOCOL_VERSION; +import { channel } from '../../src/channel'; +import type { WsSocket } from '../../src/http/ws-core'; import { Unauthorized } from '../../src/signals'; -const fakeWs = () => { - const ws: any = new EventEmitter(); - ws.sent = []; - ws.send = (s: string) => ws.sent.push(decode(s)); - ws.close = vi.fn(); - return ws; +const V = MESH_PROTOCOL_VERSION; + +/** Lets the control loop drain: it consumes `inbound` asynchronously and does not await RPCs. */ +const settle = () => new Promise((resolve) => setTimeout(resolve, 5)); + +/** + * 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(); + 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', () => { @@ -24,81 +52,118 @@ describe('buildManifest', () => { }); describe('createMeshControl', () => { - const manifest = buildManifest({ providers: ['config'], steps: ['auth'], routes: [{ method: 'GET', pattern: '/u/:id' }] }); - const make = (over: Partial[0]> = {}) => createMeshControl({ - secret: 'good', manifest, - resolveScope: async (name) => ({ resolved: name }), - resolveRoute: async () => ({ status: 200, headers: {}, body: 'route-body' }), - ...over, + const manifest = buildManifest({ + providers: ['config'], + steps: ['auth'], + routes: [{ method: 'GET', pattern: '/u/:id' }], }); + const make = (over: Partial[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', () => { expect(make().path).toBe('/__mesh__/control'); }); - it('rejects a bad secret and closes', () => { - const ws = fakeWs(); make().handle(ws); - ws.emit('message', encode({ type: 'hello', v: V, secret: 'wrong' })); - expect(ws.close).toHaveBeenCalledWith(1008); - expect(ws.sent).toEqual([]); + it('rejects a bad secret and closes', async () => { + const t = fakeSocket(); + make().handle(t.socket); + await t.deliver({ type: 'hello', v: V, secret: 'wrong' }); + expect(t.close).toHaveBeenCalledWith(1008); + expect(t.sent).toEqual([]); }); - it('answers a good hello with the manifest, stamped with the protocol version', () => { - const ws = fakeWs(); make().handle(ws); - ws.emit('message', encode({ type: 'hello', v: V, secret: 'good' })); - expect(ws.sent[0]).toMatchObject({ type: 'manifest', v: V, scopes: manifest.scopes }); + it('answers a good hello with the manifest, stamped with the protocol version', async () => { + const t = fakeSocket(); + make().handle(t.socket); + 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', () => { - const ws = fakeWs(); make().handle(ws); + 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 - ws.emit('message', encode({ type: 'hello', v: V + 1, secret: 'good' } as any)); - expect(ws.sent).toEqual([]); - const [code, reason] = ws.close.mock.calls[0]; + 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', () => { - const ws = fakeWs(); make().handle(ws); - ws.emit('message', encode({ type: 'hello', v: V + 1, secret: 'wrong' } as any)); - expect(ws.sent).toEqual([]); - expect(ws.close).toHaveBeenCalled(); + 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 () => { - const ws = fakeWs(); make().handle(ws); - ws.emit('message', encode({ type: 'rpc-req', id: '1', kind: 'scope', name: 'config', ctx: {} as any })); - await new Promise((r) => setTimeout(r, 5)); - expect(ws.sent).toEqual([]); + const t = fakeSocket(); + make().handle(t.socket); + await t.deliver({ type: 'rpc-req', id: '1', kind: 'scope', name: 'config', ctx: {} }); + expect(t.sent).toEqual([]); }); it('resolves an exported scope after handshake', async () => { - const ws = fakeWs(); make().handle(ws); - ws.emit('message', encode({ type: 'hello', v: V, secret: 'good' })); - ws.emit('message', encode({ type: 'rpc-req', id: '7', kind: 'scope', name: 'config', ctx: {} as any })); - await new Promise((r) => setTimeout(r, 5)); - expect(ws.sent.find((f: any) => f.type === 'rpc-res')).toEqual({ type: 'rpc-res', id: '7', ok: true, result: { resolved: 'config' } }); + const t = fakeSocket(); + make().handle(t.socket); + await t.deliver({ type: 'hello', v: V, secret: 'good' }); + await t.deliver({ type: 'rpc-req', id: '7', kind: 'scope', name: 'config', ctx: {} }); + 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 () => { - const ws = fakeWs(); make().handle(ws); - ws.emit('message', encode({ type: 'hello', v: V, secret: 'good' })); - ws.emit('message', encode({ type: 'rpc-req', id: '8', kind: 'scope', name: 'secretsvc', ctx: {} as any })); - await new Promise((r) => setTimeout(r, 5)); - const res: any = ws.sent.find((f: any) => f.type === 'rpc-res'); + const t = fakeSocket(); + make().handle(t.socket); + await t.deliver({ type: 'hello', v: V, secret: 'good' }); + await t.deliver({ type: 'rpc-req', id: '8', kind: 'scope', name: 'secretsvc', ctx: {} }); + const res: any = t.sent.find((f: any) => f.type === 'rpc-res'); expect(res.ok).toBe(false); expect(res.error.status).toBe(403); }); it('propagates a thrown HttpError status in the error frame', async () => { - const ws = fakeWs(); - make({ resolveScope: async () => { throw new Unauthorized('nope'); } }).handle(ws); - ws.emit('message', encode({ type: 'hello', v: V, secret: 'good' })); - ws.emit('message', encode({ type: 'rpc-req', id: '9', kind: 'scope', name: 'config', ctx: {} as any })); - await new Promise((r) => setTimeout(r, 5)); - const res: any = ws.sent.find((f: any) => f.type === 'rpc-res'); + const t = fakeSocket(); + make({ + resolveScope: async () => { + throw new Unauthorized('nope'); + }, + }).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 } }); }); + + 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']); + }); }); From 0ea4db3fef22c6b821986d785f7fa77406413ac1 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 15 Jul 2026 15:00:04 -0500 Subject: [PATCH 126/139] feat(mesh): connect the teacup over a runtime-neutral WebSocket client MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/http/ws-adapter.ts | 46 ++++++++++++- src/mesh/link.ts | 150 ++++++++++++++++++++++++++--------------- test/mesh/link.test.ts | 28 +++++++- 3 files changed, 168 insertions(+), 56 deletions(-) diff --git a/src/http/ws-adapter.ts b/src/http/ws-adapter.ts index 8e024c0..8f9307e 100644 --- a/src/http/ws-adapter.ts +++ b/src/http/ws-adapter.ts @@ -41,8 +41,8 @@ export interface EventfulSocket { send(data: string): void; close(code?: number, reason?: string): void; addEventListener( - type: 'message' | 'close' | 'error', - listener: (event: { data?: string | ArrayBuffer }) => void, + type: 'open' | 'message' | 'close' | 'error', + listener: (event: { data?: string | ArrayBuffer; error?: unknown }) => void, ): void; } @@ -107,6 +107,48 @@ export function neutralSocket( }; } +/** 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 } { + 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((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, diff --git a/src/mesh/link.ts b/src/mesh/link.ts index caa6f6c..a2ce38e 100644 --- a/src/mesh/link.ts +++ b/src/mesh/link.ts @@ -1,5 +1,7 @@ import type { Bus } from '../bus'; import { HttpError } from '../signals'; +import { connectSocket, type SocketCtor } from '../http/ws-adapter'; +import type { WsSocket } from '../http/ws-core'; import { encode, decode, MESH_PROTOCOL_VERSION, type Manifest, type RequestEnvelope, type Frame } from './protocol'; /** Client handle to a remote mesh server: its manifest, an RPC caller, and a close(). */ @@ -16,12 +18,6 @@ type PendingEntry = { timer: ReturnType; }; -function loadWs(): any { - // lazy/optional, like streams; the ws CJS export is the WebSocket class - // eslint-disable-next-line @typescript-eslint/no-require-imports - return require('ws'); -} - /** Reject and clear every in-flight RPC — used when the link closes. */ function rejectAllPending(pending: Map, reason: string): void { for (const [, entry] of pending) { @@ -34,7 +30,7 @@ function rejectAllPending(pending: Map, reason: string): v /** Register one RPC in `pending` by id, send its request, and reject it on timeout. */ function sendRpc( - ws: any, + socket: WsSocket, pending: Map, id: string, kind: 'scope' | 'route', @@ -49,12 +45,12 @@ function sendRpc( }, timeoutMs); 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. */ -function buildLink(ws: any, pending: Map, manifest: Manifest, timeoutMs: number): Link { +function buildLink(socket: WsSocket, pending: Map, manifest: Manifest, timeoutMs: number): Link { // ids only need to be unique within this link: `pending` is per-connection, so a // per-link counter suffices (no module-global sequence, no test-order coupling). let counter = 0; @@ -64,10 +60,10 @@ function buildLink(ws: any, pending: Map, manifest: Manife rpc(kind, name, ctx) { const id = String(counter++); - return sendRpc(ws, pending, id, kind, name, ctx, timeoutMs); + return sendRpc(socket, pending, id, kind, name, ctx, timeoutMs); }, close() { - ws.close(); + socket.close(); }, }; } @@ -91,60 +87,108 @@ function settleRpcResponse( } } -/** Open a WebSocket link to a mesh server, handshake with `secret`, and resolve once its manifest arrives. */ -export function connectLink(args: { url: string; secret: string; timeoutMs?: number; bus?: Bus }): Promise { +/** Handle for the in-flight handshake, so the frame loop can settle `connectLink`'s promise. */ +interface Handshake { + url: string; + socket: WsSocket; + pending: Map; + timeoutMs: number; + bus?: Bus; + resolve: (link: Link) => void; + reject: (error: unknown) => void; + onManifest: () => void; +} + +/** Settle the handshake from a `manifest` frame: refuse a version mismatch, else build the Link. */ +function settleManifest(frame: Extract, 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 { + 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 === '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; + bus?: Bus; + Ctor?: SocketCtor; +}): Promise { const timeoutMs = args.timeoutMs ?? 30_000; - const WS = loadWs(); - const ws = new WS(args.url); + const { socket, opened } = connectSocket(args.url, args.Ctor ?? undefined); const pending = new Map(); - let manifest: Manifest | undefined; + let manifest = false; return new Promise((resolve, reject) => { const connectTimer = setTimeout(() => { - ws.close(); + socket.close(); reject(new Error(`mesh connect timeout: ${args.url}`)); }, timeoutMs); - ws.on('open', () => ws.send(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: args.secret }))); - ws.on('error', (error: unknown) => reject(error)); - ws.on('close', () => { - clearTimeout(connectTimer); - args.bus?.emit('mesh:disconnect', { name: args.url }); - rejectAllPending(pending, 'mesh link closed'); - if (!manifest) reject(new Error(`mesh handshake failed: ${args.url}`)); - }); - - ws.on('message', (data: unknown) => { - let frame: Frame; - - try { - frame = decode(String(data)); - } catch { - return; - } - - if (frame.type === 'manifest') { + const hs: Handshake = { + url: args.url, + socket, + pending, + timeoutMs, + bus: args.bus, + resolve, + reject, + onManifest: () => { + manifest = true; clearTimeout(connectTimer); + }, + }; - if (frame.v !== MESH_PROTOCOL_VERSION) { - ws.close(); - reject( - new Error( - `mesh protocol version mismatch at ${args.url}: teapot speaks v${frame.v}, this teacup speaks v${MESH_PROTOCOL_VERSION}`, - ), - ); - return; - } + opened.then( + () => socket.send(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: args.secret })), + (error) => reject(error), + ); - manifest = { scopes: frame.scopes, routes: frame.routes }; - args.bus?.emit('mesh:connect', { name: args.url }); - resolve(buildLink(ws, pending, manifest, timeoutMs)); - return; - } + // 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); + args.bus?.emit('mesh:disconnect', { name: args.url }); + rejectAllPending(pending, 'mesh link closed'); + if (!manifest) reject(new Error(`mesh handshake failed: ${args.url}`)); + }, + { once: true }, + ); - if (frame.type === 'rpc-res') { - settleRpcResponse(pending, frame, args.bus); - } + void readFrames(hs).catch(() => { + /* inbound failed; the abort listener above reports it */ }); }); } diff --git a/test/mesh/link.test.ts b/test/mesh/link.test.ts index 888aafd..d80965e 100644 --- a/test/mesh/link.test.ts +++ b/test/mesh/link.test.ts @@ -1,6 +1,7 @@ import { describe, it, expect } from 'vitest'; -import { WebSocketServer } from 'ws'; +import WS, { WebSocketServer } from 'ws'; import { connectLink } from '../../src/mesh/link'; +import { loadWebSocketCtor, type SocketCtor } from '../../src/http/ws-adapter'; import { encode, decode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol'; const V = MESH_PROTOCOL_VERSION; @@ -53,6 +54,31 @@ function startSkewedTeapot() { 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', () => { it('sends its protocol version in the hello', async () => { const seen: any[] = []; From db9a7712afe1b7b7ee5b98ba105bd401171786a0 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 15 Jul 2026 15:04:49 -0500 Subject: [PATCH 127/139] feat(mesh): boot the mesh graph from the app boot gate, not listen() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/app/index.ts | 85 ++++++++++++------------ src/app/introspect.ts | 15 ++++- test/fetch.test.ts | 27 ++++++-- test/mesh/fetch-boot.test.ts | 123 +++++++++++++++++++++++++++++++++++ 4 files changed, 201 insertions(+), 49 deletions(-) create mode 100644 test/mesh/fetch-boot.test.ts diff --git a/src/app/index.ts b/src/app/index.ts index 13ae295..c320650 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -112,10 +112,13 @@ export function createApp(opts: { // For each route, resolve which providers/steps feed it via topo order. // MVP: every route depends on every declared step + provider in the app graph. - // For mesh apps, finalize is DEFERRED to listen() so remote scopes can join the graph first. + // For mesh apps, finalize is DEFERRED to the boot gate so remote scopes can join the graph + // first — connecting to teapots is network I/O, so it cannot happen during construction. let orderedProviders: GraphNode[] = []; let orderedSteps: GraphNode[] = []; let booted = false; + let remoteRoutes: RouteDef[] = []; + const meshLinks: Link[] = []; const finalize = (): void => { ({ orderedProviders, orderedSteps } = finalizeGraph(registry)); @@ -124,6 +127,16 @@ export function createApp(opts: { if (!opts.mesh) finalize(); + // mesh teacup: connect remote teapots and splice their scopes/routes in, then finalize. + const prepareGraph = async (): Promise => { + if (!opts.mesh || booted) return; + + const spliced = await spliceRemoteScopes(opts.mesh, bus, registry); + remoteRoutes = spliced.remoteRoutes; + meshLinks.push(...spliced.meshLinks); + finalize(); + }; + const inspect = (routePath: string): InspectLine[] => inspectRoute(routePlans, routePath, booted); const graph = (): GraphView => buildGraphView(providerNodes, stepNodes, routePlans, booted); const explain = (routePath: string): Explain => explainRoute(routePlans, routePath, booted); @@ -150,14 +163,15 @@ export function createApp(opts: { const providedSeed = (plan: RoutePlan) => seedProviders(container, plan); const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan); - // 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( + // Boots exactly once, however first triggered (app.fetch, app.upgrade or listen()); calling + // several never double-boots (which would re-run provider factories and their side effects). + const bootApp = makeAppBooter( registry, opts.overrides, () => orderedProviders, { runners, container, providerMeta, bus }, degradedProviders, + prepareGraph, ); const staticResolver = opts.static ? buildStaticResolver(opts.static) : undefined; @@ -173,36 +187,25 @@ export function createApp(opts: { static: staticResolver, }; const fetchFn = buildAppFetch( - () => booted, routePlans, { providedSeed, planSteps, bus, onError: opts.onError }, fetchOpts, - bootAppProviders, + bootApp, devRoutes, + () => remoteRoutes, ); const upgradeFn = buildAppUpgrade( - () => booted, routePlans, { providedSeed, planSteps, bus, onError: opts.onError }, streams, - bootAppProviders, + bootApp, ); const listen = async (port: number): Promise => { const deps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError }; - // mesh teacup: connect remote teapots, splice their scopes/routes into the graph, then finalize - let remoteRoutes: RouteDef[] = []; - const meshLinks: Link[] = []; - - if (opts.mesh && !booted) { - const spliced = await spliceRemoteScopes(opts.mesh, bus, registry); - remoteRoutes = spliced.remoteRoutes; - meshLinks.push(...spliced.meshLinks); - finalize(); - } - - await bootAppProviders(); + // the same gate app.fetch uses: splices remote mesh scopes, finalizes, boots providers + await bootApp(); const meshControl = buildMeshControl(opts.mesh, registry, { container, @@ -547,11 +550,13 @@ async function bootProviders( } /** - * Returns a memoized boot function: applies overrides and boots app-scope providers exactly once, - * however first triggered — {@link buildAppFetch}'s handler or `listen()` may both call it, and the - * memoization guarantees only the first call actually runs (and warns about) the boot sequence. + * Returns a memoized boot function: prepares the graph, applies overrides and boots app-scope + * providers exactly once, however first triggered — `app.fetch`, `app.upgrade` and `listen()` may + * all call it, and the memoization guarantees only the first runs the sequence. This is the single + * place an app becomes ready, which is what lets a mesh app boot on any runtime rather than only + * where `listen()` (a Node http.Server) can be built. */ -function makeProviderBooter( +function makeAppBooter( registry: Registry, overrides: Record | undefined, getOrderedProviders: () => GraphNode[], @@ -562,10 +567,13 @@ function makeProviderBooter( bus: Bus; }, degradedProviders: string[], + /** Splices remote mesh scopes in and finalizes the graph. Must precede providers: remote nodes join the topo sort. */ + prepareGraph: () => Promise, ): () => Promise { let bootPromise: Promise | undefined; const runBoot = async (): Promise => { + await prepareGraph(); applyOverrides(overrides, registry); degradedProviders.length = 0; degradedProviders.push(...(await bootProviders(getOrderedProviders(), deps))); @@ -691,29 +699,27 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps /** * 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()`. - * Non-mesh apps finalize eagerly, so `getBooted()` is already `true` and the route table is built - * on the very first call. Mesh apps defer finalize to `listen()` (remote scopes must splice into the - * graph first): `getBooted` reads the outer `booted` flag *live* on every call — exactly like - * `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. + * The boot is awaited *before* the route table is built: for a mesh app the table is not knowable + * until remote scopes have spliced in, and the boot is what does that. Both are memoized, so this + * costs one flag check per request after the first. */ function buildAppFetch( - getBooted: () => boolean, routePlans: RoutePlan[], deps: PipelineDeps, fetchOpts: HttpOptions, ensureBooted: () => Promise, devRoutes: () => RouteDef[], + getRemoteRoutes: () => RouteDef[], ): (request: Request) => Promise { let handler: ((request: Request) => Promise) | undefined; return async (request: Request): Promise => { + await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted + if (!handler) { - if (!getBooted()) throw new Error('fetch() unavailable before listen() for mesh apps'); - handler = buildFetch([...buildHttpRoutes(routePlans, [], deps), ...devRoutes()], fetchOpts); + handler = buildFetch([...buildHttpRoutes(routePlans, getRemoteRoutes(), deps), ...devRoutes()], fetchOpts); } - await ensureBooted(); // idempotent: no-op if listen() already booted the providers return handler(request); }; } @@ -722,12 +728,9 @@ function buildAppFetch( * Builds `app.upgrade`: the neutral WebSocket entry over the same route table `listen()` uses, so * Deno/Bun/edge adapters can drive ws connections without ever calling `listen()`. Node keeps its own * `server.on('upgrade')` path (see `attachWs`) and never calls this. - * Mirrors {@link buildAppFetch}'s finalize guard exactly: non-mesh apps finalize eagerly, so - * `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. + * Mirrors {@link buildAppFetch}: the boot is awaited before the ws route table is built. */ function buildAppUpgrade( - getBooted: () => boolean, routePlans: RoutePlan[], deps: PipelineDeps, streams: Set<() => void>, @@ -736,12 +739,10 @@ function buildAppUpgrade( let wsRoutes: WsRouteDef[] | undefined; return async (request: WsRequest, socket: WsSocket): Promise => { - if (!wsRoutes) { - if (!getBooted()) throw new Error('upgrade() unavailable before listen() for mesh apps'); - wsRoutes = buildWsRoutes(routePlans, deps); - } + await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted + + if (!wsRoutes) wsRoutes = buildWsRoutes(routePlans, deps); - await ensureBooted(); // idempotent: no-op if listen() already booted the providers const path = request.url.split('?')[0]; const route = matchWsRoute(wsRoutes, path); diff --git a/src/app/introspect.ts b/src/app/introspect.ts index 7607c3d..a85f937 100644 --- a/src/app/introspect.ts +++ b/src/app/introspect.ts @@ -4,7 +4,10 @@ import type { InspectLine, Explain, ExplainNode, RoutePlan } from './types'; /** Lists the provider/step/handler chain for a route, in execution order. */ export function inspectRoute(routePlans: RoutePlan[], routePath: string, booted: boolean): InspectLine[] { - if (!booted) throw new Error('inspect() unavailable before listen() for mesh apps'); + if (!booted) + throw new Error( + 'inspect() unavailable until a mesh app has booted — call listen(), or serve one request through app.fetch/app.upgrade, which splices the remote scopes in', + ); const plan = routePlans.find((candidate) => candidate.pattern === routePath); if (!plan) throw new Error(`no route: ${routePath}`); return [ @@ -25,7 +28,10 @@ export function buildGraphView( routePlans: RoutePlan[], booted: boolean, ): 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 — call listen(), or serve one request through app.fetch/app.upgrade, which splices the remote scopes in', + ); return { nodes: [ ...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. */ 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 — call listen(), or serve one request through app.fetch/app.upgrade, which splices the remote scopes in', + ); const plan = routePlans.find((candidate) => candidate.pattern === routePath); if (!plan) throw new Error(`no route: ${routePath}`); const toExplainNode = (node: GraphNode, kind: 'provider' | 'step'): ExplainNode => ({ diff --git a/test/fetch.test.ts b/test/fetch.test.ts index 1d0373b..5505077 100644 --- a/test/fetch.test.ts +++ b/test/fetch.test.ts @@ -110,17 +110,36 @@ describe('app.fetch trustProxy gates x-forwarded-for', () => { }); }); -describe('app.fetch mesh gating (live `booted` read)', () => { - it('throws before listen() and starts working after listen() finalizes', async () => { +describe('app.fetch on a mesh app', () => { + // Previously this asserted fetch() *threw* until listen() ran, which made mesh Node-only: + // Deno/Bun/edge serve through app.fetch and can never call listen() (it builds an http.Server). + // The boot gate now finalizes the mesh graph on first use, whoever triggers it. + it('serves without ever calling listen()', async () => { const meshApp = createApp({ modules: [MeshModule], experimental: true, mesh: { secret: 's3cr3t' } }); - 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); + try { const res = await meshApp.fetch(new Request('http://x/api/mesh/ping')); 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 { server.close(); } diff --git a/test/mesh/fetch-boot.test.ts b/test/mesh/fetch-boot.test.ts new file mode 100644 index 0000000..49c1477 --- /dev/null +++ b/test/mesh/fetch-boot.test.ts @@ -0,0 +1,123 @@ +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(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 teapotUrl = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`; + +/** + * 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('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(); + }); +}); From 0c68cba5321d862738b8722f408fde38d8e77f09 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 15 Jul 2026 15:12:53 -0500 Subject: [PATCH 128/139] feat(mesh): mount the control channel on app.upgrade, and close links without a server MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/app/index.ts | 96 +++++++++++++++++--------- src/http/types.ts | 3 +- src/http/ws.ts | 3 +- src/mesh/teapot.ts | 17 +++-- test/mesh/control-upgrade.test.ts | 2 +- test/mesh/fetch-boot.test.ts | 110 ++++++++++++++++++++++++++++++ 6 files changed, 191 insertions(+), 40 deletions(-) diff --git a/src/app/index.ts b/src/app/index.ts index c320650..f89abe5 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -30,7 +30,7 @@ import { connectLink, type Link } from '../mesh/link'; import { Rooms } from '../rooms'; import type { TlsOptions, SecurityOptions, CorsOptions } from '../security'; import { buildRemote } from '../mesh/teacup'; -import { buildManifest, createMeshControl } from '../mesh/teapot'; +import { buildManifest, createMeshControl, MESH_CONTROL_PATH } from '../mesh/teapot'; import type { MeshControl } from '../http'; import type { RequestEnvelope, RouteEntry } from '../mesh/protocol'; import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types'; @@ -127,14 +127,28 @@ export function createApp(opts: { if (!opts.mesh) finalize(); - // mesh teacup: connect remote teapots and splice their scopes/routes in, then finalize. - const prepareGraph = async (): Promise => { - if (!opts.mesh || booted) return; + 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; - const spliced = await spliceRemoteScopes(opts.mesh, bus, registry); - remoteRoutes = spliced.remoteRoutes; - meshLinks.push(...spliced.meshLinks); - finalize(); + // 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 => { + 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, + }); }; const inspect = (routePath: string): InspectLine[] => inspectRoute(routePlans, routePath, booted); @@ -160,9 +174,6 @@ export function createApp(opts: { return routes; }; - const providedSeed = (plan: RoutePlan) => seedProviders(container, plan); - const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan); - // Boots exactly once, however first triggered (app.fetch, app.upgrade or listen()); calling // several never double-boots (which would re-run provider factories and their side effects). const bootApp = makeAppBooter( @@ -194,26 +205,15 @@ export function createApp(opts: { devRoutes, () => remoteRoutes, ); - const upgradeFn = buildAppUpgrade( - routePlans, - { providedSeed, planSteps, bus, onError: opts.onError }, - streams, - bootApp, - ); + const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl); const listen = async (port: number): Promise => { - const deps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError }; + const deps = pipelineDeps; - // the same gate app.fetch uses: splices remote mesh scopes, finalizes, boots providers + // the same gate app.fetch uses: splices remote mesh scopes, finalizes, boots providers, + // and builds the mesh control channel — so Node and Deno/Bun serve an identical graph await bootApp(); - const meshControl = buildMeshControl(opts.mesh, registry, { - container, - orderedProviders, - orderedSteps, - deps, - }); - const httpRoutes = [...buildHttpRoutes(routePlans, remoteRoutes, deps), ...devRoutes()]; const wsRoutes = buildWsRoutes(routePlans, deps); @@ -235,7 +235,13 @@ export function createApp(opts: { const close = (): Promise => new Promise((resolve) => { + // before the server check: a mesh app booted through app.fetch (Deno/Bun, where listen() + // never runs) has links but no server, and would otherwise leak every teapot connection. + // Closing a link rejects its in-flight RPCs via the socket's abort. + closeLinks(meshLinks); + if (!server) return resolve(); + server.close(() => resolve()); // waits for in-flight buffered to drain for (const closeStream of streams) closeStream(); // force-close long-lived SSE/WS so close() resolves server.closeIdleConnections(); // Node >=18.2: drop idle keep-alive @@ -735,23 +741,49 @@ function buildAppUpgrade( deps: PipelineDeps, streams: Set<() => void>, ensureBooted: () => Promise, + getMeshControl: () => MeshControl | undefined, ): (request: WsRequest, socket: WsSocket) => Promise { let wsRoutes: WsRouteDef[] | undefined; return async (request: WsRequest, socket: WsSocket): Promise => { + // Subscribe to inbound BEFORE awaiting the boot. `channel` is fan-out: a frame pushed with no + // subscriber is dropped, so anything the peer sends while providers are still booting would be + // lost. For the mesh control channel that is the `hello` itself — the handshake would hang + // until timeout against a teapot whose providers happened to boot slowly. + const frames = socket.inbound[Symbol.asyncIterator](); + const ready: WsSocket = Object.create(socket, { + inbound: { value: { [Symbol.asyncIterator]: () => frames } }, + }) as WsSocket; + await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted - if (!wsRoutes) wsRoutes = buildWsRoutes(routePlans, deps); - const path = request.url.split('?')[0]; - const route = matchWsRoute(wsRoutes, path); + const meshControl = getMeshControl(); - if (!route) { - socket.close(1008, 'no matching ws route'); + // The reserved mesh path, checked before route matching: this is what lets a teapot export + // its scopes from Deno/Bun, where the Node `server.on('upgrade')` path does not exist. + if (path === MESH_CONTROL_PATH) { + // an explicit refusal, not "no matching ws route": the path is reserved either way, and a + // peer that reached a teapot with nothing exported deserves to be told which it was + if (!meshControl) { + ready.close(1008, 'mesh control channel not enabled: this app exports nothing, or has no mesh.secret'); + return; + } + + await meshControl.handle(ready); 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); }; } diff --git a/src/http/types.ts b/src/http/types.ts index 4526f69..7ea2406 100644 --- a/src/http/types.ts +++ b/src/http/types.ts @@ -76,6 +76,7 @@ export interface MeshControl { /** * 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): void; + handle(socket: WsSocket): Promise; } diff --git a/src/http/ws.ts b/src/http/ws.ts index 1665ada..6c8188a 100644 --- a/src/http/ws.ts +++ b/src/http/ws.ts @@ -40,7 +40,8 @@ function handleMeshUpgrade( // 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. - wss.handleUpgrade(req, socket, head, (ws: any) => meshControl.handle(nodeSocket(ws))); + // serveFrames swallows its own failures, so the floating promise cannot reject + wss.handleUpgrade(req, socket, head, (ws: any) => void meshControl.handle(nodeSocket(ws))); return true; } diff --git a/src/mesh/teapot.ts b/src/mesh/teapot.ts index f453633..c59503b 100644 --- a/src/mesh/teapot.ts +++ b/src/mesh/teapot.ts @@ -182,16 +182,23 @@ async function serveFrames( } /** 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) => void } { +export function createMeshControl(deps: MeshControlDeps): { + path: string; + handle: (socket: WsSocket) => Promise; +} { const exportedScopes = new Set(deps.manifest.scopes.map((scope) => scope.token)); const exportedRoutes = new Set(deps.manifest.routes.map((route) => `${route.method} ${route.pattern}`)); return { path: MESH_CONTROL_PATH, - handle(socket: WsSocket) { - // `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. - void serveFrames(socket, deps, exportedScopes, exportedRoutes); + /** + * Resolves when the connection ends, mirroring `runWsConnection` — so `app.upgrade` can await + * the control channel's lifetime the same way it awaits a regular ws route's. + * `channel` is fan-out and subscribes when the async iterator is created, which `for await` + * does synchronously, so the loop is live before any frame can arrive. + */ + handle(socket: WsSocket): Promise { + return serveFrames(socket, deps, exportedScopes, exportedRoutes); }, }; } diff --git a/test/mesh/control-upgrade.test.ts b/test/mesh/control-upgrade.test.ts index cd50118..454b4dd 100644 --- a/test/mesh/control-upgrade.test.ts +++ b/test/mesh/control-upgrade.test.ts @@ -5,7 +5,7 @@ import { createHttpServer, type MeshControl } from '../../src/http'; describe('mesh control upgrade', () => { it('routes the reserved path to meshControl.handle and leaves wsRoutes intact', async () => { 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); await new Promise((r) => server.listen(0, r)); const port = (server.address() as any).port; diff --git a/test/mesh/fetch-boot.test.ts b/test/mesh/fetch-boot.test.ts index 49c1477..7ba41bd 100644 --- a/test/mesh/fetch-boot.test.ts +++ b/test/mesh/fetch-boot.test.ts @@ -1,5 +1,8 @@ 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'; @@ -28,8 +31,43 @@ class LocalCtl { @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(); + 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: @@ -104,6 +142,30 @@ describe('mesh over app.fetch (no listen)', () => { 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('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); @@ -121,3 +183,51 @@ describe('mesh over app.fetch (no listen)', () => { 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); + }); +}); From a74417494f7426bae885ffd58a5af65b60a52284 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 15 Jul 2026 15:30:43 -0500 Subject: [PATCH 129/139] test(mesh): prove mesh across Node, Deno and Bun MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- package.json | 2 +- test/bun/mesh.test.ts | 84 ++++++++++++++++ test/deno/mesh-interop.test.ts | 170 +++++++++++++++++++++++++++++++++ test/deno/mesh.test.ts | 108 +++++++++++++++++++++ test/interop/_node-peer.ts | 71 ++++++++++++++ 5 files changed, 434 insertions(+), 1 deletion(-) create mode 100644 test/bun/mesh.test.ts create mode 100644 test/deno/mesh-interop.test.ts create mode 100644 test/deno/mesh.test.ts create mode 100644 test/interop/_node-peer.ts diff --git a/package.json b/package.json index b17be00..7169e50 100644 --- a/package.json +++ b/package.json @@ -79,7 +79,7 @@ "build": "tsup", "test": "vitest run", "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:edge": "tsx test/edge/run.ts", "typecheck": "tsc --noEmit -p tsconfig.json", diff --git a/test/bun/mesh.test.ts b/test/bun/mesh.test.ts new file mode 100644 index 0000000..136a496 --- /dev/null +++ b/test/bun/mesh.test.ts @@ -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); + } +}); diff --git a/test/deno/mesh-interop.test.ts b/test/deno/mesh-interop.test.ts new file mode 100644 index 0000000..9fae7d4 --- /dev/null +++ b/test/deno/mesh-interop.test.ts @@ -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 { + 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 { + 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); + } +}); diff --git a/test/deno/mesh.test.ts b/test/deno/mesh.test.ts new file mode 100644 index 0000000..cb8fc28 --- /dev/null +++ b/test/deno/mesh.test.ts @@ -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) { + 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(); + } +}); diff --git a/test/interop/_node-peer.ts b/test/interop/_node-peer.ts new file mode 100644 index 0000000..dada500 --- /dev/null +++ b/test/interop/_node-peer.ts @@ -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 -> 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 { + 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); +}); From 033af2d1fc6ab30d3356fdebb0962f3970fd95aa Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 15 Jul 2026 16:04:57 -0500 Subject: [PATCH 130/139] fix(mesh): fail the boot when two teapots export the same route MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/app/index.ts | 17 +++++++++ test/mesh/integration.test.ts | 67 +++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+) diff --git a/src/app/index.ts b/src/app/index.ts index f89abe5..f6c34e5 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -466,6 +466,7 @@ async function spliceRemoteScopes( ): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[] }> { const remoteRoutes: RouteDef[] = []; const meshLinks: Link[] = []; + const routeOwners = new Map(); // "METHOD /pattern" -> the teapot that exported it try { for (const teapot of mesh.teapots ?? []) { @@ -486,6 +487,22 @@ async function spliceRemoteScopes( } for (const route of routes) { + const key = `${route.method} ${route.pattern}`; + const owner = routeOwners.get(key); + + // Fail the boot rather than pick one. Route matching keeps the first of two identical + // patterns, so the loser would be silently dead — and callers could come to depend on + // "first teapot wins", which would make adding balancing later a breaking change. + // Scope tokens already fail this way in setRunner; routes now match. + if (owner) { + throw new Error( + `mesh: route '${key}' is exported by more than one teapot (${owner} and ${teapot.url}) — ` + + 'load balancing across teapots is not implemented yet, so green-tea will not choose one for you. ' + + 'Export it from a single teapot.', + ); + } + + routeOwners.set(key, teapot.url); remoteRoutes.push({ method: route.method, pattern: route.pattern, diff --git a/test/mesh/integration.test.ts b/test/mesh/integration.test.ts index 98bbf37..3108417 100644 --- a/test/mesh/integration.test.ts +++ b/test/mesh/integration.test.ts @@ -23,6 +23,28 @@ class LocalCtl { @Module({ mountpoint: '/api', controllers: [LocalCtl] }) 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('/c') +class PlainCtl { + @Get('/ok') + ok() { + return { ok: true }; + } +} +@Module({ mountpoint: '/', controllers: [PlainCtl] }) +class PlainTeacupModule {} + describe('mesh skeleton integration', () => { it('teacup resolves remote app-scope + request-scope into a local handler', async () => { const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); @@ -52,6 +74,51 @@ describe('mesh skeleton integration', () => { 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('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('rejects a bad secret (teacup boot fails)', async () => { const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); const tServer = await teapot.listen(0); const tPort = (tServer.address() as any).port; From 34dbb32b2c99940dbdc9234d33cf79f0f4a8f3bd Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 15 Jul 2026 16:20:55 -0500 Subject: [PATCH 131/139] docs(mesh): warn on shadowed remote routes, and tell the truth about mesh MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- CHANGELOG.md | 28 ++++++++- src/app/index.ts | 13 ++++ test/mesh/integration.test.ts | 66 ++++++++++++++++++++- website/src/content/docs/guides/mesh.md | 45 +++++++++++++- website/src/content/docs/guides/runtimes.md | 18 +++--- 5 files changed, 159 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cd43a36..4418446 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,17 +13,41 @@ green-tea uses calendar versioning: `YY.MM.PATCH`. bring-your-own hook, and zero-config `static` directory serving (`createApp({ static: true })`). File and static serving require a filesystem (Node/Deno/Bun); string-mode `@Html` runs everywhere. - **`app.fetch(request): Promise`** — a Web-Standards handler so the - same app runs HTTP and SSE on Deno/Bun/edge runtimes via the Fetch API - (WebSocket and mesh remain Node-only). + same app runs HTTP and SSE on Deno/Bun/edge runtimes via the Fetch API. - **Deno adapter** (`@green-tea/core/deno`): `serveDeno(app)` runs HTTP + SSE + WebSocket on Deno. - **Bun adapter** (`@green-tea/core/bun`): `serveBun(app)` runs HTTP + SSE + WebSocket on Bun, reusing the neutral `app.upgrade` / `WsSocket` capability. WebSocket, rooms, and channels behave identically to Node and Deno. - **Cloudflare Workers / edge adapter** (`@green-tea/core/edge`): `edgeHandler(app)` runs HTTP + SSE + WebSocket on workerd, reusing the neutral `app.upgrade` / `WsSocket` capability. Requires the `nodejs_compat` compatibility flag. Green Tea now runs on Node, Deno, Bun, and the edge — with identical WebSocket, rooms, and channel behaviour on all four. - **`app.upgrade(request, socket)`**: neutral WebSocket entry point for non-Node runtimes, built on a shared `WsSocket` capability. WebSocket logic is now runtime-agnostic (`src/http/ws-core.ts`). +- **Mesh (alpha) runs on Node, Deno and Bun** — teapot *and* teacup, in any combination + (a Deno teapot can serve a Node teacup). It no longer needs `app.listen()`: the graph boots on + first use, so `serveDeno`/`serveBun` work through `app.fetch`/`app.upgrade`. Edge is **not** + supported — the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which + `nodejs_compat` does not provide. +- **`MESH_PROTOCOL_VERSION`**: the mesh wire is versioned. Peers exchange it in the `hello`/`manifest` + frames and refuse a mismatch, naming both versions, instead of misreading each other's frames. + The teapot checks the version *before* the secret — a skewed peer is not an auth failure. +- **`HttpError` accepts `headers`**, so a custom error can carry its own response headers + (`retry-after`, `etag`, …) without a special case in the error renderer. ### Fixed - The opt-in dev routes `/__graph__` (graph viewer) and `/__openapi__` are now served over `app.fetch` too, so they work on every runtime (Deno/Bun/edge), not only the Node `app.listen()` path. +- **`request:step:enter`/`leave` are now emitted for `@Ws` and mesh routes.** Only HTTP routes + emitted them, so a logging plugin silently observed nothing on a WebSocket route — a gap in a + documented plugin API. All transports now run their steps through one path. +- **A mesh route exported by two teapots now fails the boot**, naming the route and both teapots, + instead of silently serving whichever connected first and leaving the other dead. There is no + load balancing to fall back on, so green-tea will not pick for you. +- **A local route shadowing a remote one now warns.** Local still takes precedence — that is how you + override a teapot — but a silently shadowed export used to look like a broken teapot. +- **`app.close()` closes mesh links even with no server**, so a mesh app booted through `app.fetch` + (every Deno/Bun deployment) no longer leaks its teapot connections. +- **WebSocket frames arriving during boot are no longer dropped.** `app.upgrade` awaited the boot + before handing the socket to a consumer, and the inbound channel is fan-out, so a peer that spoke + first lost those frames — for mesh, that was the handshake itself. +- The plugins guide documented a `request:step:exit` event that has never existed; the bus emits + `request:step:leave`. ### Changed - App-scope providers now boot exactly once (memoized): a second `app.listen()` diff --git a/src/app/index.ts b/src/app/index.ts index f6c34e5..98e967e 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -503,6 +503,19 @@ async function spliceRemoteScopes( } routeOwners.set(key, teapot.url); + + // Local routes are merged ahead of remote ones (see buildHttpRoutes), so a local twin + // wins. That precedence is deliberate — your own code beats an imported one, and it is + // how you override a teapot — but silently shadowing an export looks exactly like a + // broken teapot from the outside. Warn and let the developer decide. + if (registry.routePlans.some((plan) => plan.method === route.method && plan.pattern === route.pattern)) { + console.warn( + `[green-tea] mesh: route '${key}' is exported by teapot ${teapot.url} but also declared locally — ` + + 'the local route takes precedence and the remote one will not be reached. ' + + 'Remove one if that is not what you meant.', + ); + } + remoteRoutes.push({ method: route.method, pattern: route.pattern, diff --git a/test/mesh/integration.test.ts b/test/mesh/integration.test.ts index 3108417..f7321c9 100644 --- a/test/mesh/integration.test.ts +++ b/test/mesh/integration.test.ts @@ -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'; const SECRET = 's3cr3t'; @@ -45,6 +45,17 @@ class PlainCtl { @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', () => { it('teacup resolves remote app-scope + request-scope into a local handler', async () => { const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); @@ -119,6 +130,59 @@ describe('mesh skeleton integration', () => { 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 () => { const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); const tServer = await teapot.listen(0); const tPort = (tServer.address() as any).port; diff --git a/website/src/content/docs/guides/mesh.md b/website/src/content/docs/guides/mesh.md index fe9bfae..c0cf60d 100644 --- a/website/src/content/docs/guides/mesh.md +++ b/website/src/content/docs/guides/mesh.md @@ -11,6 +11,19 @@ A **teacup** can depend on a token that physically lives on another node — a * Exports are opt-in (`export: true`) and the control channel is gated by a shared secret. +## What runs where + +Mesh runs on **Node, Deno and Bun**, as both teapot and teacup, in any combination — a Deno teapot can serve a Node teacup. The wire is JSON over a WebSocket, so peers only have to agree on the protocol version, not the runtime. + +**Edge (Cloudflare Workers) is not supported.** The teapot's secret comparison uses `node:crypto`'s `timingSafeEqual`, which workerd's `nodejs_compat` does not provide. + +You do **not** need `listen()`. The graph boots on first use, so `Deno.serve`/`Bun.serve` work through `app.fetch`/`app.upgrade` like any other route: + +```typescript +serveDeno(teapot, { port: 3002 }); // control channel served via app.upgrade +serveBun(teacup, { port: 3003 }); // teapots connected on the first request +``` + ## Node A — teapot (exposes `config`, `auth`, and a route) ```typescript @@ -60,7 +73,37 @@ await teacup.listen(3003); - A **provider** export is **app-scope** — resolved once and cached. - A **step** export is **request-scope** — one RPC per request, carrying the request envelope. -Remote tokens become synthetic nodes in the local graph with RPC-backed runners, so the rest of the pipeline is unchanged. For non-mesh apps `createApp` stays synchronous; 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. + +## 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 + pattern`, the boot **fails**, naming the route and both teapots: + +``` +mesh: route 'GET /api/svc/ping' is exported by more than one teapot +(ws://a/__mesh__/control and ws://b/__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 it 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. +``` + +## Protocol version + +Peers are separate processes on separate deploy cadences, so the wire is versioned: `MESH_PROTOCOL_VERSION` travels in the `hello` and `manifest` frames, and a mismatch is refused on both sides with both versions named. A teapot checks the version **before** the secret — a skewed peer is not an authentication failure, and reporting it as one would send you hunting the wrong bug. + +Bump the version and old peers refuse the connection loudly instead of misreading a frame. :::note[Skeleton limitations (by design)] No discovery, load-balancing, or failover yet; app-scope remote values are not reconciled on reconnect; the request envelope omits `req.url`. diff --git a/website/src/content/docs/guides/runtimes.md b/website/src/content/docs/guides/runtimes.md index e2f8c73..6ce091e 100644 --- a/website/src/content/docs/guides/runtimes.md +++ b/website/src/content/docs/guides/runtimes.md @@ -27,8 +27,9 @@ and body for the same request (enforced by a parity test suite). **All four runtimes now have full WebSocket support:** Node, Deno, and Bun via `serveDeno` / `serveBun`, and Cloudflare Workers / edge via `edgeHandler` (see below) — same graph, same -`@Ws` handlers, same rooms/channels everywhere. `app.listen()`, TLS, per-request timeouts, -and mesh remain Node-only; on Deno/Bun/edge you get `app.fetch` + the runtime's adapter. +`@Ws` handlers, same rooms/channels everywhere. `app.listen()`, TLS and per-request timeouts +remain Node-only; on Deno/Bun/edge you get `app.fetch` + the runtime's adapter. **Mesh (alpha) +runs on Node, Deno and Bun** — teapot and teacup, in any combination — but not on edge. **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 @@ -58,8 +59,9 @@ Any runtime can build a `WsSocket` capability (`inbound`, `abort`, `isOpen`, `se `close`, `terminate`) and drive the graph — `serveBun` and `edgeHandler` build on the same primitive (see below). -**Still Node-only:** `app.listen()`, TLS, per-request timeouts, and mesh. On Deno you -get `app.fetch` + `serveDeno`. +**Still Node-only:** `app.listen()`, TLS and per-request timeouts. On Deno you get +`app.fetch` + `serveDeno`. [Mesh](/guides/mesh/) works here: the control channel is +served through `app.upgrade` and the teacup connects with Deno's global `WebSocket`. ## WebSocket on Bun @@ -80,8 +82,8 @@ serveBun(app, { port: 8000 }); `app.upgrade` — the same graph, the same `@Ws` handlers, the same rooms/channels you run on Node and Deno. Behaviour matches the Node reference. -**Still Node-only:** `app.listen()`, TLS, per-request timeouts, and mesh. On Bun you -get `app.fetch` + `serveBun`. +**Still Node-only:** `app.listen()`, TLS and per-request timeouts. On Bun you get +`app.fetch` + `serveBun`. [Mesh](/guides/mesh/) works here too. ## Cloudflare Workers / edge @@ -113,7 +115,9 @@ compatibility_date = "2024-09-23" # or later Green Tea's core statically imports Node built-ins that workerd only provides under this flag; without it, the Worker fails to load. -**Still Node-only:** `app.listen()`, TLS, per-request timeouts, and mesh. Cloudflare's +**Still Node-only:** `app.listen()`, TLS and per-request timeouts. [Mesh](/guides/mesh/) +is **not** supported on edge: the teapot's secret comparison needs `node:crypto`'s +`timingSafeEqual`, which `nodejs_compat` does not provide. Cloudflare's Durable Objects and WebSocket Hibernation are **not** used — `edgeHandler` accepts WebSockets with the standard `WebSocketPair` model, so a Worker holds the connection open for its lifetime rather than hibernating between messages. From 9886e5374789091207af809ad44ffed53f3a1e84 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 15 Jul 2026 23:00:14 -0500 Subject: [PATCH 132/139] feat(app): add app.ready() so introspection works on any app MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- CHANGELOG.md | 6 ++ src/app/index.ts | 32 ++++++++--- src/app/introspect.ts | 6 +- src/app/types.ts | 12 ++++ test/app.test.ts | 14 +++++ test/mesh/fetch-boot.test.ts | 75 +++++++++++++++++++++++++ website/src/content/docs/guides/mesh.md | 13 +++++ 7 files changed, 147 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4418446..ce9bf08 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,12 @@ green-tea uses calendar versioning: `YY.MM.PATCH`. 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`** — 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. ### Fixed - The opt-in dev routes `/__graph__` (graph viewer) and `/__openapi__` are now diff --git a/src/app/index.ts b/src/app/index.ts index 98e967e..7226502 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -53,6 +53,21 @@ interface Registry { 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): () => Promise { + let promise: Promise | undefined; + + return (): Promise => { + if (!promise) promise = run(); + + return promise; + }; +} + /** Request-time helpers shared by the HTTP, WS and mesh route builders. */ interface PipelineDeps { providedSeed(plan: RoutePlan): Promise>; @@ -151,6 +166,11 @@ export function createApp(opts: { }); }; + // Memoized separately from the provider boot on purpose: resolving the graph and being ready + // to serve are different things. Introspection needs only the former, and must not run + // provider factories (and open their connections) as a side effect of drawing a diagram. + const ready = once(prepareGraph); + const inspect = (routePath: string): InspectLine[] => inspectRoute(routePlans, routePath, booted); const graph = (): GraphView => buildGraphView(providerNodes, stepNodes, routePlans, booted); const explain = (routePath: string): Explain => explainRoute(routePlans, routePath, booted); @@ -182,7 +202,7 @@ export function createApp(opts: { () => orderedProviders, { runners, container, providerMeta, bus }, degradedProviders, - prepareGraph, + ready, ); const staticResolver = opts.static ? buildStaticResolver(opts.static) : undefined; @@ -250,6 +270,7 @@ export function createApp(opts: { return { listen, close, + ready, fetch: fetchFn, upgrade: upgradeFn, inspect, @@ -603,11 +624,9 @@ function makeAppBooter( bus: Bus; }, degradedProviders: string[], - /** Splices remote mesh scopes in and finalizes the graph. Must precede providers: remote nodes join the topo sort. */ + /** Resolves the graph (splices remote mesh scopes, finalizes). Must precede providers: remote nodes join the topo sort. */ prepareGraph: () => Promise, ): () => Promise { - let bootPromise: Promise | undefined; - const runBoot = async (): Promise => { await prepareGraph(); applyOverrides(overrides, registry); @@ -621,10 +640,7 @@ function makeAppBooter( } }; - return (): Promise => { - if (!bootPromise) bootPromise = runBoot(); - return bootPromise; - }; + return once(runBoot); } /** diff --git a/src/app/introspect.ts b/src/app/introspect.ts index a85f937..22f2450 100644 --- a/src/app/introspect.ts +++ b/src/app/introspect.ts @@ -6,7 +6,7 @@ import type { InspectLine, Explain, ExplainNode, RoutePlan } from './types'; export function inspectRoute(routePlans: RoutePlan[], routePath: string, booted: boolean): InspectLine[] { if (!booted) throw new Error( - 'inspect() unavailable until a mesh app has booted — call listen(), or serve one request through app.fetch/app.upgrade, which splices the remote scopes in', + 'inspect() unavailable until a mesh app has booted: a mesh graph is not knowable until its teapots are asked. Call `await app.ready()` first — it is a no-op on a non-mesh app', ); const plan = routePlans.find((candidate) => candidate.pattern === routePath); if (!plan) throw new Error(`no route: ${routePath}`); @@ -30,7 +30,7 @@ export function buildGraphView( ): GraphView { if (!booted) throw new Error( - 'graph() unavailable until a mesh app has booted — call listen(), or serve one request through app.fetch/app.upgrade, which splices the remote scopes in', + 'graph() unavailable until a mesh app has booted: a mesh graph is not knowable until its teapots are asked. Call `await app.ready()` first — it is a no-op on a non-mesh app', ); return { nodes: [ @@ -62,7 +62,7 @@ export function buildGraphView( export function explainRoute(routePlans: RoutePlan[], routePath: string, booted: boolean): Explain { if (!booted) throw new Error( - 'explain() unavailable until a mesh app has booted — call listen(), or serve one request through app.fetch/app.upgrade, which splices the remote scopes in', + 'explain() unavailable until a mesh app has booted: a mesh graph is not knowable until its teapots are asked. Call `await app.ready()` first — it is a no-op on a non-mesh app', ); const plan = routePlans.find((candidate) => candidate.pattern === routePath); if (!plan) throw new Error(`no route: ${routePath}`); diff --git a/src/app/types.ts b/src/app/types.ts index 50606a1..c8a9bff 100644 --- a/src/app/types.ts +++ b/src/app/types.ts @@ -36,6 +36,18 @@ export interface Explain { export interface App { listen(port: number): Promise; close(): Promise; + /** + * 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; /** 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; /** Run a WebSocket upgrade through the graph using an adapter-provided socket (Deno/Bun/edge). Node uses its own listener path. */ diff --git a/test/app.test.ts b/test/app.test.ts index fc944ad..1c39576 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -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']); }); +test('ready() is a no-op on a non-mesh app, so one protocol works for both', async () => { + // The point: code holding an `App` should not have to know whether it is a mesh app. + // `await app.ready(); app.graph()` is uniform — here it changes nothing and boots nothing. + const app = createApp({ modules: [ApiModule] }); + const booted: string[] = []; + app.bus.on('boot:provider:start', (p) => booted.push(p.name)); + + const before = app.graph().nodes.length; + await app.ready(); + + expect(app.graph().nodes.length).toBe(before); + expect(booted).toEqual([]); +}); + test('a logger plugin observes step:enter without mutating the chain', async () => { const seen: string[] = []; const logger = (api: any) => api.bus.on('request:step:enter', (p: any) => seen.push(p.name)); diff --git a/test/mesh/fetch-boot.test.ts b/test/mesh/fetch-boot.test.ts index 7ba41bd..c75f4c5 100644 --- a/test/mesh/fetch-boot.test.ts +++ b/test/mesh/fetch-boot.test.ts @@ -166,6 +166,81 @@ describe('mesh over app.fetch (no listen)', () => { 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); diff --git a/website/src/content/docs/guides/mesh.md b/website/src/content/docs/guides/mesh.md index c0cf60d..b3d9df6 100644 --- a/website/src/content/docs/guides/mesh.md +++ b/website/src/content/docs/guides/mesh.md @@ -75,6 +75,19 @@ await teacup.listen(3003); 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. From dba40b0c8b48e29927b3441c21d6de92aa5ec9b6 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 15 Jul 2026 23:32:45 -0500 Subject: [PATCH 133/139] feat(mesh): heartbeat the link, and tell the truth when a teapot is gone MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- CHANGELOG.md | 12 +++ src/app/index.ts | 12 ++- src/app/types.ts | 7 ++ src/http/ws-core.ts | 19 ++++ src/http/ws.ts | 15 ++- src/mesh/link.ts | 73 +++++++++++++- src/mesh/protocol.ts | 18 +++- src/mesh/teapot.ts | 6 ++ test/mesh/failure.test.ts | 121 ++++++++++++++++++++++++ test/mesh/heartbeat.test.ts | 86 +++++++++++++++++ website/src/content/docs/guides/mesh.md | 22 +++++ 11 files changed, 378 insertions(+), 13 deletions(-) create mode 100644 test/mesh/failure.test.ts create mode 100644 test/mesh/heartbeat.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index ce9bf08..32a7ac2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,10 +35,22 @@ green-tea uses calendar versioning: `YY.MM.PATCH`. ready to serve are different things, and drawing a diagram should not open your database connections. Serving boots them too and shares the same memoized step. +- **Mesh heartbeat** (`mesh.heartbeatMs`, default 15s): each teacup pings its teapots and closes a + link after two unanswered rounds, so a half-open connection surfaces as an immediate 503 rather + than every request paying `timeoutMs` first. Ping/pong are mesh frames, not WebSocket protocol + pings — the platform `WebSocket` on Deno/Bun does not expose `ws.ping()`. + ### Fixed - The opt-in dev routes `/__graph__` (graph viewer) and `/__openapi__` are now served over `app.fetch` too, so they work on every runtime (Deno/Bun/edge), not only the Node `app.listen()` path. +- **A teapot with a live control channel could never shut down.** Mesh control connections were + not registered with the stream registry, so `server.close()` waited on a connected teacup that + had no reason to hang up, and `app.close()` never resolved. +- **A downed teapot now answers 503 immediately** instead of hanging for the full `timeoutMs` + (30s by default) and then answering 500. A closed socket cannot deliver the frame, so the wait + bought nothing. An RPC that times out on a live link is now 504, not 500 — a dead upstream and + a slow one are different operational stories, and neither is "this service broke". - **`request:step:enter`/`leave` are now emitted for `@Ws` and mesh routes.** Only HTTP routes emitted them, so a logging plugin silently observed nothing on a WebSocket route — a gap in a documented plugin API. All transports now run their steps through one path. diff --git a/src/app/index.ts b/src/app/index.ts index 7226502..7554943 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -7,7 +7,7 @@ import { runPipeline, runSteps, PipelineStep } from '../pipeline'; import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http'; import type { HttpOptions } from '../http'; import { buildFetch } from '../http/web'; -import { matchWsRoute, runWsConnection, 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 { JsonTransformer, type ErrorRenderer } from '../transformers'; import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin'; @@ -491,7 +491,13 @@ async function spliceRemoteScopes( try { 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); const { providers, steps, routes } = buildRemote(link); const origin = `mesh:${teapot.url}`; @@ -816,7 +822,7 @@ function buildAppUpgrade( return; } - await meshControl.handle(ready); + await trackUntil(ready, meshControl.handle(ready), streams); return; } diff --git a/src/app/types.ts b/src/app/types.ts index c8a9bff..eb87af4 100644 --- a/src/app/types.ts +++ b/src/app/types.ts @@ -86,5 +86,12 @@ export interface RoutePlan { export interface MeshConfig { secret?: string; teapots?: Array<{ url: string; secret: string }>; + /** How long an RPC may wait for its teapot before failing with 504 (default: 30s). */ timeoutMs?: number; + /** + * Gap between heartbeat pings to each teapot (default: 15s). Two unanswered rounds close the + * link, so a half-open connection surfaces as an immediate 503 instead of every request paying + * `timeoutMs` first. Lower it to notice a dead teapot sooner, at the cost of more chatter. + */ + heartbeatMs?: number; } diff --git a/src/http/ws-core.ts b/src/http/ws-core.ts index 7a642bb..6a5bd71 100644 --- a/src/http/ws-core.ts +++ b/src/http/ws-core.ts @@ -31,6 +31,25 @@ export function matchWsRoute( .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, + streams?: Set<() => void>, +): Promise { + const { closer } = trackConnection(socket, streams); + + try { + await connection; + } finally { + streams?.delete(closer); + } +} + /** Registers the connection with the stream registry so it can be force-closed on shutdown. */ function trackConnection(socket: WsSocket, streams?: Set<() => void>): { closer: () => void } { const closer = () => { diff --git a/src/http/ws.ts b/src/http/ws.ts index 6c8188a..f738067 100644 --- a/src/http/ws.ts +++ b/src/http/ws.ts @@ -1,7 +1,7 @@ import type http from 'http'; import { channel } from '../channel'; 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'; /** 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, socket: any, head: Buffer, + streams?: Set<() => void>, ): boolean { if (path !== meshControl.path) return false; @@ -40,8 +41,14 @@ function handleMeshUpgrade( // 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. - // serveFrames swallows its own failures, so the floating promise cannot reject - wss.handleUpgrade(req, socket, head, (ws: any) => void meshControl.handle(nodeSocket(ws))); + // 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; } @@ -97,7 +104,7 @@ export function attachWs( server.on('upgrade', (req, socket, head) => { 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); diff --git a/src/mesh/link.ts b/src/mesh/link.ts index a2ce38e..1c98da3 100644 --- a/src/mesh/link.ts +++ b/src/mesh/link.ts @@ -18,11 +18,15 @@ type PendingEntry = { timer: ReturnType; }; -/** Reject and clear every in-flight RPC — used when the link closes. */ +/** + * Reject and clear every in-flight RPC — used when the link closes. + * 503, not a bare Error: a dead upstream is not "this service broke", and the status is what + * tells a caller it may retry and an operator where to look. A bare Error renders as a 500. + */ function rejectAllPending(pending: Map, reason: string): void { for (const [, entry] of pending) { clearTimeout(entry.timer); - entry.reject(new Error(reason)); + entry.reject(new HttpError(503, reason)); } pending.clear(); @@ -38,10 +42,19 @@ function sendRpc( ctx: RequestEnvelope, timeoutMs: number, ): Promise { + // Answer now rather than in timeoutMs. A closed socket cannot deliver the frame, so waiting + // would make every request to a downed teapot hang for the full timeout (30s by default) + // before failing anyway — the caller pays for a verdict already known. + if (!socket.isOpen) { + return Promise.reject(new HttpError(503, `mesh link is down: cannot resolve '${name}'`)); + } + return new Promise((resolveCall, rejectCall) => { + // 504: the link is alive but the teapot did not answer in time — a gateway timeout, + // which is a different operational story from a link that is down. const timer = setTimeout(() => { pending.delete(id); - rejectCall(new Error(`mesh rpc timeout: ${name}`)); + rejectCall(new HttpError(504, `mesh rpc timeout: ${name}`)); }, timeoutMs); pending.set(id, { resolve: resolveCall, reject: rejectCall, timer }); @@ -87,6 +100,50 @@ function settleRpcResponse( } } +/** Default gap between heartbeat pings. Two missed rounds close the link. */ +const HEARTBEAT_MS = 15_000; + +/** + * Close code for a link we hang up on because its teapot went quiet. + * + * Not 1011: a *client* may only send 1000 or 3000-4999 — anything else throws `invalid code`, + * and our neutral close swallows throws, so a reserved code would leave the link open while + * looking like it closed. 4000+ is the application range, so 4011 mirrors 1011's meaning. + */ +const CLOSE_HEARTBEAT_TIMEOUT = 4011; + +/** + * Pings the teapot on an interval and closes the link if a round goes unanswered. + * + * A TCP connection can die without either side noticing — a dropped route, a killed container, + * a NAT timing out — leaving the socket "open" with nobody home. Without this, a teacup only + * learns on the next request, which pays the full rpc timeout before failing. Closing the socket + * turns that into an immediate 503 from the dead-link guard, and emits `mesh:disconnect`. + * + * The interval is unref'd, so a heartbeat never holds the process open by itself. + */ +function startHeartbeat(socket: WsSocket, everyMs: number): { stop: () => void; markAlive: () => void } { + let answered = true; + + const timer = setInterval(() => { + if (!answered) { + socket.close(CLOSE_HEARTBEAT_TIMEOUT, 'mesh heartbeat timeout'); // aborts -> disconnect + reject pending + return; + } + + answered = false; + socket.send(encode({ type: 'ping' })); + }, everyMs); + timer.unref?.(); + + return { + stop: () => clearInterval(timer), + markAlive: () => { + answered = true; + }, + }; +} + /** Handle for the in-flight handshake, so the frame loop can settle `connectLink`'s promise. */ interface Handshake { url: string; @@ -97,6 +154,7 @@ interface Handshake { 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. */ @@ -129,6 +187,7 @@ async function readFrames(hs: Handshake): Promise { } 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); } } @@ -141,6 +200,7 @@ export function connectLink(args: { url: string; secret: string; timeoutMs?: number; + heartbeatMs?: number; bus?: Bus; Ctor?: SocketCtor; }): Promise { @@ -148,6 +208,7 @@ export function connectLink(args: { const { socket, opened } = connectSocket(args.url, args.Ctor ?? undefined); const pending = new Map(); let manifest = false; + let heartbeat: { stop: () => void; markAlive: () => void } | undefined; return new Promise((resolve, reject) => { const connectTimer = setTimeout(() => { @@ -166,7 +227,10 @@ export function connectLink(args: { onManifest: () => { manifest = true; clearTimeout(connectTimer); + // started only once authenticated: an unauthenticated peer should not be pinging + heartbeat = startHeartbeat(socket, args.heartbeatMs ?? HEARTBEAT_MS); }, + onPong: () => heartbeat?.markAlive(), }; opened.then( @@ -180,8 +244,9 @@ export function connectLink(args: { 'abort', () => { clearTimeout(connectTimer); + heartbeat?.stop(); args.bus?.emit('mesh:disconnect', { name: args.url }); - rejectAllPending(pending, 'mesh link closed'); + rejectAllPending(pending, `mesh link to ${args.url} is down`); if (!manifest) reject(new Error(`mesh handshake failed: ${args.url}`)); }, { once: true }, diff --git a/src/mesh/protocol.ts b/src/mesh/protocol.ts index 5f4b82b..9492fda 100644 --- a/src/mesh/protocol.ts +++ b/src/mesh/protocol.ts @@ -31,13 +31,21 @@ export interface Manifest { routes: RouteEntry[]; } -/** Discriminated union of every message on the mesh wire. The handshake frames carry `v`. */ +/** + * Discriminated union of every message on the mesh wire. The handshake frames carry `v`. + * + * `ping`/`pong` are application frames rather than WebSocket protocol pings on purpose: the `ws` + * package exposes `ws.ping()`, but the platform `WebSocket` that Deno and Bun provide does not, + * so a protocol-level heartbeat could not work on every runtime mesh claims to support. + */ export type Frame = | { type: 'hello'; v: number; secret: string } | { type: 'manifest'; v: number; scopes: ScopeEntry[]; routes: RouteEntry[] } | { type: 'rpc-req'; id: string; kind: 'scope' | 'route'; name: string; ctx: RequestEnvelope } | { type: 'rpc-res'; id: string; ok: true; result: unknown } - | { type: 'rpc-res'; id: string; ok: false; error: { message: string; status?: number } }; + | { type: 'rpc-res'; id: string; ok: false; error: { message: string; status?: number } } + | { type: 'ping' } + | { type: 'pong' }; const isString = (value: unknown): value is string => typeof value === 'string'; const isNumber = (value: unknown): boolean => typeof value === 'number'; @@ -71,6 +79,12 @@ const SHAPE: Record = { 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. */ diff --git a/src/mesh/teapot.ts b/src/mesh/teapot.ts index c59503b..dd5fdcf 100644 --- a/src/mesh/teapot.ts +++ b/src/mesh/teapot.ts @@ -167,6 +167,12 @@ async function serveFrames( 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')` diff --git a/test/mesh/failure.test.ts b/test/mesh/failure.test.ts new file mode 100644 index 0000000..88c1a75 --- /dev/null +++ b/test/mesh/failure.test.ts @@ -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(); + }); +}); diff --git a/test/mesh/heartbeat.test.ts b/test/mesh/heartbeat.test.ts new file mode 100644 index 0000000..9acf2f4 --- /dev/null +++ b/test/mesh/heartbeat.test.ts @@ -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(); + }); +}); diff --git a/website/src/content/docs/guides/mesh.md b/website/src/content/docs/guides/mesh.md index b3d9df6..e46c97a 100644 --- a/website/src/content/docs/guides/mesh.md +++ b/website/src/content/docs/guides/mesh.md @@ -112,6 +112,28 @@ declared locally — the local route takes precedence and the remote one will no 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. From 4081106813914a05fd025dfe8c7197215956ae96 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 17 Jul 2026 15:50:59 -0500 Subject: [PATCH 134/139] 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 --- src/pipeline.ts | 4 ++-- test/pipeline.test.ts | 35 ++++++++++++++++++++++++++++++++++- 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/src/pipeline.ts b/src/pipeline.ts index 1003e49..680e25b 100644 --- a/src/pipeline.ts +++ b/src/pipeline.ts @@ -47,12 +47,12 @@ export function isStreamResult(result: PipelineResult): result is StreamResult { */ export async function runSteps(steps: PipelineStep[], seed: Record, bus: Bus): Promise { // context is intentionally `any`: each step merges arbitrary keys into the accumulator - let context: any = seed; + 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); - context = { ...context, ...output }; + Object.assign(context, output); bus.emit('request:step:leave', { name: step.name, scope: step.origin }); } diff --git a/test/pipeline.test.ts b/test/pipeline.test.ts index 24e7168..abeb142 100644 --- a/test/pipeline.test.ts +++ b/test/pipeline.test.ts @@ -1,5 +1,5 @@ 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 { JsonTransformer } from '../src/transformers'; import { Unauthorized } from '../src/signals'; @@ -100,3 +100,36 @@ describe('runPipeline transport enforcement', () => { 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); + }); +}); From 642ef109b2bda336bae0bc08cc985dda0f1eeecb Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 17 Jul 2026 16:25:31 -0500 Subject: [PATCH 135/139] 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 --- src/app/index.ts | 29 +++++++++++++++++++++-- test/graph-depth.test.ts | 50 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 2 deletions(-) create mode 100644 test/graph-depth.test.ts diff --git a/src/app/index.ts b/src/app/index.ts index 7554943..f265dca 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -104,6 +104,12 @@ export function createApp(opts: { static?: boolean | string; /** Opt in to alpha features whose API may still change. Currently gates `mesh`. */ experimental?: boolean; + /** + * Warn at boot when a route's dependency chain resolves to more than this many steps (default 20; + * `false` silences). A design nudge, not a perf limit — deep graphs run fine (cost is linear), but + * 20+ steps on one route usually means a step is doing too much. + */ + warnGraphDepth?: number | false; }): App { // mesh is alpha: its API and wire protocol may change. Require an explicit opt-in. if (opts.mesh && !opts.experimental) { @@ -136,7 +142,7 @@ export function createApp(opts: { const meshLinks: Link[] = []; const finalize = (): void => { - ({ orderedProviders, orderedSteps } = finalizeGraph(registry)); + ({ orderedProviders, orderedSteps } = finalizeGraph(registry, opts.warnGraphDepth)); booted = true; }; @@ -437,11 +443,19 @@ function provideBuiltins(registry: Registry): void { registry.setRunner('rooms', () => ({ rooms: roomsInstance })); // merge object -> ctx.rooms } +// Boot-time nudge: a route whose need-closure pulls this many steps is almost always a modeling +// smell (a step doing too much, or work that belongs in a provider), not a real dependency depth. +// Cost is linear so it isn't a perf problem — it's a design one. Generous on purpose. +const DEEP_GRAPH_WARN = 20; + /** * Topo-sorts the graph, slices each route's provider/step closure into its plan, and validates every need. * @returns The app-scope providers and request-scope steps in execution order. */ -function finalizeGraph(registry: Registry): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } { +function finalizeGraph( + registry: Registry, + warnDepth: number | false = DEEP_GRAPH_WARN, +): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } { const { providerNodes, stepNodes, routePlans } = registry; const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params']); const orderedProviders = ordered.filter((node) => providerNodes.includes(node)); @@ -454,6 +468,17 @@ function finalizeGraph(registry: Registry): { orderedProviders: GraphNode[]; ord plan.providers = closure.filter((node) => providerNodes.includes(node)); const sliced = new Set([...closure.filter((node) => stepNodes.includes(node)), ...alwaysSteps]); plan.steps = ordered.filter((node) => stepNodes.includes(node) && sliced.has(node)); // topo order, deduped + + // The route's own dependency depth, excluding always-on observer steps (plugins). + const depth = closure.filter((node) => stepNodes.includes(node)).length; + + if (warnDepth !== false && depth > warnDepth) { + console.warn( + `[green-tea] ${plan.method} ${plan.pattern} resolves to ${depth} steps — an unusually deep dependency chain. ` + + `It runs fine (per-request cost is linear), but ${warnDepth}+ steps on one route usually means a step ` + + `is doing too much or the graph wants splitting. If it's intentional, ignore this.`, + ); + } } assertNeedsSatisfiable(routePlans, providerNodes, stepNodes); diff --git a/test/graph-depth.test.ts b/test/graph-depth.test.ts new file mode 100644 index 0000000..7726ab4 --- /dev/null +++ b/test/graph-depth.test.ts @@ -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(); + }); +}); From 3a4cd5a7ceac8b4cbbd7a872ae8088102b104b24 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 17 Jul 2026 19:05:52 -0500 Subject: [PATCH 136/139] test(bench): reach bench servers cross-host + add scale and Bun/Deno servers 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 --- bench/servers/fastify.ts | 2 +- bench/servers/green-tea-bun.ts | 34 ++++++++++++++++++++++++++++++++ bench/servers/green-tea-deno.ts | 33 +++++++++++++++++++++++++++++++ bench/servers/nestjs-express.ts | 2 +- bench/servers/nestjs-fastify.ts | 2 +- bench/servers/scale-express.ts | 26 ++++++++++++++++++++++++ bench/servers/scale-green-tea.ts | 33 +++++++++++++++++++++++++++++++ 7 files changed, 129 insertions(+), 3 deletions(-) create mode 100644 bench/servers/green-tea-bun.ts create mode 100644 bench/servers/green-tea-deno.ts create mode 100644 bench/servers/scale-express.ts create mode 100644 bench/servers/scale-green-tea.ts diff --git a/bench/servers/fastify.ts b/bench/servers/fastify.ts index 9cd8833..8ea42bf 100644 --- a/bench/servers/fastify.ts +++ b/bench/servers/fastify.ts @@ -12,7 +12,7 @@ app.post('/validate', { if (!b.email.includes('@')) { reply.code(422); return { error: 'invalid' }; } 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); } console.log(`READY ${Number(new URL(addr).port)}`); }); diff --git a/bench/servers/green-tea-bun.ts b/bench/servers/green-tea-bun.ts new file mode 100644 index 0000000..2b5cbfa --- /dev/null +++ b/bench/servers/green-tea-bun.ts @@ -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}`); diff --git a/bench/servers/green-tea-deno.ts b/bench/servers/green-tea-deno.ts new file mode 100644 index 0000000..70b0319 --- /dev/null +++ b/bench/servers/green-tea-deno.ts @@ -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}`) }); diff --git a/bench/servers/nestjs-express.ts b/bench/servers/nestjs-express.ts index 7945244..210de81 100644 --- a/bench/servers/nestjs-express.ts +++ b/bench/servers/nestjs-express.ts @@ -9,7 +9,7 @@ async function main() { inst.disable('x-powered-by'); inst.set('etag', 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(); server.keepAliveTimeout = 5000; // parity (works on Node http.Server after listen) console.log(`READY ${server.address().port}`); diff --git a/bench/servers/nestjs-fastify.ts b/bench/servers/nestjs-fastify.ts index 4b95565..9556f98 100644 --- a/bench/servers/nestjs-fastify.ts +++ b/bench/servers/nestjs-fastify.ts @@ -6,7 +6,7 @@ import { BenchModule } from './_nest-shared'; async function main() { const adapter = new FastifyAdapter({ logger: false, keepAliveTimeout: 5000 }); // parity via constructor const app = await NestFactory.create(BenchModule, adapter, { logger: false }); - await app.listen(0, '127.0.0.1'); + await app.listen(0, '0.0.0.0'); const server = app.getHttpServer(); console.log(`READY ${(server.address() as any).port}`); } diff --git a/bench/servers/scale-express.ts b/bench/servers/scale-express.ts new file mode 100644 index 0000000..16c843d --- /dev/null +++ b/bench/servers/scale-express.ts @@ -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}`); +}); diff --git a/bench/servers/scale-green-tea.ts b/bench/servers/scale-green-tea.ts new file mode 100644 index 0000000..e351994 --- /dev/null +++ b/bench/servers/scale-green-tea.ts @@ -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); }); From 2a84331022bb7364649daeb06c7ccaddd1f629a0 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 17 Jul 2026 20:36:36 -0500 Subject: [PATCH 137/139] ci: relocate CI workflow to .github/workflows for two-forge compatibility MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- {.gitea => .github}/workflows/ci.yml | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {.gitea => .github}/workflows/ci.yml (100%) diff --git a/.gitea/workflows/ci.yml b/.github/workflows/ci.yml similarity index 100% rename from .gitea/workflows/ci.yml rename to .github/workflows/ci.yml From 33df70730bdbdc7f14c1140d46c8aeffa085e69d Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 17 Jul 2026 20:43:43 -0500 Subject: [PATCH 138/139] ci: add stage/promote/release workflows for the two-forge pipeline 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 --- .github/workflows/promote.yml | 30 ++++++++++++++++++++++++++++++ .github/workflows/release.yml | 26 ++++++++++++++++++++++++++ .github/workflows/stage.yml | 28 ++++++++++++++++++++++++++++ 3 files changed, 84 insertions(+) create mode 100644 .github/workflows/promote.yml create mode 100644 .github/workflows/release.yml create mode 100644 .github/workflows/stage.yml diff --git a/.github/workflows/promote.yml b/.github/workflows/promote.yml new file mode 100644 index 0000000..4758498 --- /dev/null +++ b/.github/workflows/promote.yml @@ -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 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..1dd85f6 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,26 @@ +name: Release → npmjs + +# Production publish. Runs on GITHUB ONLY, on a version tag (`v*`). Publishes the stable +# package (version from package.json) to the public npmjs registry under `latest`. +# The tag arrives via the promote workflow; the version should be stable (no prerelease) +# before tagging. +on: + push: + tags: ['v*'] + +jobs: + publish-prod: + if: ${{ github.server_url == 'https://github.com' }} + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '22' + registry-url: 'https://registry.npmjs.org' + - run: npm ci + # `npm publish` runs prepublishOnly (lint + complexity + typecheck + test + build) first. + - name: Publish to npmjs + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + run: npm publish --access public diff --git a/.github/workflows/stage.yml b/.github/workflows/stage.yml new file mode 100644 index 0000000..9b467a4 --- /dev/null +++ b/.github/workflows/stage.yml @@ -0,0 +1,28 @@ +name: Stage → Verdaccio + +# Staging publish. Runs on GITEA ONLY (the `if` guards against GitHub), on every merge +# to main. Publishes the package as-is — version comes from package.json (a prerelease +# like 26.7.1-stg.N) — to the internal Verdaccio under the `stg` dist-tag. Verdaccio +# allows overwrite, so re-publishing the same version is a no-op-ish refresh. +on: + push: + branches: [main] + +jobs: + publish-stg: + if: ${{ github.server_url != 'https://github.com' }} + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '22' + - run: npm ci + # `npm publish` runs prepublishOnly (lint + complexity + typecheck + test + build) + # as its own gate before anything leaves the machine. + - name: Publish to Verdaccio + env: + NODE_AUTH_TOKEN: ${{ secrets.VERDACCIO_TOKEN }} + run: | + npm config set //npm.svc.zoit.services/:_authToken "$NODE_AUTH_TOKEN" + npm publish --registry https://npm.svc.zoit.services --tag stg From 96d863d4026fd0f21828ecf41819d4d0fe1cbf80 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 17 Jul 2026 21:17:17 -0500 Subject: [PATCH 139/139] ci: use the NPM_AUTH secret for both Verdaccio and npmjs publishes 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 --- .github/workflows/release.yml | 2 +- .github/workflows/stage.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1dd85f6..4eb5f05 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -22,5 +22,5 @@ jobs: # `npm publish` runs prepublishOnly (lint + complexity + typecheck + test + build) first. - name: Publish to npmjs env: - NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + NODE_AUTH_TOKEN: ${{ secrets.NPM_AUTH }} run: npm publish --access public diff --git a/.github/workflows/stage.yml b/.github/workflows/stage.yml index 9b467a4..2822bf2 100644 --- a/.github/workflows/stage.yml +++ b/.github/workflows/stage.yml @@ -22,7 +22,7 @@ jobs: # as its own gate before anything leaves the machine. - name: Publish to Verdaccio env: - NODE_AUTH_TOKEN: ${{ secrets.VERDACCIO_TOKEN }} + NODE_AUTH_TOKEN: ${{ secrets.NPM_AUTH }} run: | npm config set //npm.svc.zoit.services/:_authToken "$NODE_AUTH_TOKEN" npm publish --registry https://npm.svc.zoit.services --tag stg