hono-problem-details 0.11.0 → 0.12.1

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.
package/README.md CHANGED
@@ -210,6 +210,18 @@ problemDetailsHandler({
210
210
  Keep `includeStack` off in production — stack traces should not leave the server even via
211
211
  opt-in extension fields.
212
212
 
213
+ Unlike Hono's default error handler, `problemDetailsHandler()` does not log anything. Pass
214
+ `onUnhandledError` to log (or report) errors that fall through to the generic 500. It is not
215
+ called for `ProblemDetailsError`, `HTTPException`, or errors matched by `mapError`:
216
+
217
+ ```ts
218
+ app.onError(
219
+ problemDetailsHandler({
220
+ onUnhandledError: (err) => console.error(err),
221
+ }),
222
+ );
223
+ ```
224
+
213
225
  ## Extension Members
214
226
 
215
227
  Extension members are flattened to top level per RFC 9457:
@@ -354,6 +366,17 @@ app.post("/users", zValidator("json", schema, zodProblemHook()), (c) => {
354
366
  // }
355
367
  ```
356
368
 
369
+ By default the hooks build the response themselves, so `problemDetailsHandler` options (`typePrefix`, `defaultType`, `localize`, `autoInstance`, `otelApi`) do not apply to validation errors. Pass `delegateToHandler: true` to any of the validator hooks (`zodProblemHook`, `valibotProblemHook`, `standardSchemaProblemHook`) to throw a `ProblemDetailsError` instead and let the handler produce the response. The handler options only apply with `app.onError(problemDetailsHandler(...))`; without it, Hono's default error handler falls back to `ProblemDetailsError.getResponse()` and returns the plain 422 body:
370
+
371
+ ```ts
372
+ app.onError(problemDetailsHandler({ typePrefix: "https://example.com/problems", autoInstance: true }));
373
+
374
+ app.post("/users", zValidator("json", schema, zodProblemHook({ delegateToHandler: true })), (c) => {
375
+ // ...
376
+ });
377
+ // type: "https://example.com/problems/unprocessable-content", instance: "/users"
378
+ ```
379
+
357
380
  ## Valibot Validator Integration
358
381
 
359
382
  ```ts
@@ -516,14 +539,19 @@ problemDetailsHandler({
516
539
 
517
540
  The callback receives the fully-built `ProblemDetails` object and the Hono `Context`, allowing access to headers like `Accept-Language`. Return a new `ProblemDetails` with translated fields.
518
541
 
542
+ > **Note on extensions**: The patch is merged shallowly, so returning `extensions` replaces
543
+ > all extension members (`code`, `traceId`, validation `errors`, ...). Spread the original
544
+ > to keep them: `return { extensions: { ...pd.extensions, hint: translate(lang, "hint") } }`.
545
+
519
546
  > **Note on caching**: If your responses vary by `Accept-Language`, add `Vary: Accept-Language`
520
547
  > from your own middleware so CDNs and browser caches don't serve the wrong translation.
521
548
  > This middleware intentionally does not set `Vary` — error handlers shouldn't mutate
522
549
  > request-scope headers that also apply to successful responses.
523
550
 
524
551
  > **Note on failures**: If your `localize` callback throws, the handler falls back to the
525
- > un-localized `ProblemDetails` and continues. Throwing from inside `app.onError` would cause
526
- > the error handler to re-enter itself, so the swallow is deliberate. Catch errors inside your
552
+ > un-localized `ProblemDetails` and continues. Hono hands an error thrown from inside
553
+ > `app.onError` back to `onError` (several times when middleware is present), and if it keeps
554
+ > throwing, the request rejects, so the swallow is deliberate. Catch errors inside your
527
555
  > callback if you need to observe them.
528
556
 
529
557
  ## OpenTelemetry Integration
@@ -538,7 +566,7 @@ problemDetailsHandler({
538
566
  });
539
567
  ```
540
568
 
541
- When enabled, the handler adds a `traceId` extension member to every response it produces (thrown `ProblemDetailsError`s, `HTTPException`s, and unhandled errors) when a trace is active. Validation-hook responses (`zodProblemHook`, `valibotProblemHook`, `standardSchemaProblemHook`) are returned directly by the validator and never pass through the handler, so they do not carry `traceId`.
569
+ When enabled, the handler adds a `traceId` extension member to every response it produces (thrown `ProblemDetailsError`s, `HTTPException`s, and unhandled errors) when a trace is active. Validation-hook responses (`zodProblemHook`, `valibotProblemHook`, `standardSchemaProblemHook`) are returned directly by the validator and never pass through the handler, so they do not carry `traceId` unless you set `delegateToHandler: true` (see [Zod Validator Integration](#zod-validator-integration)).
542
570
  This allows clients to correlate errors with server-side traces for easier debugging.
543
571
 
544
572
  ## Handler Options
@@ -564,7 +592,13 @@ problemDetailsHandler({
564
592
  return { title: `[${lang}] ${pd.title}` };
565
593
  },
566
594
 
567
- // Custom error mapping
595
+ // Called for errors that become the generic 500 (not ProblemDetailsError, HTTPException,
596
+ // or mapError results). The handler doesn't log by default; use this to restore logging.
597
+ // A throwing callback is swallowed; the return value is not awaited.
598
+ onUnhandledError: (err, c) => console.error(err),
599
+
600
+ // Custom error mapping. A throwing callback is silently swallowed
601
+ // and the error is handled as if mapError returned undefined.
568
602
  mapError: (error) => {
569
603
  if (error instanceof MyCustomError) {
570
604
  return {
@@ -0,0 +1,34 @@
1
+ import {
2
+ buildProblemResponse,
3
+ normalizeProblemDetails
4
+ } from "./chunk-URAOTABQ.js";
5
+
6
+ // src/error.ts
7
+ var ProblemDetailsError = class extends Error {
8
+ /** The normalized RFC 9457 Problem Details object. */
9
+ problemDetails;
10
+ /**
11
+ * Whether the input carried an explicit `type`. Lets the handler apply
12
+ * `typePrefix`/`defaultType` only when the thrower left `type` unset.
13
+ */
14
+ hasExplicitType;
15
+ /**
16
+ * @param input - Missing `type` defaults to `"about:blank"`;
17
+ * missing `title` is derived from the HTTP status code.
18
+ */
19
+ constructor(input) {
20
+ const pd = normalizeProblemDetails(input);
21
+ super(pd.detail ?? pd.title);
22
+ this.name = "ProblemDetailsError";
23
+ this.problemDetails = pd;
24
+ this.hasExplicitType = input.type !== void 0;
25
+ }
26
+ /** Build a standalone `application/problem+json` Response without the handler middleware. */
27
+ getResponse() {
28
+ return buildProblemResponse(this.problemDetails);
29
+ }
30
+ };
31
+
32
+ export {
33
+ ProblemDetailsError
34
+ };
@@ -1,3 +1,6 @@
1
+ import {
2
+ ProblemDetailsError
3
+ } from "./chunk-LIQQKPXQ.js";
1
4
  import {
2
5
  PROBLEM_JSON_CONTENT_TYPE
3
6
  } from "./chunk-URAOTABQ.js";
@@ -15,12 +18,23 @@ function sanitizeError(error) {
15
18
  };
16
19
  }
17
20
  function buildValidationResponse(errors, options) {
21
+ const title = options?.title ?? "Validation Error";
22
+ const detail = options?.detail ?? "Request validation failed";
23
+ const sanitizedErrors = errors.map(sanitizeError);
24
+ if (options?.delegateToHandler) {
25
+ throw new ProblemDetailsError({
26
+ status: 422,
27
+ title,
28
+ detail,
29
+ extensions: { errors: sanitizedErrors }
30
+ });
31
+ }
18
32
  const body = {
19
33
  type: "about:blank",
20
34
  status: 422,
21
- title: options?.title ?? "Validation Error",
22
- detail: options?.detail ?? "Request validation failed",
23
- errors: errors.map(sanitizeError)
35
+ title,
36
+ detail,
37
+ errors: sanitizedErrors
24
38
  };
25
39
  return new Response(JSON.stringify(body), {
26
40
  status: 422,
package/dist/index.cjs CHANGED
@@ -182,6 +182,13 @@ function getOtelTraceId(api) {
182
182
  }
183
183
 
184
184
  // src/handler.ts
185
+ var REPRESENTATION_HEADERS = /* @__PURE__ */ new Set([
186
+ "transfer-encoding",
187
+ "etag",
188
+ "last-modified",
189
+ "digest",
190
+ "accept-ranges"
191
+ ]);
185
192
  function buildType(status, options) {
186
193
  if (options.typePrefix) {
187
194
  const slug = statusToSlug(status);
@@ -189,6 +196,16 @@ function buildType(status, options) {
189
196
  }
190
197
  return options.defaultType ?? "about:blank";
191
198
  }
199
+ function copyResHeaders(error, response) {
200
+ if (error instanceof import_http_exception.HTTPException) {
201
+ error.res?.headers.forEach((value, name) => {
202
+ if (!name.startsWith("content-") && !REPRESENTATION_HEADERS.has(name)) {
203
+ response.headers.append(name, value);
204
+ }
205
+ });
206
+ }
207
+ return response;
208
+ }
192
209
  function toResponse(input, c, options) {
193
210
  let pd = normalizeProblemDetails({
194
211
  ...input,
@@ -216,28 +233,40 @@ function toResponse(input, c, options) {
216
233
  return buildProblemResponse(pd);
217
234
  }
218
235
  function problemDetailsHandler(options = {}) {
219
- return (error, c) => {
236
+ const handle = (error, c) => {
220
237
  if (error instanceof ProblemDetailsError) {
221
238
  const pd = error.problemDetails;
222
239
  return toResponse(error.hasExplicitType ? pd : { ...pd, type: void 0 }, c, options);
223
240
  }
224
241
  if (options.mapError) {
225
- const mapped = options.mapError(error);
226
- if (mapped) {
227
- return toResponse(mapped, c, options);
242
+ try {
243
+ const mapped = options.mapError(error);
244
+ if (mapped) {
245
+ return copyResHeaders(error, toResponse(mapped, c, options));
246
+ }
247
+ } catch {
228
248
  }
229
249
  }
230
250
  if (error instanceof import_http_exception.HTTPException) {
231
- return toResponse(
232
- {
233
- status: error.status,
234
- title: statusToPhrase(error.status),
235
- detail: error.message
236
- },
237
- c,
238
- options
251
+ return copyResHeaders(
252
+ error,
253
+ toResponse(
254
+ {
255
+ status: error.status,
256
+ title: statusToPhrase(error.status),
257
+ detail: error.message || void 0
258
+ },
259
+ c,
260
+ options
261
+ )
239
262
  );
240
263
  }
264
+ if (options.onUnhandledError) {
265
+ try {
266
+ options.onUnhandledError(error, c);
267
+ } catch {
268
+ }
269
+ }
241
270
  return toResponse(
242
271
  {
243
272
  status: 500,
@@ -249,6 +278,12 @@ function problemDetailsHandler(options = {}) {
249
278
  options
250
279
  );
251
280
  };
281
+ const dispatch = (first, second) => {
282
+ if (typeof second !== "function") return handle(first, second);
283
+ const c = first;
284
+ return c.error ? handle(c.error, c) : second();
285
+ };
286
+ return dispatch;
252
287
  }
253
288
 
254
289
  // src/registry.ts
package/dist/index.d.cts CHANGED
@@ -66,14 +66,27 @@ interface ProblemDetailsHandlerOptions {
66
66
  * ```
67
67
  */
68
68
  otelApi?: OtelApiLike;
69
- /** Custom error to ProblemDetails mapping */
69
+ /**
70
+ * Custom error to ProblemDetails mapping. A throwing callback is swallowed
71
+ * (ADR-0005) and the error is handled as if mapError returned undefined.
72
+ */
70
73
  mapError?: (error: Error) => ProblemDetailsInput | undefined;
71
74
  /**
72
75
  * Localize title/detail before sending the response.
73
76
  * Returned fields are merged onto the original ProblemDetails, so callers may
74
77
  * return a partial patch (e.g. `{ title: "..." }`) or omit the return entirely.
78
+ * The merge is shallow: a returned `extensions` replaces all extension members,
79
+ * so spread `pd.extensions` to keep `code`, `traceId`, or validation `errors`.
80
+ * A throwing callback is swallowed and the un-localized response is sent (ADR-0003).
75
81
  */
76
82
  localize?: (pd: ProblemDetails, c: Context) => Partial<ProblemDetails> | undefined;
83
+ /**
84
+ * Called for errors that fall through to the generic 500 response, before it is built.
85
+ * Not called for `ProblemDetailsError`, `HTTPException`, or errors matched by `mapError`.
86
+ * A throwing callback is swallowed. The return value is not awaited: do async work
87
+ * fire-and-forget and catch its rejections yourself.
88
+ */
89
+ onUnhandledError?: (error: Error, c: Context) => void;
77
90
  }
78
91
  interface OtelApiLike {
79
92
  trace: {
package/dist/index.d.ts CHANGED
@@ -66,14 +66,27 @@ interface ProblemDetailsHandlerOptions {
66
66
  * ```
67
67
  */
68
68
  otelApi?: OtelApiLike;
69
- /** Custom error to ProblemDetails mapping */
69
+ /**
70
+ * Custom error to ProblemDetails mapping. A throwing callback is swallowed
71
+ * (ADR-0005) and the error is handled as if mapError returned undefined.
72
+ */
70
73
  mapError?: (error: Error) => ProblemDetailsInput | undefined;
71
74
  /**
72
75
  * Localize title/detail before sending the response.
73
76
  * Returned fields are merged onto the original ProblemDetails, so callers may
74
77
  * return a partial patch (e.g. `{ title: "..." }`) or omit the return entirely.
78
+ * The merge is shallow: a returned `extensions` replaces all extension members,
79
+ * so spread `pd.extensions` to keep `code`, `traceId`, or validation `errors`.
80
+ * A throwing callback is swallowed and the un-localized response is sent (ADR-0003).
75
81
  */
76
82
  localize?: (pd: ProblemDetails, c: Context) => Partial<ProblemDetails> | undefined;
83
+ /**
84
+ * Called for errors that fall through to the generic 500 response, before it is built.
85
+ * Not called for `ProblemDetailsError`, `HTTPException`, or errors matched by `mapError`.
86
+ * A throwing callback is swallowed. The return value is not awaited: do async work
87
+ * fire-and-forget and catch its rejections yourself.
88
+ */
89
+ onUnhandledError?: (error: Error, c: Context) => void;
77
90
  }
78
91
  interface OtelApiLike {
79
92
  trace: {
package/dist/index.js CHANGED
@@ -1,3 +1,6 @@
1
+ import {
2
+ ProblemDetailsError
3
+ } from "./chunk-LIQQKPXQ.js";
1
4
  import {
2
5
  PROBLEM_JSON_CONTENT_TYPE,
3
6
  buildProblemResponse,
@@ -8,32 +11,6 @@ import {
8
11
  statusToSlug
9
12
  } from "./chunk-P4D7EVU3.js";
10
13
 
11
- // src/error.ts
12
- var ProblemDetailsError = class extends Error {
13
- /** The normalized RFC 9457 Problem Details object. */
14
- problemDetails;
15
- /**
16
- * Whether the input carried an explicit `type`. Lets the handler apply
17
- * `typePrefix`/`defaultType` only when the thrower left `type` unset.
18
- */
19
- hasExplicitType;
20
- /**
21
- * @param input - Missing `type` defaults to `"about:blank"`;
22
- * missing `title` is derived from the HTTP status code.
23
- */
24
- constructor(input) {
25
- const pd = normalizeProblemDetails(input);
26
- super(pd.detail ?? pd.title);
27
- this.name = "ProblemDetailsError";
28
- this.problemDetails = pd;
29
- this.hasExplicitType = input.type !== void 0;
30
- }
31
- /** Build a standalone `application/problem+json` Response without the handler middleware. */
32
- getResponse() {
33
- return buildProblemResponse(this.problemDetails);
34
- }
35
- };
36
-
37
14
  // src/factory.ts
38
15
  function problemDetails(input) {
39
16
  return new ProblemDetailsError(input);
@@ -54,6 +31,13 @@ function getOtelTraceId(api) {
54
31
  }
55
32
 
56
33
  // src/handler.ts
34
+ var REPRESENTATION_HEADERS = /* @__PURE__ */ new Set([
35
+ "transfer-encoding",
36
+ "etag",
37
+ "last-modified",
38
+ "digest",
39
+ "accept-ranges"
40
+ ]);
57
41
  function buildType(status, options) {
58
42
  if (options.typePrefix) {
59
43
  const slug = statusToSlug(status);
@@ -61,6 +45,16 @@ function buildType(status, options) {
61
45
  }
62
46
  return options.defaultType ?? "about:blank";
63
47
  }
48
+ function copyResHeaders(error, response) {
49
+ if (error instanceof HTTPException) {
50
+ error.res?.headers.forEach((value, name) => {
51
+ if (!name.startsWith("content-") && !REPRESENTATION_HEADERS.has(name)) {
52
+ response.headers.append(name, value);
53
+ }
54
+ });
55
+ }
56
+ return response;
57
+ }
64
58
  function toResponse(input, c, options) {
65
59
  let pd = normalizeProblemDetails({
66
60
  ...input,
@@ -88,28 +82,40 @@ function toResponse(input, c, options) {
88
82
  return buildProblemResponse(pd);
89
83
  }
90
84
  function problemDetailsHandler(options = {}) {
91
- return (error, c) => {
85
+ const handle = (error, c) => {
92
86
  if (error instanceof ProblemDetailsError) {
93
87
  const pd = error.problemDetails;
94
88
  return toResponse(error.hasExplicitType ? pd : { ...pd, type: void 0 }, c, options);
95
89
  }
96
90
  if (options.mapError) {
97
- const mapped = options.mapError(error);
98
- if (mapped) {
99
- return toResponse(mapped, c, options);
91
+ try {
92
+ const mapped = options.mapError(error);
93
+ if (mapped) {
94
+ return copyResHeaders(error, toResponse(mapped, c, options));
95
+ }
96
+ } catch {
100
97
  }
101
98
  }
102
99
  if (error instanceof HTTPException) {
103
- return toResponse(
104
- {
105
- status: error.status,
106
- title: statusToPhrase(error.status),
107
- detail: error.message
108
- },
109
- c,
110
- options
100
+ return copyResHeaders(
101
+ error,
102
+ toResponse(
103
+ {
104
+ status: error.status,
105
+ title: statusToPhrase(error.status),
106
+ detail: error.message || void 0
107
+ },
108
+ c,
109
+ options
110
+ )
111
111
  );
112
112
  }
113
+ if (options.onUnhandledError) {
114
+ try {
115
+ options.onUnhandledError(error, c);
116
+ } catch {
117
+ }
118
+ }
113
119
  return toResponse(
114
120
  {
115
121
  status: 500,
@@ -121,6 +127,12 @@ function problemDetailsHandler(options = {}) {
121
127
  options
122
128
  );
123
129
  };
130
+ const dispatch = (first, second) => {
131
+ if (typeof second !== "function") return handle(first, second);
132
+ const c = first;
133
+ return c.error ? handle(c.error, c) : second();
134
+ };
135
+ return dispatch;
124
136
  }
125
137
 
126
138
  // src/registry.ts
@@ -24,13 +24,134 @@ __export(standard_schema_exports, {
24
24
  });
25
25
  module.exports = __toCommonJS(standard_schema_exports);
26
26
 
27
+ // src/status.ts
28
+ var STATUS_PHRASES = {
29
+ 400: "Bad Request",
30
+ 401: "Unauthorized",
31
+ 402: "Payment Required",
32
+ 403: "Forbidden",
33
+ 404: "Not Found",
34
+ 405: "Method Not Allowed",
35
+ 406: "Not Acceptable",
36
+ 407: "Proxy Authentication Required",
37
+ 408: "Request Timeout",
38
+ 409: "Conflict",
39
+ 410: "Gone",
40
+ 411: "Length Required",
41
+ 412: "Precondition Failed",
42
+ 413: "Content Too Large",
43
+ 414: "URI Too Long",
44
+ 415: "Unsupported Media Type",
45
+ 416: "Range Not Satisfiable",
46
+ 417: "Expectation Failed",
47
+ 418: "I'm a Teapot",
48
+ 421: "Misdirected Request",
49
+ 422: "Unprocessable Content",
50
+ 423: "Locked",
51
+ 424: "Failed Dependency",
52
+ 425: "Too Early",
53
+ 426: "Upgrade Required",
54
+ 428: "Precondition Required",
55
+ 429: "Too Many Requests",
56
+ 431: "Request Header Fields Too Large",
57
+ 451: "Unavailable For Legal Reasons",
58
+ 500: "Internal Server Error",
59
+ 501: "Not Implemented",
60
+ 502: "Bad Gateway",
61
+ 503: "Service Unavailable",
62
+ 504: "Gateway Timeout",
63
+ 505: "HTTP Version Not Supported",
64
+ 506: "Variant Also Negotiates",
65
+ 507: "Insufficient Storage",
66
+ 508: "Loop Detected",
67
+ 510: "Not Extended",
68
+ 511: "Network Authentication Required"
69
+ };
70
+ var STATUS_SLUGS = Object.fromEntries(
71
+ Object.entries(STATUS_PHRASES).map(([code, phrase]) => [
72
+ Number(code),
73
+ phrase.toLowerCase().replace(/'/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "")
74
+ ])
75
+ );
76
+ function statusToPhrase(status) {
77
+ return STATUS_PHRASES[status];
78
+ }
79
+
27
80
  // src/utils.ts
28
81
  var PROBLEM_JSON_CONTENT_TYPE = "application/problem+json; charset=utf-8";
82
+ var DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
83
+ function sanitizeExtensions(extensions) {
84
+ if (!extensions) return extensions;
85
+ let filtered;
86
+ for (const key of Object.keys(extensions)) {
87
+ if (DANGEROUS_KEYS.has(key)) {
88
+ if (!filtered) filtered = { ...extensions };
89
+ delete filtered[key];
90
+ }
91
+ }
92
+ return filtered ?? extensions;
93
+ }
94
+ function clampHttpStatus(status) {
95
+ return Number.isInteger(status) && status >= 200 && status <= 599 ? status : 500;
96
+ }
29
97
  var FALLBACK_BODY = JSON.stringify({
30
98
  type: "about:blank",
31
99
  status: 500,
32
100
  title: "Internal Server Error"
33
101
  });
102
+ function normalizeProblemDetails(input) {
103
+ return {
104
+ type: input.type ?? "about:blank",
105
+ status: input.status,
106
+ title: input.title ?? statusToPhrase(input.status) ?? "Unknown Error",
107
+ detail: input.detail,
108
+ instance: input.instance,
109
+ extensions: input.extensions
110
+ };
111
+ }
112
+ function buildProblemResponse(pd) {
113
+ const { extensions, ...standard } = pd;
114
+ const status = clampHttpStatus(pd.status);
115
+ const body = { ...sanitizeExtensions(extensions), ...standard, status };
116
+ const { json, fallback } = safeStringify(body);
117
+ return new Response(json, {
118
+ status: fallback ? 500 : status,
119
+ headers: { "Content-Type": PROBLEM_JSON_CONTENT_TYPE }
120
+ });
121
+ }
122
+ function safeStringify(body) {
123
+ try {
124
+ return { json: JSON.stringify(body), fallback: false };
125
+ } catch {
126
+ return { json: FALLBACK_BODY, fallback: true };
127
+ }
128
+ }
129
+
130
+ // src/error.ts
131
+ var ProblemDetailsError = class extends Error {
132
+ /** The normalized RFC 9457 Problem Details object. */
133
+ problemDetails;
134
+ /**
135
+ * Whether the input carried an explicit `type`. Lets the handler apply
136
+ * `typePrefix`/`defaultType` only when the thrower left `type` unset.
137
+ */
138
+ hasExplicitType;
139
+ /**
140
+ * @param input - Missing `type` defaults to `"about:blank"`;
141
+ * missing `title` is derived from the HTTP status code.
142
+ */
143
+ constructor(input) {
144
+ const pd = normalizeProblemDetails(input);
145
+ super(pd.detail ?? pd.title);
146
+ this.name = "ProblemDetailsError";
147
+ this.problemDetails = pd;
148
+ this.hasExplicitType = input.type !== void 0;
149
+ }
150
+ /** Build a standalone `application/problem+json` Response without the handler middleware. */
151
+ getResponse() {
152
+ return buildProblemResponse(this.problemDetails);
153
+ }
154
+ };
34
155
 
35
156
  // src/integrations/validation.ts
36
157
  var CONTROL_CHAR_RE = /[\x00-\x1f\x7f]/g;
@@ -45,12 +166,23 @@ function sanitizeError(error) {
45
166
  };
46
167
  }
47
168
  function buildValidationResponse(errors, options) {
169
+ const title = options?.title ?? "Validation Error";
170
+ const detail = options?.detail ?? "Request validation failed";
171
+ const sanitizedErrors = errors.map(sanitizeError);
172
+ if (options?.delegateToHandler) {
173
+ throw new ProblemDetailsError({
174
+ status: 422,
175
+ title,
176
+ detail,
177
+ extensions: { errors: sanitizedErrors }
178
+ });
179
+ }
48
180
  const body = {
49
181
  type: "about:blank",
50
182
  status: 422,
51
- title: options?.title ?? "Validation Error",
52
- detail: options?.detail ?? "Request validation failed",
53
- errors: errors.map(sanitizeError)
183
+ title,
184
+ detail,
185
+ errors: sanitizedErrors
54
186
  };
55
187
  return new Response(JSON.stringify(body), {
56
188
  status: 422,
@@ -1,6 +1,6 @@
1
1
  import { StandardSchemaV1 } from '@standard-schema/spec';
2
2
  import { Context } from 'hono';
3
- import { V as ValidationHookOptions } from '../validation-DqPEnoIw.cjs';
3
+ import { V as ValidationHookOptions } from '../validation-CZHjSmb_.cjs';
4
4
 
5
5
  /**
6
6
  * Create a `@hono/standard-validator` hook that returns RFC 9457 Problem Details
@@ -1,6 +1,6 @@
1
1
  import { StandardSchemaV1 } from '@standard-schema/spec';
2
2
  import { Context } from 'hono';
3
- import { V as ValidationHookOptions } from '../validation-DqPEnoIw.js';
3
+ import { V as ValidationHookOptions } from '../validation-CZHjSmb_.js';
4
4
 
5
5
  /**
6
6
  * Create a `@hono/standard-validator` hook that returns RFC 9457 Problem Details
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  buildValidationResponse
3
- } from "../chunk-4SQFFZU6.js";
3
+ } from "../chunk-R6NMRTVW.js";
4
+ import "../chunk-LIQQKPXQ.js";
4
5
  import "../chunk-URAOTABQ.js";
5
6
  import "../chunk-P4D7EVU3.js";
6
7
 
@@ -24,13 +24,134 @@ __export(valibot_exports, {
24
24
  });
25
25
  module.exports = __toCommonJS(valibot_exports);
26
26
 
27
+ // src/status.ts
28
+ var STATUS_PHRASES = {
29
+ 400: "Bad Request",
30
+ 401: "Unauthorized",
31
+ 402: "Payment Required",
32
+ 403: "Forbidden",
33
+ 404: "Not Found",
34
+ 405: "Method Not Allowed",
35
+ 406: "Not Acceptable",
36
+ 407: "Proxy Authentication Required",
37
+ 408: "Request Timeout",
38
+ 409: "Conflict",
39
+ 410: "Gone",
40
+ 411: "Length Required",
41
+ 412: "Precondition Failed",
42
+ 413: "Content Too Large",
43
+ 414: "URI Too Long",
44
+ 415: "Unsupported Media Type",
45
+ 416: "Range Not Satisfiable",
46
+ 417: "Expectation Failed",
47
+ 418: "I'm a Teapot",
48
+ 421: "Misdirected Request",
49
+ 422: "Unprocessable Content",
50
+ 423: "Locked",
51
+ 424: "Failed Dependency",
52
+ 425: "Too Early",
53
+ 426: "Upgrade Required",
54
+ 428: "Precondition Required",
55
+ 429: "Too Many Requests",
56
+ 431: "Request Header Fields Too Large",
57
+ 451: "Unavailable For Legal Reasons",
58
+ 500: "Internal Server Error",
59
+ 501: "Not Implemented",
60
+ 502: "Bad Gateway",
61
+ 503: "Service Unavailable",
62
+ 504: "Gateway Timeout",
63
+ 505: "HTTP Version Not Supported",
64
+ 506: "Variant Also Negotiates",
65
+ 507: "Insufficient Storage",
66
+ 508: "Loop Detected",
67
+ 510: "Not Extended",
68
+ 511: "Network Authentication Required"
69
+ };
70
+ var STATUS_SLUGS = Object.fromEntries(
71
+ Object.entries(STATUS_PHRASES).map(([code, phrase]) => [
72
+ Number(code),
73
+ phrase.toLowerCase().replace(/'/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "")
74
+ ])
75
+ );
76
+ function statusToPhrase(status) {
77
+ return STATUS_PHRASES[status];
78
+ }
79
+
27
80
  // src/utils.ts
28
81
  var PROBLEM_JSON_CONTENT_TYPE = "application/problem+json; charset=utf-8";
82
+ var DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
83
+ function sanitizeExtensions(extensions) {
84
+ if (!extensions) return extensions;
85
+ let filtered;
86
+ for (const key of Object.keys(extensions)) {
87
+ if (DANGEROUS_KEYS.has(key)) {
88
+ if (!filtered) filtered = { ...extensions };
89
+ delete filtered[key];
90
+ }
91
+ }
92
+ return filtered ?? extensions;
93
+ }
94
+ function clampHttpStatus(status) {
95
+ return Number.isInteger(status) && status >= 200 && status <= 599 ? status : 500;
96
+ }
29
97
  var FALLBACK_BODY = JSON.stringify({
30
98
  type: "about:blank",
31
99
  status: 500,
32
100
  title: "Internal Server Error"
33
101
  });
102
+ function normalizeProblemDetails(input) {
103
+ return {
104
+ type: input.type ?? "about:blank",
105
+ status: input.status,
106
+ title: input.title ?? statusToPhrase(input.status) ?? "Unknown Error",
107
+ detail: input.detail,
108
+ instance: input.instance,
109
+ extensions: input.extensions
110
+ };
111
+ }
112
+ function buildProblemResponse(pd) {
113
+ const { extensions, ...standard } = pd;
114
+ const status = clampHttpStatus(pd.status);
115
+ const body = { ...sanitizeExtensions(extensions), ...standard, status };
116
+ const { json, fallback } = safeStringify(body);
117
+ return new Response(json, {
118
+ status: fallback ? 500 : status,
119
+ headers: { "Content-Type": PROBLEM_JSON_CONTENT_TYPE }
120
+ });
121
+ }
122
+ function safeStringify(body) {
123
+ try {
124
+ return { json: JSON.stringify(body), fallback: false };
125
+ } catch {
126
+ return { json: FALLBACK_BODY, fallback: true };
127
+ }
128
+ }
129
+
130
+ // src/error.ts
131
+ var ProblemDetailsError = class extends Error {
132
+ /** The normalized RFC 9457 Problem Details object. */
133
+ problemDetails;
134
+ /**
135
+ * Whether the input carried an explicit `type`. Lets the handler apply
136
+ * `typePrefix`/`defaultType` only when the thrower left `type` unset.
137
+ */
138
+ hasExplicitType;
139
+ /**
140
+ * @param input - Missing `type` defaults to `"about:blank"`;
141
+ * missing `title` is derived from the HTTP status code.
142
+ */
143
+ constructor(input) {
144
+ const pd = normalizeProblemDetails(input);
145
+ super(pd.detail ?? pd.title);
146
+ this.name = "ProblemDetailsError";
147
+ this.problemDetails = pd;
148
+ this.hasExplicitType = input.type !== void 0;
149
+ }
150
+ /** Build a standalone `application/problem+json` Response without the handler middleware. */
151
+ getResponse() {
152
+ return buildProblemResponse(this.problemDetails);
153
+ }
154
+ };
34
155
 
35
156
  // src/integrations/validation.ts
36
157
  var CONTROL_CHAR_RE = /[\x00-\x1f\x7f]/g;
@@ -45,12 +166,23 @@ function sanitizeError(error) {
45
166
  };
46
167
  }
47
168
  function buildValidationResponse(errors, options) {
169
+ const title = options?.title ?? "Validation Error";
170
+ const detail = options?.detail ?? "Request validation failed";
171
+ const sanitizedErrors = errors.map(sanitizeError);
172
+ if (options?.delegateToHandler) {
173
+ throw new ProblemDetailsError({
174
+ status: 422,
175
+ title,
176
+ detail,
177
+ extensions: { errors: sanitizedErrors }
178
+ });
179
+ }
48
180
  const body = {
49
181
  type: "about:blank",
50
182
  status: 422,
51
- title: options?.title ?? "Validation Error",
52
- detail: options?.detail ?? "Request validation failed",
53
- errors: errors.map(sanitizeError)
183
+ title,
184
+ detail,
185
+ errors: sanitizedErrors
54
186
  };
55
187
  return new Response(JSON.stringify(body), {
56
188
  status: 422,
@@ -1,6 +1,6 @@
1
1
  import { Context } from 'hono';
2
2
  import { GenericSchema, GenericSchemaAsync, SafeParseResult } from 'valibot';
3
- import { V as ValidationHookOptions } from '../validation-DqPEnoIw.cjs';
3
+ import { V as ValidationHookOptions } from '../validation-CZHjSmb_.cjs';
4
4
 
5
5
  /**
6
6
  * Create a `@hono/valibot-validator` hook that returns RFC 9457 Problem Details
@@ -1,6 +1,6 @@
1
1
  import { Context } from 'hono';
2
2
  import { GenericSchema, GenericSchemaAsync, SafeParseResult } from 'valibot';
3
- import { V as ValidationHookOptions } from '../validation-DqPEnoIw.js';
3
+ import { V as ValidationHookOptions } from '../validation-CZHjSmb_.js';
4
4
 
5
5
  /**
6
6
  * Create a `@hono/valibot-validator` hook that returns RFC 9457 Problem Details
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  buildValidationResponse
3
- } from "../chunk-4SQFFZU6.js";
3
+ } from "../chunk-R6NMRTVW.js";
4
+ import "../chunk-LIQQKPXQ.js";
4
5
  import "../chunk-URAOTABQ.js";
5
6
  import "../chunk-P4D7EVU3.js";
6
7
 
@@ -24,13 +24,134 @@ __export(zod_exports, {
24
24
  });
25
25
  module.exports = __toCommonJS(zod_exports);
26
26
 
27
+ // src/status.ts
28
+ var STATUS_PHRASES = {
29
+ 400: "Bad Request",
30
+ 401: "Unauthorized",
31
+ 402: "Payment Required",
32
+ 403: "Forbidden",
33
+ 404: "Not Found",
34
+ 405: "Method Not Allowed",
35
+ 406: "Not Acceptable",
36
+ 407: "Proxy Authentication Required",
37
+ 408: "Request Timeout",
38
+ 409: "Conflict",
39
+ 410: "Gone",
40
+ 411: "Length Required",
41
+ 412: "Precondition Failed",
42
+ 413: "Content Too Large",
43
+ 414: "URI Too Long",
44
+ 415: "Unsupported Media Type",
45
+ 416: "Range Not Satisfiable",
46
+ 417: "Expectation Failed",
47
+ 418: "I'm a Teapot",
48
+ 421: "Misdirected Request",
49
+ 422: "Unprocessable Content",
50
+ 423: "Locked",
51
+ 424: "Failed Dependency",
52
+ 425: "Too Early",
53
+ 426: "Upgrade Required",
54
+ 428: "Precondition Required",
55
+ 429: "Too Many Requests",
56
+ 431: "Request Header Fields Too Large",
57
+ 451: "Unavailable For Legal Reasons",
58
+ 500: "Internal Server Error",
59
+ 501: "Not Implemented",
60
+ 502: "Bad Gateway",
61
+ 503: "Service Unavailable",
62
+ 504: "Gateway Timeout",
63
+ 505: "HTTP Version Not Supported",
64
+ 506: "Variant Also Negotiates",
65
+ 507: "Insufficient Storage",
66
+ 508: "Loop Detected",
67
+ 510: "Not Extended",
68
+ 511: "Network Authentication Required"
69
+ };
70
+ var STATUS_SLUGS = Object.fromEntries(
71
+ Object.entries(STATUS_PHRASES).map(([code, phrase]) => [
72
+ Number(code),
73
+ phrase.toLowerCase().replace(/'/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "")
74
+ ])
75
+ );
76
+ function statusToPhrase(status) {
77
+ return STATUS_PHRASES[status];
78
+ }
79
+
27
80
  // src/utils.ts
28
81
  var PROBLEM_JSON_CONTENT_TYPE = "application/problem+json; charset=utf-8";
82
+ var DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
83
+ function sanitizeExtensions(extensions) {
84
+ if (!extensions) return extensions;
85
+ let filtered;
86
+ for (const key of Object.keys(extensions)) {
87
+ if (DANGEROUS_KEYS.has(key)) {
88
+ if (!filtered) filtered = { ...extensions };
89
+ delete filtered[key];
90
+ }
91
+ }
92
+ return filtered ?? extensions;
93
+ }
94
+ function clampHttpStatus(status) {
95
+ return Number.isInteger(status) && status >= 200 && status <= 599 ? status : 500;
96
+ }
29
97
  var FALLBACK_BODY = JSON.stringify({
30
98
  type: "about:blank",
31
99
  status: 500,
32
100
  title: "Internal Server Error"
33
101
  });
102
+ function normalizeProblemDetails(input) {
103
+ return {
104
+ type: input.type ?? "about:blank",
105
+ status: input.status,
106
+ title: input.title ?? statusToPhrase(input.status) ?? "Unknown Error",
107
+ detail: input.detail,
108
+ instance: input.instance,
109
+ extensions: input.extensions
110
+ };
111
+ }
112
+ function buildProblemResponse(pd) {
113
+ const { extensions, ...standard } = pd;
114
+ const status = clampHttpStatus(pd.status);
115
+ const body = { ...sanitizeExtensions(extensions), ...standard, status };
116
+ const { json, fallback } = safeStringify(body);
117
+ return new Response(json, {
118
+ status: fallback ? 500 : status,
119
+ headers: { "Content-Type": PROBLEM_JSON_CONTENT_TYPE }
120
+ });
121
+ }
122
+ function safeStringify(body) {
123
+ try {
124
+ return { json: JSON.stringify(body), fallback: false };
125
+ } catch {
126
+ return { json: FALLBACK_BODY, fallback: true };
127
+ }
128
+ }
129
+
130
+ // src/error.ts
131
+ var ProblemDetailsError = class extends Error {
132
+ /** The normalized RFC 9457 Problem Details object. */
133
+ problemDetails;
134
+ /**
135
+ * Whether the input carried an explicit `type`. Lets the handler apply
136
+ * `typePrefix`/`defaultType` only when the thrower left `type` unset.
137
+ */
138
+ hasExplicitType;
139
+ /**
140
+ * @param input - Missing `type` defaults to `"about:blank"`;
141
+ * missing `title` is derived from the HTTP status code.
142
+ */
143
+ constructor(input) {
144
+ const pd = normalizeProblemDetails(input);
145
+ super(pd.detail ?? pd.title);
146
+ this.name = "ProblemDetailsError";
147
+ this.problemDetails = pd;
148
+ this.hasExplicitType = input.type !== void 0;
149
+ }
150
+ /** Build a standalone `application/problem+json` Response without the handler middleware. */
151
+ getResponse() {
152
+ return buildProblemResponse(this.problemDetails);
153
+ }
154
+ };
34
155
 
35
156
  // src/integrations/validation.ts
36
157
  var CONTROL_CHAR_RE = /[\x00-\x1f\x7f]/g;
@@ -45,12 +166,23 @@ function sanitizeError(error) {
45
166
  };
46
167
  }
47
168
  function buildValidationResponse(errors, options) {
169
+ const title = options?.title ?? "Validation Error";
170
+ const detail = options?.detail ?? "Request validation failed";
171
+ const sanitizedErrors = errors.map(sanitizeError);
172
+ if (options?.delegateToHandler) {
173
+ throw new ProblemDetailsError({
174
+ status: 422,
175
+ title,
176
+ detail,
177
+ extensions: { errors: sanitizedErrors }
178
+ });
179
+ }
48
180
  const body = {
49
181
  type: "about:blank",
50
182
  status: 422,
51
- title: options?.title ?? "Validation Error",
52
- detail: options?.detail ?? "Request validation failed",
53
- errors: errors.map(sanitizeError)
183
+ title,
184
+ detail,
185
+ errors: sanitizedErrors
54
186
  };
55
187
  return new Response(JSON.stringify(body), {
56
188
  status: 422,
@@ -1,6 +1,6 @@
1
1
  import { Context } from 'hono';
2
2
  import { ZodError } from 'zod';
3
- import { V as ValidationHookOptions } from '../validation-DqPEnoIw.cjs';
3
+ import { V as ValidationHookOptions } from '../validation-CZHjSmb_.cjs';
4
4
 
5
5
  /**
6
6
  * Create a `@hono/zod-validator` hook that returns RFC 9457 Problem Details
@@ -1,6 +1,6 @@
1
1
  import { Context } from 'hono';
2
2
  import { ZodError } from 'zod';
3
- import { V as ValidationHookOptions } from '../validation-DqPEnoIw.js';
3
+ import { V as ValidationHookOptions } from '../validation-CZHjSmb_.js';
4
4
 
5
5
  /**
6
6
  * Create a `@hono/zod-validator` hook that returns RFC 9457 Problem Details
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  buildValidationResponse
3
- } from "../chunk-4SQFFZU6.js";
3
+ } from "../chunk-R6NMRTVW.js";
4
+ import "../chunk-LIQQKPXQ.js";
4
5
  import "../chunk-URAOTABQ.js";
5
6
  import "../chunk-P4D7EVU3.js";
6
7
 
@@ -0,0 +1,14 @@
1
+ interface ValidationHookOptions {
2
+ title?: string;
3
+ detail?: string;
4
+ /**
5
+ * Throw a `ProblemDetailsError` instead of returning a Response, so
6
+ * `problemDetailsHandler` builds the response and its options (`typePrefix`,
7
+ * `defaultType`, `localize`, `autoInstance`, `otelApi`) apply. Without
8
+ * `app.onError(problemDetailsHandler())`, Hono's default error handler falls back to
9
+ * `ProblemDetailsError.getResponse()`, returning the plain 422. Default: `false`.
10
+ */
11
+ delegateToHandler?: boolean;
12
+ }
13
+
14
+ export type { ValidationHookOptions as V };
@@ -0,0 +1,14 @@
1
+ interface ValidationHookOptions {
2
+ title?: string;
3
+ detail?: string;
4
+ /**
5
+ * Throw a `ProblemDetailsError` instead of returning a Response, so
6
+ * `problemDetailsHandler` builds the response and its options (`typePrefix`,
7
+ * `defaultType`, `localize`, `autoInstance`, `otelApi`) apply. Without
8
+ * `app.onError(problemDetailsHandler())`, Hono's default error handler falls back to
9
+ * `ProblemDetailsError.getResponse()`, returning the plain 422. Default: `false`.
10
+ */
11
+ delegateToHandler?: boolean;
12
+ }
13
+
14
+ export type { ValidationHookOptions as V };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hono-problem-details",
3
- "version": "0.11.0",
3
+ "version": "0.12.1",
4
4
  "description": "RFC 9457 Problem Details middleware for Hono",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -118,7 +118,7 @@
118
118
  "@hono/zod-validator": "^0.7.5",
119
119
  "@opentelemetry/api": "^1.0.0",
120
120
  "@standard-schema/spec": "^1.0.0",
121
- "hono": ">=4.12.34",
121
+ "hono": ">=4.13.7",
122
122
  "valibot": "^1.0.0",
123
123
  "zod": "^3.25.0 || ^4.0.0"
124
124
  },
@@ -151,22 +151,22 @@
151
151
  "devDependencies": {
152
152
  "@arethetypeswrong/cli": "0.18.5",
153
153
  "@biomejs/biome": "^2.4.14",
154
- "@changesets/changelog-github": "0.7.0",
155
- "@changesets/cli": "2.31.1",
154
+ "@changesets/changelog-github": "1.0.1",
155
+ "@changesets/cli": "3.0.3",
156
156
  "@hono/standard-validator": "0.4.0",
157
157
  "@hono/valibot-validator": "^0.6.1",
158
- "@hono/zod-openapi": "1.6.0",
158
+ "@hono/zod-openapi": "1.6.3",
159
159
  "@hono/zod-validator": "^0.9.0",
160
160
  "@opentelemetry/api": "^1.0.0",
161
161
  "@standard-schema/spec": "1.1.0",
162
- "@vitest/coverage-v8": "^4.1.8",
163
- "hono": "^4.12.34",
164
- "knip": "6.32.2",
165
- "lefthook": "2.1.10",
162
+ "@vitest/coverage-v8": "^4.1.12",
163
+ "hono": "^4.13.7",
164
+ "knip": "6.41.0",
165
+ "lefthook": "2.2.1",
166
166
  "tsup": "^8.0.0",
167
167
  "typescript": "^6.0.3",
168
168
  "valibot": "^1.3.1",
169
- "vitest": "^4.1.8",
169
+ "vitest": "^4.1.12",
170
170
  "zod": "^4.0.0"
171
171
  },
172
172
  "engines": {
@@ -1,6 +0,0 @@
1
- interface ValidationHookOptions {
2
- title?: string;
3
- detail?: string;
4
- }
5
-
6
- export type { ValidationHookOptions as V };
@@ -1,6 +0,0 @@
1
- interface ValidationHookOptions {
2
- title?: string;
3
- detail?: string;
4
- }
5
-
6
- export type { ValidationHookOptions as V };