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

+4
View File
@@ -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();
});
+9 -5
View File
@@ -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();
});
+2 -2
View File
@@ -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' });
});
+38 -35
View File
@@ -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();
});
});
+87 -13
View File
@@ -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<unknown>, @abort() sig: AbortSignal) { return [inc, sig]; } }
class Ctl {
handle(@inbound() inc: AsyncIterable<unknown>, @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<unknown>, @abort() _a: AbortSignal) {} }
class Ctl {
handle(@inbound() _i: AsyncIterable<unknown>, @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();
});
});
+52
View File
@@ -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([]);
});
});
+6 -3
View File
@@ -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 () => {