@zudojs/http 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +64 -6
  2. package/dist/httpAdapter/http.adapter.d.ts +34 -3
  3. package/dist/httpAdapter/http.adapter.js +28 -10
  4. package/dist/httpAdapter/http.adapters.js +4 -34
  5. package/dist/httpAdapter/httpAdapter.errorResponse.d.ts +35 -0
  6. package/dist/httpAdapter/httpAdapter.errorResponse.js +137 -0
  7. package/dist/httpAdapter/httpAdapter.logger.d.ts +19 -0
  8. package/dist/httpAdapter/httpAdapter.logger.js +21 -0
  9. package/dist/httpAdapter/node/httpNode.adapter.d.ts +20 -1
  10. package/dist/httpAdapter/node/httpNode.adapter.js +80 -20
  11. package/dist/httpAdapter/node/httpNode.request.d.ts +12 -1
  12. package/dist/httpAdapter/node/httpNode.request.js +23 -16
  13. package/dist/httpAdapter/node/httpNode.server.d.ts +6 -0
  14. package/dist/httpAdapter/node/httpNode.server.js +6 -0
  15. package/dist/httpAdapter/node/httpNode.type.d.ts +2 -1
  16. package/dist/httpClient/httpClient.executor.js +14 -3
  17. package/dist/httpCookies/http.cookies.d.ts +29 -2
  18. package/dist/httpCookies/http.cookies.js +44 -24
  19. package/dist/httpCookies/httpCookies.defaults.d.ts +40 -0
  20. package/dist/httpCookies/httpCookies.defaults.js +42 -0
  21. package/dist/httpCookies/index.d.ts +1 -0
  22. package/dist/httpCookies/index.js +1 -0
  23. package/dist/httpMiddleware/builtin/conditional/httpMiddleware.conditional.d.ts +22 -1
  24. package/dist/httpMiddleware/builtin/conditional/httpMiddleware.conditional.js +19 -4
  25. package/dist/httpMiddleware/builtin/conditional/index.d.ts +1 -0
  26. package/dist/httpMiddleware/builtin/cors/httpMiddleware.cors.d.ts +8 -0
  27. package/dist/httpMiddleware/builtin/cors/httpMiddleware.cors.js +25 -22
  28. package/dist/httpMiddleware/builtin/helpers/httpMiddleware.accessor.js +2 -6
  29. package/dist/httpMiddleware/builtin/helpers/httpMiddleware.media.d.ts +33 -0
  30. package/dist/httpMiddleware/builtin/helpers/httpMiddleware.media.js +59 -0
  31. package/dist/httpMiddleware/builtin/helpers/index.d.ts +1 -0
  32. package/dist/httpMiddleware/builtin/helpers/index.js +1 -0
  33. package/dist/httpMiddleware/builtin/image/httpMiddleware.image.d.ts +13 -0
  34. package/dist/httpMiddleware/builtin/image/httpMiddleware.image.js +31 -53
  35. package/dist/httpMiddleware/builtin/index.d.ts +1 -0
  36. package/dist/httpMiddleware/builtin/index.js +1 -0
  37. package/dist/httpMiddleware/builtin/rateLimit/httpMiddleware.rateLimit.d.ts +47 -0
  38. package/dist/httpMiddleware/builtin/rateLimit/httpMiddleware.rateLimit.js +61 -0
  39. package/dist/httpMiddleware/builtin/rateLimit/index.d.ts +7 -0
  40. package/dist/httpMiddleware/builtin/rateLimit/index.js +7 -0
  41. package/dist/httpMiddleware/builtin/static/httpMiddleware.static.js +30 -4
  42. package/dist/httpMiddleware/builtin/video/httpMiddleware.video.d.ts +19 -1
  43. package/dist/httpMiddleware/builtin/video/httpMiddleware.video.js +38 -59
  44. package/dist/httpMiddleware/builtin/video/httpMiddleware.video.options.d.ts +12 -0
  45. package/dist/httpMiddleware/builtin/video/httpMiddleware.video.options.js +31 -0
  46. package/dist/httpMiddleware/httpMiddleware.error.d.ts +5 -31
  47. package/dist/httpMiddleware/httpMiddleware.error.js +5 -53
  48. package/dist/httpProxy/http.proxy.d.ts +7 -0
  49. package/dist/httpProxy/http.proxy.js +9 -0
  50. package/dist/httpProxy/httpProxy.pathGuard.d.ts +23 -0
  51. package/dist/httpProxy/httpProxy.pathGuard.js +43 -0
  52. package/dist/httpProxy/index.d.ts +1 -0
  53. package/dist/httpProxy/index.js +1 -0
  54. package/dist/httpRequest/httpRequest.context.d.ts +7 -0
  55. package/dist/httpRequest/httpRequest.context.js +15 -16
  56. package/dist/httpRequest/index.d.ts +1 -0
  57. package/dist/httpRequest/index.js +1 -0
  58. package/dist/httpRequest/target/httpRequest.target.d.ts +45 -0
  59. package/dist/httpRequest/target/httpRequest.target.js +93 -0
  60. package/dist/httpRequest/target/index.d.ts +9 -0
  61. package/dist/httpRequest/target/index.js +9 -0
  62. package/dist/httpResponse/httpResponse.context.d.ts +10 -0
  63. package/dist/httpResponse/httpResponse.context.js +13 -1
  64. package/dist/httpResponse/httpResponse.helper.d.ts +22 -0
  65. package/dist/httpResponse/httpResponse.helper.js +94 -24
  66. package/dist/httpRouter/core/registry/core/httpRegistry.helper.js +1 -1
  67. package/dist/httpRouter/core/util/httpRoute.util.d.ts +14 -0
  68. package/dist/httpRouter/core/util/httpRoute.util.js +18 -14
  69. package/dist/httpRouter/dispatch/httpRoute.dispatcher.js +12 -1
  70. package/dist/httpSecurity/httpSecurity.config.d.ts +6 -0
  71. package/dist/httpSecurity/httpSecurity.config.js +1 -0
  72. package/dist/httpSecurity/httpSecurity.guard.d.ts +7 -9
  73. package/dist/httpSecurity/httpSecurity.guard.js +7 -14
  74. package/dist/httpSecurity/httpSecurity.nodeGuard.d.ts +48 -0
  75. package/dist/httpSecurity/httpSecurity.nodeGuard.js +32 -0
  76. package/dist/httpSecurity/httpSecurity.validator.js +4 -2
  77. package/dist/httpSecurity/index.d.ts +2 -0
  78. package/dist/httpSecurity/index.js +1 -0
  79. package/dist/httpServer/core/httpServer.core.d.ts +11 -0
  80. package/dist/httpServer/core/httpServer.core.js +30 -4
  81. package/dist/httpTrustProxy/httpTrustProxy.compilation.d.ts +5 -2
  82. package/dist/httpTrustProxy/httpTrustProxy.compilation.js +19 -2
  83. package/dist/httpTrustProxy/httpTrustProxy.type.d.ts +3 -1
  84. package/dist/index.js +0 -1
  85. package/package.json +9 -5
