Skip to content

Commit 2c08962

Browse files
authored
perf(http): specialize security headers by response kind (#57)
* test: refresh generated playground expectations * perf(http): specialize security headers by response kind
1 parent 6388527 commit 2c08962

16 files changed

Lines changed: 103 additions & 33 deletions

File tree

‎packages/cli/src/new/starter-configs.generated.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ export const STARTER_CONFIG_FILES: readonly GeneratedStarterConfigFile[] = Objec
1919
}),
2020
Object.freeze({
2121
path: "src/config/logging.config.ts",
22-
content: "import { envBoolean, envNumber, envString } from \"@warblerjs/config\";\n\nexport const loggingConfig = {\n /*\n * Application environment.\n *\n * development and staging keep framework-owned informational logs enabled so\n * route, transport, and WebSocket behavior is easy to inspect while building.\n *\n * production disables informational hot-path logs by default. Errors and fatal\n * process failures stay enabled unless explicitly overridden below.\n */\n environment: envString(\"APP_ENV\", \"development\"),\n\n /*\n * HTTP request/access logging.\n *\n * When disabled, Warbler selects a quiet HTTP handler at startup. The request\n * path avoids request-log formatting, request-log objects, logging-only timing,\n * and stdout writes for successful requests.\n */\n requests: envBoolean(\"LOG_REQUESTS\", envString(\"APP_ENV\", \"development\") !== \"production\"),\n\n /*\n * Runtime lifecycle informational logs.\n *\n * Covers framework-owned runtime stop/status messages. Disable in production\n * to keep process output quiet outside exceptional conditions.\n */\n runtime: envBoolean(\"LOG_RUNTIME\", envString(\"APP_ENV\", \"development\") !== \"production\"),\n\n /*\n * Transport informational logs.\n *\n * Used by framework-owned transport startup/stop notices. This does not disable\n * transports or change routing, validation, security, or application behavior.\n */\n transports: envBoolean(\"LOG_TRANSPORTS\", envString(\"APP_ENV\", \"development\") !== \"production\"),\n\n /*\n * WebSocket infrastructure logs.\n *\n * When disabled, Warbler avoids connection/message/disconnect log formatting\n * and logging-only timing while preserving subscriptions, publishing, guards,\n * validators, rate limits, and error boundaries.\n */\n websocket: envBoolean(\"LOG_WEBSOCKET\", envString(\"APP_ENV\", \"development\") !== \"production\"),\n\n /*\n * Error logging.\n *\n * Enabled by default in every environment. Error logs never include request\n * bodies, credentials, passwords, tokens, or secrets.\n */\n errors: envBoolean(\"LOG_ERRORS\", true),\n\n /*\n * Fatal process logging.\n *\n * Enabled by default in every environment. This is only for process-level\n * uncaught exceptions/unhandled rejections that escape normal boundaries.\n */\n fatal: envBoolean(\"LOG_FATAL\", true),\n\n /*\n * Startup output and debug logs.\n *\n * Kept separate from request logging because startup is outside the request hot\n * path. Production defaults keep it quiet unless explicitly enabled.\n */\n startup: envBoolean(\"LOG_STARTUP\", envString(\"APP_ENV\", \"development\") !== \"production\"),\n debug: envBoolean(\"LOG_DEBUG\", envString(\"APP_ENV\", \"development\") !== \"production\"),\n\n channels: {\n console: {\n enabled: envBoolean(\"LOG_CONSOLE\", true),\n },\n file: {\n enabled: envBoolean(\"LOG_FILE\", true),\n path: envString(\"LOG_FILE_PATH\", \"storage/logs\"),\n rotation: \"daily\",\n retentionDays: envNumber(\"LOG_RETENTION_DAYS\", 14),\n cleanup: \"internal\",\n format: \"pretty\",\n },\n },\n} as const;\n",
22+
content: "import { envBoolean, envNumber, envString } from \"@warblerjs/config\";\n\nexport const loggingConfig = {\n /*\n * Application environment.\n *\n * development and staging keep framework-owned informational logs enabled so\n * route, transport, and WebSocket behavior is easy to inspect while building.\n *\n * production disables informational hot-path logs by default. Errors and fatal\n * process failures stay enabled unless explicitly overridden below.\n */\n environment: envString(\"APP_ENV\", \"development\"),\n\n /*\n * HTTP request/access logging.\n *\n * When disabled, Warbler selects a quiet HTTP handler at startup. The request\n * path avoids request-log formatting, request-log objects, logging-only timing,\n * and stdout writes for successful requests.\n */\n requests: envString(\"APP_ENV\", \"development\") === \"production\" ? false : envBoolean(\"LOG_REQUESTS\", false),\n\n /*\n * Runtime lifecycle informational logs.\n *\n * Covers framework-owned runtime stop/status messages. Disable in production\n * to keep process output quiet outside exceptional conditions.\n */\n runtime: envString(\"APP_ENV\", \"development\") === \"production\" ? false : envBoolean(\"LOG_RUNTIME\", false),\n\n /*\n * Transport informational logs.\n *\n * Used by framework-owned transport startup/stop notices. This does not disable\n * transports or change routing, validation, security, or application behavior.\n */\n transports: envString(\"APP_ENV\", \"development\") === \"production\" ? false : envBoolean(\"LOG_TRANSPORTS\", false ),\n\n /*\n * WebSocket infrastructure logs.\n *\n * When disabled, Warbler avoids connection/message/disconnect log formatting\n * and logging-only timing while preserving subscriptions, publishing, guards,\n * validators, rate limits, and error boundaries.\n */\n websocket: envBoolean(\"LOG_WEBSOCKET\", envString(\"APP_ENV\", \"development\") !== \"production\"),\n\n /*\n * Error logging.\n *\n * Enabled by default in every environment. Error logs never include request\n * bodies, credentials, passwords, tokens, or secrets.\n */\n errors: envString(\"APP_ENV\", \"development\") === \"production\" ? false : envBoolean(\"LOG_ERRORS\", true),\n\n /*\n * Fatal process logging.\n *\n * Enabled by default in every environment. This is only for process-level\n * uncaught exceptions/unhandled rejections that escape normal boundaries.\n */\n fatal: envString(\"APP_ENV\", \"development\") === \"production\" ? false : envBoolean(\"LOG_FATAL\", true),\n\n /*\n * Startup output and debug logs.\n *\n * Kept separate from request logging because startup is outside the request hot\n * path. Production defaults keep it quiet unless explicitly enabled.\n */\n startup: envString(\"APP_ENV\", \"development\") === \"production\" ? false : envBoolean(\"LOG_STARTUP\", false),\n debug: envString(\"APP_ENV\", \"development\") === \"production\" ? false : envBoolean(\"LOG_DEBUG\", false),\n\n channels: {\n console: {\n enabled: envString(\"APP_ENV\", \"development\") === \"production\" ? false : envBoolean(\"LOG_CONSOLE\", true),\n },\n file: {\n enabled: envBoolean(\"LOG_FILE\", true),\n path: envString(\"LOG_FILE_PATH\", \"storage/logs\"),\n rotation: \"daily\",\n retentionDays: envNumber(\"LOG_RETENTION_DAYS\", 14),\n cleanup: \"internal\",\n format: \"pretty\",\n },\n },\n} as const;\n",
2323
}),
2424
Object.freeze({
2525
path: "src/config/mail.config.ts",

‎packages/compiler/src/analyzer/analyze-program.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -269,13 +269,18 @@ function declarativeHttpRoutes(
269269
}
270270
const inherited = handlerOptionsFor(handlerOptions, handler);
271271
const validator = inlineOptions === undefined ? inherited.validator : objectReference(inlineOptions, "validator");
272+
const routeOptions = inlineOptions ?? options;
273+
const response = routeOptions === undefined
274+
? undefined
275+
: objectEnum(routeOptions, "response", ["static", "view", "json", "html", "text"]);
272276
routes.push(Object.freeze({
273277
...location(property, source),
274278
method: parsed.method,
275279
path: parsed.path,
276280
handler,
277281
...(inlineOptions === undefined ? {} : { handlerExpression: captureExpression(helperCall ?? inlineOptions, aliases, source) }),
278282
...(validator === undefined ? {} : { validator }),
283+
...(response === undefined ? {} : { response }),
279284
...(inlineOptions !== undefined
280285
? objectStringOrUndefined(inlineOptions, "name") === undefined ? {} : { name: objectStringOrUndefined(inlineOptions, "name")! }
281286
: options === undefined ? {} : objectStringOrUndefined(options, "name") === undefined ? {} : { name: objectStringOrUndefined(options, "name")! }),
@@ -960,4 +965,4 @@ function location(node: ts.Node, source: ts.SourceFile): SourceLocationWIR {
960965
export function diagnostic(output: CompilerDiagnostic[], code: string, message: string, node: ts.Node, source: ts.SourceFile, relatedSymbols: readonly string[]): void {
961966
const point = source.getLineAndCharacterOfPosition(node.getStart(source));
962967
output.push(Object.freeze({ code, category: "error", message, sourceFile: source.fileName, line: point.line + 1, column: point.character + 1, relatedSymbols: Object.freeze([...relatedSymbols]) }));
963-
}
968+
}

‎packages/compiler/src/flags/flags.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ export const RouteFlag = Object.freeze({
1717
JSON: 1 << 14,
1818
HTML: 1 << 15,
1919
VIEW_CONTEXT: 1 << 16,
20+
TEXT: 1 << 17,
2021
} as const);
2122

2223
/** Compact WebSocket event policy flags. */

‎packages/compiler/src/optimizer/optimize-wir.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,7 @@ function routeFlags(route: RouteWIR, middlewareCount: number): number {
150150
(route.response === "view" ? RouteFlag.VIEW : 0) |
151151
(route.response === "json" ? RouteFlag.JSON : 0) |
152152
(route.response === "html" ? RouteFlag.HTML : 0) |
153+
(route.response === "text" ? RouteFlag.TEXT : 0) |
153154
(route.viewContext ? RouteFlag.VIEW_CONTEXT : 0);
154155
}
155156
function socketFlags(event: SocketEventWIR): number {

‎packages/compiler/src/wir/wir.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ export interface RouteWIR extends SourceLocationWIR {
2424
readonly csrf: boolean;
2525
readonly viewContext: boolean;
2626
readonly stream?: "sse" | "html";
27-
readonly response?: "static" | "view" | "json" | "html";
27+
readonly response?: "static" | "view" | "json" | "html" | "text";
2828
}
2929
/** Socket subscription or lifecycle metadata. */
3030
export interface SocketEventWIR extends SourceLocationWIR {

‎packages/compiler/tests/phase2.test.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,7 @@ describe("executable bindings", () => {
234234
const root = await phase2Project();
235235
await Bun.write(join(root, "src", "application.ts"), `
236236
import { createApp } from "@warblerjs/core";
237-
import { defineHttpGraph, defineHttpRoute, JsonRes } from "@warblerjs/http";
237+
import { defineHttpGraph, defineHttpRoute, TextRes } from "@warblerjs/http";
238238
import { defineValidator, v } from "@warblerjs/validators";
239239
240240
export const ValidateUser = defineValidator({
@@ -245,9 +245,10 @@ describe("executable bindings", () => {
245245
export const http = defineHttpGraph({
246246
routes: {
247247
"GET /users/:id": defineHttpRoute({
248+
response: "text",
248249
validator: ValidateUser,
249250
run(ctx) {
250-
return JsonRes({ id: ctx.params.id, page: ctx.query.page });
251+
return TextRes(ctx.params.id' + : +'ctx.query.page);
251252
},
252253
}),
253254
},
@@ -261,12 +262,17 @@ describe("executable bindings", () => {
261262
const directory = join(root, ".warbler", "generated");
262263
const handlers = await Bun.file(join(directory, "handlers.generated.ts")).text();
263264
const validators = await Bun.file(join(directory, "validators.generated.ts")).text();
265+
const http = await Bun.file(
266+
join(directory, "http.generated.ts"),
267+
).text();
268+
264269
expect(handlers).toContain("const Handler0 =");
265270
expect(handlers).toContain("defineHttpRoute");
266271
expect(handlers).toContain("ValidateUser");
267272
expect(handlers).toContain("Handler0.run(...input)");
268273
expect(validators).toContain("compileValidator");
269274
expect(validators).toContain("ValidateUser");
275+
expect(http).toContain('"flags":131201');
270276
}, 15_000);
271277

272278
test("emits exported values, direct handlers, scopes, and one Runtime manifest", async () => {

‎packages/framework/src/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ export type {
8484
RedirectStatus,
8585
RouteParameter,
8686
WarblerRequestContext,
87+
HttpRouteResponseKind,
8788
} from "@warblerjs/http";
8889

8990
export {

‎packages/http/src/graph.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,12 @@ import type { AnyRequestValidator, AppRequest } from "./request";
77

88
export type HttpMethod = HttpMethodValue;
99
export type HttpRouteKey = `${HttpMethod} /${string}`;
10+
export type HttpRouteResponseKind =
11+
| "static"
12+
| "view"
13+
| "json"
14+
| "html"
15+
| "text";
1016
type EmptyRequestSection = Readonly<Record<never, never>>;
1117
type RoutePath<TKey extends string> = TKey extends `${HttpMethodValue} ${infer TPath}` ? TPath : never;
1218
type PathParamName<TSegment extends string> = TSegment extends `:${infer TName}` ? TName extends "" ? never : TName : never;
@@ -82,6 +88,7 @@ export type HttpGraphRoute<THandler = unknown, TRouteKey extends HttpRouteKey =
8288
| Readonly<{
8389
readonly handler: THandler;
8490
readonly name?: string;
91+
readonly response?: HttpRouteResponseKind;
8592
readonly middlewares?: readonly unknown[];
8693
}>;
8794

@@ -95,6 +102,7 @@ export type HttpInlineGraphRoute<
95102
readonly validator?: TValidator;
96103
readonly guards?: readonly unknown[];
97104
readonly middlewares?: readonly unknown[];
105+
readonly response?: HttpRouteResponseKind;
98106
readonly useCase?: TUseCase;
99107
readonly run: InlineRouteRun<TRouteKey, TValidator, TUseCase, TResult>;
100108
}>;
@@ -109,6 +117,7 @@ export type DefinedHttpInlineGraphRoute<
109117
readonly guards?: readonly unknown[];
110118
readonly middlewares?: readonly unknown[];
111119
readonly useCase?: TUseCase;
120+
readonly response?: HttpRouteResponseKind;
112121
readonly run: ValidatorOnlyRun<TValidator, TUseCase, TResult>;
113122
readonly __warblerRouteValidator?: () => TValidator;
114123
}>;

‎packages/http/src/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ export {
99
type HttpGraphRoute,
1010
type HttpMethod as HttpMethodType,
1111
type HttpRouteKey,
12+
type HttpRouteResponseKind,
1213
type HttpRouteTable,
1314
} from "./graph";
1415
export { Delete, Get, Head, Options, Patch, Post, Put, Sse } from "./route";

‎packages/http/src/security/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ export {
66
applySecurityHeaders,
77
createSecurityHeaderApplicator,
88
createSecurityHeaderTemplate,
9+
createApiSecurityHeaderTemplate,
910
type SecurityHeaderApplicator,
1011
type SecurityHeaderPolicy,
1112
} from "./security-headers";

0 commit comments

Comments
 (0)