feat(http): complete HEAD and OPTIONS semantics

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-08-02 20:45:44 -05:00
1 parent 63be0ef8f7
commit 9a61ba8646
7 files changed
+207 -41

No files matched your search

+74 -24
View File
@@ -3,7 +3,7 @@ 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 { resolveRoute, allowedMethods, normalizeRequestPath, parseQuery } from './router';
import { pickEncoder } from './stream';
import type { RouteDef, HttpOptions } from './types';
import type { StreamEncoder } from '../encoders';
@@ -49,6 +49,61 @@ export function computeInjected(
return injected;
}
function errorOutcome(
error: unknown,
req: NeutralRequest,
injected: Record<string, string>,
opts: HttpOptions | undefined,
headers: Record<string, string> = {},
): HandleResult {
const rendered = renderError(error, { method: req.method, url: req.url, headers: req.headers }, opts?.onError);
return {
injected,
outcome: {
kind: 'buffered',
status: rendered.status,
headers: { ...rendered.headers, ...headers },
body: req.method === 'HEAD' ? '' : rendered.body,
},
};
}
async function unmatchedOutcome(
routes: RouteDef[],
opts: HttpOptions | undefined,
req: NeutralRequest,
path: string,
injected: Record<string, string>,
): Promise<HandleResult> {
if ((req.method === 'GET' || req.method === 'HEAD') && opts?.static) {
const hit = await opts.static(path);
if (hit) {
return {
injected,
outcome: {
kind: 'buffered',
status: 200,
headers: { 'content-type': hit.contentType },
body: req.method === 'HEAD' ? '' : hit.body,
},
};
}
}
const allow = allowedMethods(routes, path);
if (req.method === 'OPTIONS' && allow.length) {
return {
injected,
outcome: { kind: 'buffered', status: 204, headers: { allow: allow.join(', ') }, body: '' },
};
}
const error = allow.length ? new HttpError(405, 'Method Not Allowed') : new NotFound('Not Found');
return errorOutcome(error, req, injected, opts, allow.length ? { allow: allow.join(', ') } : {});
}
/**
* 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
@@ -59,35 +114,22 @@ export async function handle(
opts: HttpOptions | undefined,
req: NeutralRequest,
): Promise<HandleResult | Preflight> {
const path = req.url.split('?')[0];
const injected = computeInjected(opts, req);
let path: string;
try {
path = normalizeRequestPath(req.url.split('?')[0]);
} catch {
return errorOutcome(new HttpError(400, 'Bad Request'), req, injected, opts);
}
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);
const matched = resolveRoute(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');
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 } };
}
if (!matched) return unmatchedOutcome(routes, opts, req, path, injected);
let result: PipelineResult;
@@ -111,5 +153,13 @@ export async function handle(
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 } };
return {
injected,
outcome: {
kind: 'buffered',
status: result.status,
headers: result.headers,
body: req.method === 'HEAD' ? '' : result.body,
},
};
}
+35 -2
View File
@@ -249,11 +249,44 @@ export function matchRoute(routes: RouteDef[], method: string, path: string): Ma
return best;
}
/** Route resolution adds the one HTTP fallback the matcher supports: buffered GET serves HEAD. */
export interface ResolvedRoute extends MatchedRoute {
implicitHead: boolean;
}
export function resolveRoute(routes: RouteDef[], method: string, path: string): ResolvedRoute | undefined {
const explicit = matchRoute(routes, method, path);
if (explicit) return { ...explicit, implicitHead: false };
if (method !== 'HEAD') return undefined;
const fallback = matchRoute(
routes.filter((route) => route.transport === 'buffer'),
'GET',
path,
);
return fallback ? { ...fallback, implicitHead: true } : undefined;
}
const METHOD_ORDER = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
/** 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<string>();
for (const route of routes) if (matchPattern(route.pattern, path)) methods.add(route.method);
return [...methods];
for (const route of routes) {
if (!matchPattern(route.pattern, path)) continue;
methods.add(route.method);
if (route.method === 'GET' && route.transport === 'buffer') methods.add('HEAD');
}
if (methods.size) methods.add('OPTIONS');
return [...methods].sort((a, b) => {
const indexA = METHOD_ORDER.indexOf(a);
const indexB = METHOD_ORDER.indexOf(b);
return (
(indexA < 0 ? METHOD_ORDER.length : indexA) - (indexB < 0 ? METHOD_ORDER.length : indexB) || a.localeCompare(b)
);
});
}
/** Parses a URL's query string into a flat string map (last value wins for repeated keys). */
+8 -2
View File
@@ -5,7 +5,7 @@ import { isHttpError, HttpError } from '../signals';
import type { Bus } from '../bus';
import { buildSecurityHeaders, resolveCors } from '../security';
import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart';
import { matchRoute } from './router';
import { normalizeRequestPath, resolveRoute } from './router';
import { readBody, deriveSecure, deriveIp } from './request';
import { pipeStream } from './stream';
import { attachWs } from './ws';
@@ -93,7 +93,13 @@ function createRequestHandler(cfg: HandlerConfig) {
// 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 matched: ReturnType<typeof resolveRoute>;
try {
matched = isPreflight ? undefined : resolveRoute(routes, method, normalizeRequestPath(path));
} catch {
matched = undefined; // handle() owns the standard 400 envelope and injected headers
}
let body: unknown;
+11 -3
View File
@@ -2,7 +2,7 @@ import type { StreamEncoder } from '../encoders';
import { handle, computeInjected, type HandleResult } from './core';
import { mergeInjectedHeaders } from './headers';
import { parseRequestBody } from './server';
import { matchRoute } from './router';
import { normalizeRequestPath, resolveRoute } from './router';
import { HttpError } from '../signals';
import { renderError, type ErrorRequest, type ErrorResponse } from '../transformers';
import type { RouteDef, HttpOptions, MatchedRoute } from './types';
@@ -108,7 +108,8 @@ function outcomeToResponse(result: HandleResult): Response {
return new Response(asReadableStream(result.outcome.stream, result.outcome.encoder), { headers });
}
return new Response(result.outcome.body, { status: result.outcome.status, headers });
const body = [204, 205, 304].includes(result.outcome.status) ? null : result.outcome.body;
return new Response(body, { status: result.outcome.status, headers });
}
/**
@@ -123,7 +124,14 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
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 matched: ReturnType<typeof resolveRoute>;
try {
matched = resolveRoute(routes, request.method, normalizeRequestPath(url.pathname));
} catch {
matched = undefined; // handle() renders the shared 400 response without reading a body
}
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