package/README.md CHANGED
@@ -2,6 +2,12 @@
2
2
 
3
3
  HTTP primitives, request handling, routing, middleware, and server infrastructure for Zudojs applications.
4
4
 
5
+ <!-- zudo-docs:start -->
6
+
7
+ **Documentation:** [zudojs.oyinlola.site/docs/packages-http](https://zudojs.oyinlola.site/docs/packages-http) · **For AI agents:** [Markdown version](https://zudojs.oyinlola.site/docs/packages-http.md), [llms.txt](https://zudojs.oyinlola.site/llms.txt)
8
+
9
+ <!-- zudo-docs:end -->
10
+
5
11
  ## Installation
6
12
 
7
13
  ```bash
@@ -11,19 +17,71 @@ npm install @zudojs/http
11
17
  ## Quick Start
12
18
 
13
19
  ```typescript
14
- import { createHTTPServer } from "@zudojs/http";
20
+ import {
21
+ createHttpServer,
22
+ createNodeHttpAdapter,
23
+ createResponseContext,
24
+ } from "@zudojs/http";
15
25
 
16
- const server = createHTTPServer({
17
- handler: {
18
- async fetch(request) {
19
- return new Response("Hello from Zudojs");
20
- },
26
+ const server = createHttpServer({
27
+ adapter: createNodeHttpAdapter({ host: "127.0.0.1", port: 3000 }),
28
+ handler: async (request) => {
29
+ return createResponseContext().text(`Hello from Zudojs (${request.path})`);
21
30
  },
22
31
  });
23
32
 
24
33
  await server.start();
25
34
  ```
26
35
 
36
+ A handler receives an `HttpRequestContext` and may return an
37
+ `HttpResponseContext` or any JSON value. **Every value that is not an
38
+ `HttpResponseContext` is data**: a plain object such as `{ status: "ok" }` is
39
+ sent as `application/json`, whatever its keys. To choose the status, headers
40
+ or raw body, return `createResponseContext({ status, headers, body })`.
41
+ Throwing an `HttpError` created by `notFound()`, `unauthorized()` and friends
42
+ answers with that error's status. When errors are wrapped, the **outermost**
43
+ error that carries a status wins; only the middleware pipeline's own
44
+ wrappers are looked through, so `new HttpError(502, "Bad Gateway", { cause })`
45
+ answers 502 and never exposes the cause.
46
+
47
+ ## Secure defaults
48
+
49
+ - **Request guard.** The Node adapter runs `guardRequest` on every request
50
+ before the body is read and answers `400` when it refuses: Host,
51
+ `X-Request-Id` format, header count and size, URL and query length, and
52
+ `Transfer-Encoding`/`Content-Length` smuggling. Tune it with
53
+ `createNodeHttpAdapter({ security: { allowedHosts: ["api.example.com"] } })`
54
+ or turn it off with `security: false`. HTTP/1.0 requests may omit Host, and
55
+ oversized bodies still get `413` from `maxBodySize`.
56
+ - **Canonical request targets.** Request targets with `.`/`..` segments
57
+ (including `%2e%2e`), backslashes or a non-origin form are refused with
58
+ `400`. `request.path`, the router and `createPathMiddleware` all read the
59
+ path with one parser, and `//host/admin` is a path, never an authority.
60
+ - **Path-scoped middleware** matches the way the router does: case-insensitive
61
+ and ignoring repeated or trailing slashes (`{ caseSensitive: true }` to opt
62
+ out).
63
+ - **Query strings** are parsed once: a repeated name is an array in both
64
+ `request.query`/`getQuery()` and the router's `ctx.query`.
65
+ - **Cookies** default to `Path=/; HttpOnly; Secure; SameSite=Lax`; override
66
+ any attribute explicitly. Signed cookies are bound to their name: read them
67
+ with `parseSignedCookie(value, secret, name)`.
68
+ - **`trustProxy`** accepts a hop count (`trustProxy: 1` trusts one proxy).
69
+ - **CORS** origin matching is `@zudojs/security`'s `isOriginAllowed`, and a
70
+ wildcard origin with `credentials: true` throws when the middleware is
71
+ created. **Rate limiting**: `createRateLimitMiddleware({ max, windowMs })`
72
+ wraps `@zudojs/security`'s `createRateLimiter`. Requests with no usable
73
+ client address share one bucket (`UNKNOWN_CLIENT_RATE_LIMIT_IP`,
74
+ `0.0.0.0`): they are limited together, never unlimited and never a 500.
75
+ - Signed-cookie signatures are compared with `@zudojs/crypto`'s constant-time
76
+ `timingSafeEqualString`.
77
+ - Contexts built by the stock adapters log through a `@zudojs/logger` console
78
+ logger named `http`, which redacts secret metadata fields (`authorization`,
79
+ `password`, `apiKey`, …).
80
+ - `HttpRequestGuardError`, `HttpMiddlewareError` and
81
+ `HttpMiddlewarePipelineError` are the `@zudojs/errors` classes, re-exported.
82
+ - `HttpServer.stop()` gives in-flight requests the full
83
+ `gracefulShutdownTimeout`.
84
+
27
85
  ## Features
28
86
 
29
87
  - Runtime-independent HTTP server abstraction
@@ -64,7 +64,12 @@ export interface HttpAdapter {
64
64
  */
65
65
  setErrorHandler?(handler: HttpErrorHandler): void;
66
66
  start?(): void | Promise<void>;
67
- stop?(): void | Promise<void>;
67
+ /**
68
+ * Stops the adapter. `options.graceMs` bounds how long in-flight requests
69
+ * may run before their connections are closed; `HttpServer.stop()` passes
70
+ * its `gracefulShutdownTimeout` here.
71
+ */
72
+ stop?(options?: HttpAdapterStopOptions): void | Promise<void>;
68
73
  }
69
74
  import { HttpAdapterError } from "@zudojs/errors";
70
75
  export { HttpAdapterError };
@@ -96,7 +101,7 @@ export declare abstract class BaseHttpAdapter implements HttpAdapter {
96
101
  protected handleError(error: unknown, request: HttpRequestContext, input: unknown, response: HttpResponseContext): Promise<void>;
97
102
  protected write(input: unknown, context: HttpResponseContext): Promise<void>;
98
103
  start(): Promise<void>;
99
- stop(): Promise<void>;
104
+ stop(_options?: HttpAdapterStopOptions): Promise<void>;
100
105
  get isStarted(): boolean;
101
106
  }
102
107
  export interface GenericAdapterOptions extends HttpAdapterOptions {
@@ -128,9 +133,35 @@ export declare class HttpAdapterRegistry {
128
133
  clear(): void;
129
134
  }
130
135
  export declare function startAdapter(adapter: HttpAdapter): Promise<void>;
131
- export declare function stopAdapter(adapter: HttpAdapter): Promise<void>;
136
+ /**
137
+ * Options passed to {@link HttpAdapter.stop}.
138
+ */
139
+ export interface HttpAdapterStopOptions {
140
+ /** Milliseconds in-flight requests may run before connections are closed. */
141
+ readonly graceMs?: number;
142
+ }
143
+ export declare function stopAdapter(adapter: HttpAdapter, options?: HttpAdapterStopOptions): Promise<void>;
132
144
  export declare function isHttpAdapter(value: unknown): value is HttpAdapter;
145
+ /**
146
+ * Turns a handler's return value into a response.
147
+ *
148
+ * Only an `HttpResponseContext` is treated as a response; `undefined`/`null`
149
+ * is an empty 200. **Every other value, including any plain object, is
150
+ * data** and is sent as `application/json`. To answer with a status, headers
151
+ * or a raw body, return `createResponseContext({ status, headers, body })`.
152
+ *
153
+ * A plain object used to count as a response init whenever it had any of
154
+ * eight common keys, so `{ status: "ok" }` became a 500 and a row with a
155
+ * `body` or `metadata` column was silently emptied or truncated.
156
+ */
133
157
  export declare function normalizeHandlerResult(result: HttpHandlerResult): HttpResponseContext;
158
+ /**
159
+ * Whether a value has the shape of a response init.
160
+ *
161
+ * @deprecated No longer used to interpret handler results: a plain object
162
+ * returned from a handler is always sent as JSON (see
163
+ * {@link normalizeHandlerResult}). Kept for API compatibility.
164
+ */
134
165
  export declare function isResponseContextInit(value: unknown): value is ResponseContextInit;
135
166
  export declare function mergeResponseContext(target: HttpResponseContext, source: HttpResponseContext): HttpResponseContext;
136
167
  //# sourceMappingURL=http.adapter.d.ts.map
@@ -11,6 +11,7 @@
11
11
  import { HttpRequestContext, createRequestContext, } from "../httpRequest/httpRequest.context.js";
12
12
  import { HttpResponseContext, createResponseContext, } from "../httpResponse/httpResponse.context.js";
13
13
  import { writeResponse } from "../httpResponse/httpResponse.writer.js";
14
+ import { resolveErrorResponse } from "./httpAdapter.errorResponse.js";
14
15
  /* -------------------------------------------------------------------------- */
15
16
  /* Adapter Error */
16
17
  /* -------------------------------------------------------------------------- */
@@ -85,10 +86,11 @@ export class BaseHttpAdapter {
85
86
  mergeResponseContext(response, context);
86
87
  }
87
88
  else {
88
- response.internalServerError();
89
- response.json({
90
- error: "Internal Server Error",
91
- });
89
+ const resolved = resolveErrorResponse(error);
90
+ for (const [name, value] of Object.entries(resolved.headers)) {
91
+ response.setHeader(name, value);
92
+ }
93
+ response.setStatus(resolved.status).json(resolved.body);
92
94
  }
93
95
  await this.write(input, response);
94
96
  }
@@ -108,7 +110,7 @@ export class BaseHttpAdapter {
108
110
  }
109
111
  this.started = true;
110
112
  }
111
- async stop() {
113
+ async stop(_options) {
112
114
  if (!this.started) {
113
115
  return;
114
116
  }
@@ -220,9 +222,9 @@ export async function startAdapter(adapter) {
220
222
  await adapter.start();
221
223
  }
222
224
  }
223
- export async function stopAdapter(adapter) {
225
+ export async function stopAdapter(adapter, options) {
224
226
  if (adapter.stop) {
225
- await adapter.stop();
227
+ await adapter.stop(options);
226
228
  }
227
229
  }
228
230
  /* -------------------------------------------------------------------------- */
@@ -242,6 +244,18 @@ export function isHttpAdapter(value) {
242
244
  /* -------------------------------------------------------------------------- */
243
245
  /* Result Normalization */
244
246
  /* -------------------------------------------------------------------------- */
247
+ /**
248
+ * Turns a handler's return value into a response.
249
+ *
250
+ * Only an `HttpResponseContext` is treated as a response; `undefined`/`null`
251
+ * is an empty 200. **Every other value, including any plain object, is
252
+ * data** and is sent as `application/json`. To answer with a status, headers
253
+ * or a raw body, return `createResponseContext({ status, headers, body })`.
254
+ *
255
+ * A plain object used to count as a response init whenever it had any of
256
+ * eight common keys, so `{ status: "ok" }` became a 500 and a row with a
257
+ * `body` or `metadata` column was silently emptied or truncated.
258
+ */
245
259
  export function normalizeHandlerResult(result) {
246
260
  if (result instanceof HttpResponseContext) {
247
261
  return result;
@@ -249,11 +263,15 @@ export function normalizeHandlerResult(result) {
249
263
  if (result === undefined || result === null) {
250
264
  return createResponseContext();
251
265
  }
252
- if (isResponseContextInit(result)) {
253
- return createResponseContext(result);
254
- }
255
266
  return createResponseContext().json(result);
256
267
  }
268
+ /**
269
+ * Whether a value has the shape of a response init.
270
+ *
271
+ * @deprecated No longer used to interpret handler results: a plain object
272
+ * returned from a handler is always sent as JSON (see
273
+ * {@link normalizeHandlerResult}). Kept for API compatibility.
274
+ */
257
275
  export function isResponseContextInit(value) {
258
276
  if (value === null || typeof value !== "object") {
259
277
  return false;
@@ -1,6 +1,7 @@
1
1
  import { createHTTPContext } from "../httpContext/http.context.js";
2
2
  import { createHTTPRequest } from "../httpRequest/http.request.js";
3
3
  import { createHTTPResponse } from "../httpResponse/http.response.js";
4
+ import { createDefaultContextLogger } from "./httpAdapter.logger.js";
4
5
  /* -------------------------------------------------------------------------- */
5
6
  /* Node Adapter */
6
7
  /* -------------------------------------------------------------------------- */
@@ -18,7 +19,7 @@ export class NodeHTTPAdapter {
18
19
  response,
19
20
  state: options.state ?? {},
20
21
  signal: options.signal,
21
- logger: createFallbackLogger(),
22
+ logger: createDefaultContextLogger(),
22
23
  });
23
24
  }
24
25
  }
@@ -45,7 +46,7 @@ export class NodeContextAdapter {
45
46
  response,
46
47
  state: options.state ?? {},
47
48
  signal: options.signal,
48
- logger: createFallbackLogger(),
49
+ logger: createDefaultContextLogger(),
49
50
  });
50
51
  }
51
52
  }
@@ -87,7 +88,7 @@ export function adaptNodeContext(request, response, options = {}) {
87
88
  response: adaptNodeResponse(response),
88
89
  state: options.state ?? {},
89
90
  signal: options.signal,
90
- logger: createFallbackLogger(),
91
+ logger: createDefaultContextLogger(),
91
92
  });
92
93
  }
93
94
  /* -------------------------------------------------------------------------- */
@@ -103,35 +104,4 @@ export function isHTTPAdapter(value) {
103
104
  typeof candidate.createResponse === "function" &&
104
105
  typeof candidate.createContext === "function");
105
106
  }
106
- /* -------------------------------------------------------------------------- */
107
- /* Fallback Logger */
108
- /* -------------------------------------------------------------------------- */
109
- function createFallbackLogger() {
110
- return {
111
- info(message, metadata) {
112
- if (metadata !== undefined) {
113
- console.info(message, metadata);
114
- }
115
- else {
116
- console.info(message);
117
- }
118
- },
119
- warn(message, metadata) {
120
- if (metadata !== undefined) {
121
- console.warn(message, metadata);
122
- }
123
- else {
124
- console.warn(message);
125
- }
126
- },
127
- error(message, metadata) {
128
- if (metadata !== undefined) {
129
- console.error(message, metadata);
130
- }
131
- else {
132
- console.error(message);
133
- }
134
- },
135
- };
136
- }
137
107
  //# sourceMappingURL=http.adapters.js.map
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Default error-to-response mapping shared by the adapters.
3
+ *
4
+ * An error thrown from a handler used to be answered with a generic 500 no
5
+ * matter what it was, so `throw notFound()` — the documented way to fail a
6
+ * request — reached the client as `500 Internal Server Error` with the
7
+ * error's status, message and headers (`WWW-Authenticate`, `Allow`,
8
+ * `Retry-After`) all discarded. Middleware wrappers made it worse: the
9
+ * pipeline wraps every failure in `HttpMiddlewareError` /
10
+ * `HttpMiddlewarePipelineError`, both of which report status 500, so the
11
+ * original error's status was hidden even from a custom error handler that
12
+ * only looked one level deep.
13
+ *
14
+ * This module is deliberately internal: it is not part of the public API.
15
+ *
16
+ * @module httpAdapter/errorResponse
17
+ */
18
+ export interface ResolvedErrorResponse {
19
+ readonly status: number;
20
+ readonly body: Readonly<Record<string, unknown>>;
21
+ readonly headers: Readonly<Record<string, string>>;
22
+ }
23
+ /**
24
+ * Builds the default response for an unhandled error.
25
+ *
26
+ * - The outermost error with a 4xx/5xx `statusCode` (looking through the
27
+ * pipeline's own wrappers only) is answered with that status.
28
+ * - Its `message` and `code` are included only when the error opts in with
29
+ * `expose: true` (the `@zudojs/errors` default for 4xx); otherwise the
30
+ * body carries the status text alone, so a 5xx never leaks internals.
31
+ * - Its `headers` are applied when they are valid header values.
32
+ * - Anything else is a generic `500 Internal Server Error`.
33
+ */
34
+ export declare function resolveErrorResponse(error: unknown): ResolvedErrorResponse;
35
+ //# sourceMappingURL=httpAdapter.errorResponse.d.ts.map
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Default error-to-response mapping shared by the adapters.
3
+ *
4
+ * An error thrown from a handler used to be answered with a generic 500 no
5
+ * matter what it was, so `throw notFound()` — the documented way to fail a
6
+ * request — reached the client as `500 Internal Server Error` with the
7
+ * error's status, message and headers (`WWW-Authenticate`, `Allow`,
8
+ * `Retry-After`) all discarded. Middleware wrappers made it worse: the
9
+ * pipeline wraps every failure in `HttpMiddlewareError` /
10
+ * `HttpMiddlewarePipelineError`, both of which report status 500, so the
11
+ * original error's status was hidden even from a custom error handler that
12
+ * only looked one level deep.
13
+ *
14
+ * This module is deliberately internal: it is not part of the public API.
15
+ *
16
+ * @module httpAdapter/errorResponse
17
+ */
18
+ import { getStatusText } from "../httpResponse/core/httpResponse.statusText.js";
19
+ import { isValidHeaderFieldValue } from "../httpHeaders/security/index.js";
20
+ import { HttpMiddlewareError, HttpMiddlewarePipelineError, } from "../httpMiddleware/httpMiddleware.error.js";
21
+ /* -------------------------------------------------------------------------- */
22
+ /* Constants */
23
+ /* -------------------------------------------------------------------------- */
24
+ /**
25
+ * How many levels of `cause` / `errors` nesting are inspected. Deep enough
26
+ * for the pipeline's two wrappers plus a few application layers; bounded so a
27
+ * cyclic `cause` chain cannot loop.
28
+ */
29
+ const MAX_UNWRAP_DEPTH = 8;
30
+ /* -------------------------------------------------------------------------- */
31
+ /* Resolution */
32
+ /* -------------------------------------------------------------------------- */
33
+ /**
34
+ * Whether `error` is one of the pipeline's own wrappers. These are added by
35
+ * the framework on the way out and always report 500, so they are looked
36
+ * through; nothing else is.
37
+ */
38
+ function isFrameworkWrapper(error) {
39
+ return (error instanceof HttpMiddlewareError ||
40
+ error instanceof HttpMiddlewarePipelineError);
41
+ }
42
+ /**
43
+ * Locates the error whose status answers the request.
44
+ *
45
+ * The **outermost** error that carries a status wins. Only the framework's
46
+ * own wrappers (`HttpMiddlewareError`, `HttpMiddlewarePipelineError`) are
47
+ * unwrapped. An application that throws
48
+ * `new HttpError(502, "Bad Gateway", { cause: upstream401 })` is mapping an
49
+ * upstream failure on purpose; taking the innermost status sent the client
50
+ * the upstream's 401, its message and its `WWW-Authenticate` header.
51
+ * An error that is neither a wrapper nor carries a status ends the search
52
+ * (generic 500), so a `cause` the application attached is never exposed.
53
+ */
54
+ function findStatusError(error, depth, seen) {
55
+ if (error === null || typeof error !== "object" || depth > MAX_UNWRAP_DEPTH) {
56
+ return undefined;
57
+ }
58
+ if (seen.has(error)) {
59
+ return undefined;
60
+ }
61
+ seen.add(error);
62
+ const candidate = error;
63
+ if (!isFrameworkWrapper(error)) {
64
+ return isHttpStatus(candidate.statusCode)
65
+ ? candidate
66
+ : undefined;
67
+ }
68
+ const nested = [];
69
+ if (Array.isArray(candidate.errors)) {
70
+ nested.push(...candidate.errors);
71
+ }
72
+ if (candidate.cause !== undefined) {
73
+ nested.push(candidate.cause);
74
+ }
75
+ for (const inner of nested) {
76
+ const found = findStatusError(inner, depth + 1, seen);
77
+ if (found) {
78
+ return found;
79
+ }
80
+ }
81
+ return undefined;
82
+ }
83
+ function isHttpStatus(value) {
84
+ return (typeof value === "number" &&
85
+ Number.isInteger(value) &&
86
+ value >= 400 &&
87
+ value <= 599);
88
+ }
89
+ /**
90
+ * Builds the default response for an unhandled error.
91
+ *
92
+ * - The outermost error with a 4xx/5xx `statusCode` (looking through the
93
+ * pipeline's own wrappers only) is answered with that status.
94
+ * - Its `message` and `code` are included only when the error opts in with
95
+ * `expose: true` (the `@zudojs/errors` default for 4xx); otherwise the
96
+ * body carries the status text alone, so a 5xx never leaks internals.
97
+ * - Its `headers` are applied when they are valid header values.
98
+ * - Anything else is a generic `500 Internal Server Error`.
99
+ */
100
+ export function resolveErrorResponse(error) {
101
+ const statusError = findStatusError(error, 0, new Set());
102
+ if (!statusError) {
103
+ return {
104
+ status: 500,
105
+ body: { error: "Internal Server Error" },
106
+ headers: {},
107
+ };
108
+ }
109
+ const status = statusError.statusCode;
110
+ const expose = statusError.expose === true;
111
+ const message = expose && typeof statusError.message === "string" && statusError.message
112
+ ? statusError.message
113
+ : getStatusText(status);
114
+ const body = { error: message };
115
+ if (expose && typeof statusError.code === "string" && statusError.code) {
116
+ body.code = statusError.code;
117
+ }
118
+ return {
119
+ status,
120
+ body,
121
+ headers: collectHeaders(statusError.headers),
122
+ };
123
+ }
124
+ function collectHeaders(value) {
125
+ if (value === null || typeof value !== "object") {
126
+ return {};
127
+ }
128
+ const headers = {};
129
+ for (const [name, entry] of Object.entries(value)) {
130
+ if (typeof entry !== "string" || !isValidHeaderFieldValue(entry)) {
131
+ continue;
132
+ }
133
+ headers[name] = entry;
134
+ }
135
+ return headers;
136
+ }
137
+ //# sourceMappingURL=httpAdapter.errorResponse.js.map
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Default logger for contexts built by the stock adapters.
3
+ *
4
+ * @module httpAdapter/httpAdapter.logger
5
+ */
6
+ import { type Logger } from "@zudojs/logger";
7
+ /**
8
+ * Creates the logger a stock adapter gives each `HTTPContext` when the
9
+ * caller supplies none: a `@zudojs/logger` console logger named `http`.
10
+ *
11
+ * It goes through the logger's secret-field redaction, so metadata such as
12
+ * `authorization`, `password` or `apiKey` passed to `ctx.log()` is printed
13
+ * as `[REDACTED]`. The earlier fallback called `console.*` with the raw
14
+ * metadata object. One logger per context (construction costs a few
15
+ * microseconds), so `setLevel()` / `disable()` / `close()` on one context's
16
+ * logger cannot silence another's.
17
+ */
18
+ export declare function createDefaultContextLogger(): Logger;
19
+ //# sourceMappingURL=httpAdapter.logger.d.ts.map
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Default logger for contexts built by the stock adapters.
3
+ *
4
+ * @module httpAdapter/httpAdapter.logger
5
+ */
6
+ import { createDefaultLogger } from "@zudojs/logger";
7
+ /**
8
+ * Creates the logger a stock adapter gives each `HTTPContext` when the
9
+ * caller supplies none: a `@zudojs/logger` console logger named `http`.
10
+ *
11
+ * It goes through the logger's secret-field redaction, so metadata such as
12
+ * `authorization`, `password` or `apiKey` passed to `ctx.log()` is printed
13
+ * as `[REDACTED]`. The earlier fallback called `console.*` with the raw
14
+ * metadata object. One logger per context (construction costs a few
15
+ * microseconds), so `setLevel()` / `disable()` / `close()` on one context's
16
+ * logger cannot silence another's.
17
+ */
18
+ export function createDefaultContextLogger() {
19
+ return createDefaultLogger("http");
20
+ }
21
+ //# sourceMappingURL=httpAdapter.logger.js.map
@@ -10,6 +10,7 @@ import { Server } from "node:http";
10
10
  import { HttpRequestContext } from "../../httpRequest/httpRequest.context.js";
