feat: beta-hardening — routing, degradation, mesh gate, uploads, @header

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 <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-07-07 12:00:15 -05:00
1 parent 9d79972f62
commit d6c5cee0ee
42 files changed
+2619 -1170

No files matched your search

+54 -23
View File
@@ -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<string, string>;
/** Incoming request headers; a header may repeat, hence the array variant. */
export type Headers = Record<string, string | string[] | undefined>;
/** Per-request bag that accumulates values produced by steps and providers. */
export type Context = Record<string, unknown>;
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<string, ArgSpec[]> = 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<unknown[]> {
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<string, unknown>;
if (s.keys) {
const out: Record<string, unknown> = {};
for (const k of s.keys) out[k] = record[k];
return out;
const values = bag as Record<string, unknown>;
if (spec.keys) {
const picked: Record<string, unknown> = {};
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;
}