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

+97 -89
View File
@@ -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<string, string | string[]>;
files: Record<string, UploadedFile | UploadedFile[]>;
}
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<string, string | string[]> {
const out: Record<string, string | string[]> = {};
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<MultipartBody> {
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<MultipartBody>((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);
});
}