11
11
  import { HttpResponseContext } from "../../httpResponse/httpResponse.context.js";
12
12
  import { BaseHttpAdapter } from "../http.adapter.js";
13
+ import type { HttpAdapterStopOptions } from "../http.adapter.js";
13
14
  import type { HttpResponseWriter } from "../../httpResponse/httpResponse.writer.js";
14
15
  import type { NodeAdapterOptions, NodeServerAddress } from "./httpNode.type.js";
15
16
  export declare class NodeHttpAdapter extends BaseHttpAdapter {
@@ -25,8 +26,16 @@ export declare class NodeHttpAdapter extends BaseHttpAdapter {
25
26
  private readonly connectionsCheckingInterval;
26
27
  private readonly shutdownGraceMs;
27
28
  private readonly events;
29
+ private readonly requestGuard;
28
30
  private server;
29
31
  private ownsServer;
32
+ /**
33
+ * The `clientError` listener installed by `start()`, kept so `stop()` can
34
+ * remove it. On an externally supplied server the instance survives a
35
+ * stop/start cycle, and re-adding the listener on every start leaked one
36
+ * per restart.
37
+ */
38
+ private clientErrorListener;
30
39
  constructor(options?: NodeAdapterOptions);
31
40
  get httpServer(): Server | undefined;
32
41
  get address(): NodeServerAddress | undefined;
@@ -43,8 +52,13 @@ export declare class NodeHttpAdapter extends BaseHttpAdapter {
43
52
  */
44
53
  private attachNodeBody;
45
54
  private executeNodeHandler;
55
+ /**
56
+ * Plain objects are data and are sent as JSON; see
57
+ * `normalizeHandlerResult`.
58
+ */
46
59
  private normalizeResult;
47
60
  private handleNodeError;
61
+ private writeBadRequest;
48
62
  private writeNodeResponse;
49
63
  /**
50
64
  * Runs `handle` for a Node request/response pair without ever letting the
@@ -57,7 +71,12 @@ export declare class NodeHttpAdapter extends BaseHttpAdapter {
57
71
  private dispatchNodeRequest;
58
72
  private emitAdapterError;
59
73
  start(): Promise<void>;
60
- stop(): Promise<void>;
74
+ /**
75
+ * Closes the server. The grace period is `options.graceMs` (the server's
76
+ * `gracefulShutdownTimeout`), capped by an explicit `shutdownGraceMs`;
77
+ * with neither it is 10 s.
78
+ */
79
+ stop(options?: HttpAdapterStopOptions): Promise<void>;
61
80
  }
62
81
  export declare function createNodeHttpAdapter(options?: NodeAdapterOptions): NodeHttpAdapter;
63
82
  //# sourceMappingURL=httpNode.adapter.d.ts.map