From 93a4246de5a61acfb186b6397a1bd7c0eb78d02c Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 14:15:26 -0500 Subject: [PATCH] =?UTF-8?q?feat(app):=20app.fetch=20=E2=80=94=20Web-Standa?= =?UTF-8?q?rds=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'); + }); +});