hono-problem-details 0.8.2 → 0.10.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.
package/README.md CHANGED
@@ -53,7 +53,7 @@ npm install hono-problem-details
53
53
 
54
54
  ### Requirements
55
55
 
56
- - Hono `>= 4.12.14` (peer dependency)
56
+ - Hono `>= 4.12.27` (peer dependency; floor raised for upstream security fixes)
57
57
  - TypeScript `>= 5.0` — the published `.d.ts` files are CI-tested against TS 5.0, 5.4, 5.7, 5.9, and 6.0. Older TS versions may work but are not verified.
58
58
  - Node.js `>= 22` (Node 20 reached end-of-life in April 2026; v0.6.0 raised the floor)
59
59
 
@@ -74,7 +74,7 @@ app.get("/not-found", (c) => {
74
74
 
75
75
  // Response:
76
76
  // HTTP/1.1 404 Not Found
77
- // Content-Type: application/problem+json
77
+ // Content-Type: application/problem+json; charset=utf-8
78
78
  // {
79
79
  // "type": "about:blank",
80
80
  // "status": 404,
@@ -180,7 +180,7 @@ app.get("/boom", () => {
180
180
  });
181
181
 
182
182
  // HTTP/1.1 500 Internal Server Error
183
- // Content-Type: application/problem+json
183
+ // Content-Type: application/problem+json; charset=utf-8
184
184
  // {
185
185
  // "type": "about:blank",
186
186
  // "status": 500,
@@ -268,6 +268,53 @@ throw problems.create("RATE_LIMITED", {
268
268
  });
269
269
  ```
270
270
 
271
+ ### Auto-deriving a `code` extension
272
+
273
+ Pass `{ autoCode: true }` to derive a `code` extension from each registry key, so clients can
274
+ `switch` on a short flat string instead of parsing the `type` URI:
275
+
276
+ ```ts
277
+ const problems = createProblemTypeRegistry(
278
+ {
279
+ ORDER_CONFLICT: {
280
+ type: "https://api.example.com/problems/order-conflict",
281
+ status: 409,
282
+ title: "Order Conflict",
283
+ },
284
+ },
285
+ { autoCode: true },
286
+ );
287
+
288
+ const error = problems.create("ORDER_CONFLICT");
289
+ error.problemDetails.extensions; // { code: "order-conflict" }
290
+ ```
291
+
292
+ The default transformation lowercases, collapses runs of underscores into a single hyphen, and
293
+ strips leading/trailing hyphens (`V2_AUTH` → `v2-auth`, `AUTH__TOKEN_EXPIRED` → `auth-token-expired`,
294
+ `_AUTH_` → `auth`). Keys are expected to be `SCREAMING_SNAKE_CASE`.
295
+
296
+ Two overrides take priority over the derived value, in this order:
297
+
298
+ 1. An explicit `code` on the registry definition (emitted even without `autoCode`):
299
+ ```ts
300
+ createProblemTypeRegistry(
301
+ {
302
+ ORDER_CONFLICT: {
303
+ type: "https://api.example.com/problems/order-conflict",
304
+ status: 409,
305
+ title: "Order Conflict",
306
+ code: "legacy/order_conflict",
307
+ },
308
+ },
309
+ { autoCode: true },
310
+ );
311
+ ```
312
+ 2. `extensions.code` passed to `.create()`, which wins over both the derived value and an
313
+ explicit registry `code`.
314
+
315
+ `get(key)` returns the same resolved `code` that `create(key)` emits, so docs or schemas built
316
+ from the registry stay in sync with the responses.
317
+
271
318
  ### When to use the registry vs `problemDetails()`
272
319
 
273
320
  Reach for `createProblemTypeRegistry` when your API has a fixed set of domain errors and you
@@ -297,7 +344,7 @@ app.post("/users", zValidator("json", schema, zodProblemHook()), (c) => {
297
344
 
298
345
  // Validation error response:
299
346
  // HTTP/1.1 422 Unprocessable Content
300
- // Content-Type: application/problem+json
347
+ // Content-Type: application/problem+json; charset=utf-8
301
348
  // {
302
349
  // "type": "about:blank",
303
350
  // "status": 422,
@@ -447,7 +494,7 @@ problemDetailsHandler({
447
494
  });
448
495
  ```
449
496
 
450
- When enabled, the handler adds a `traceId` extension member to all problem details responses when a trace is active.
497
+ 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`.
451
498
  This allows clients to correlate errors with server-side traces for easier debugging.
452
499
 
453
500
  ## Handler Options
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  PROBLEM_JSON_CONTENT_TYPE
3
- } from "./chunk-EL44ATLR.js";
3
+ } from "./chunk-VPS467Z5.js";
4
4
 
5
5
  // src/integrations/validation.ts
6
6
  var CONTROL_CHAR_RE = /[\x00-\x1f\x7f]/g;
@@ -36,10 +36,11 @@ function normalizeProblemDetails(input) {
36
36
  }
37
37
  function buildProblemResponse(pd) {
38
38
  const { extensions, ...standard } = pd;
39
- const body = { ...sanitizeExtensions(extensions), ...standard };
39
+ const status = clampHttpStatus(pd.status);
40
+ const body = { ...sanitizeExtensions(extensions), ...standard, status };
40
41
  const { json, fallback } = safeStringify(body);
41
42
  return new Response(json, {
42
- status: fallback ? 500 : clampHttpStatus(pd.status),
43
+ status: fallback ? 500 : status,
43
44
  headers: { "Content-Type": PROBLEM_JSON_CONTENT_TYPE }
44
45
  });
45
46
  }
package/dist/index.cjs CHANGED
@@ -120,10 +120,11 @@ function normalizeProblemDetails(input) {
120
120
  }
121
121
  function buildProblemResponse(pd) {
122
122
  const { extensions, ...standard } = pd;
123
- const body = { ...sanitizeExtensions(extensions), ...standard };
123
+ const status = clampHttpStatus(pd.status);
124
+ const body = { ...sanitizeExtensions(extensions), ...standard, status };
124
125
  const { json, fallback } = safeStringify(body);
125
126
  return new Response(json, {
126
- status: fallback ? 500 : clampHttpStatus(pd.status),
127
+ status: fallback ? 500 : status,
127
128
  headers: { "Content-Type": PROBLEM_JSON_CONTENT_TYPE }
128
129
  });
129
130
  }
@@ -139,6 +140,11 @@ function safeStringify(body) {
139
140
  var ProblemDetailsError = class extends Error {
140
141
  /** The normalized RFC 9457 Problem Details object. */
141
142
  problemDetails;
143
+ /**
144
+ * Whether the input carried an explicit `type`. Lets the handler apply
145
+ * `typePrefix`/`defaultType` only when the thrower left `type` unset.
146
+ */
147
+ hasExplicitType;
142
148
  /**
143
149
  * @param input - Missing `type` defaults to `"about:blank"`;
144
150
  * missing `title` is derived from the HTTP status code.
@@ -148,6 +154,7 @@ var ProblemDetailsError = class extends Error {
148
154
  super(pd.detail ?? pd.title);
149
155
  this.name = "ProblemDetailsError";
150
156
  this.problemDetails = pd;
157
+ this.hasExplicitType = input.type !== void 0;
151
158
  }
152
159
  /** Build a standalone `application/problem+json` Response without the handler middleware. */
153
160
  getResponse() {
@@ -183,7 +190,10 @@ function buildType(status, options) {
183
190
  return options.defaultType ?? "about:blank";
184
191
  }
185
192
  function toResponse(input, c, options) {
186
- let pd = normalizeProblemDetails(input);
193
+ let pd = normalizeProblemDetails({
194
+ ...input,
195
+ type: input.type ?? buildType(input.status, options)
196
+ });
187
197
  if (options.autoInstance && pd.instance === void 0) {
188
198
  pd = { ...pd, instance: c.req.path };
189
199
  }
@@ -208,7 +218,8 @@ function toResponse(input, c, options) {
208
218
  function problemDetailsHandler(options = {}) {
209
219
  return (error, c) => {
210
220
  if (error instanceof ProblemDetailsError) {
211
- return toResponse(error.problemDetails, c, options);
221
+ const pd = error.problemDetails;
222
+ return toResponse(error.hasExplicitType ? pd : { ...pd, type: void 0 }, c, options);
212
223
  }
213
224
  if (options.mapError) {
214
225
  const mapped = options.mapError(error);
@@ -220,7 +231,6 @@ function problemDetailsHandler(options = {}) {
220
231
  return toResponse(
221
232
  {
222
233
  status: error.status,
223
- type: buildType(error.status, options),
224
234
  title: statusToPhrase(error.status),
225
235
  detail: error.message
226
236
  },
@@ -231,7 +241,6 @@ function problemDetailsHandler(options = {}) {
231
241
  return toResponse(
232
242
  {
233
243
  status: 500,
234
- type: buildType(500, options),
235
244
  title: "Internal Server Error",
236
245
  detail: "An unexpected error occurred",
237
246
  extensions: options.includeStack ? { stack: error.stack } : void 0
@@ -243,11 +252,26 @@ function problemDetailsHandler(options = {}) {
243
252
  }
244
253
 
245
254
  // src/registry.ts
246
- function createProblemTypeRegistry(definitions) {
255
+ function deriveCode(key) {
256
+ return key.toLowerCase().replace(/_+/g, "-").replace(/^-+|-+$/g, "");
257
+ }
258
+ function createProblemTypeRegistry(definitions, options) {
259
+ const autoCode = options?.autoCode ?? false;
260
+ const resolved = new Map(
261
+ Object.keys(definitions).map((key) => {
262
+ const definition = definitions[key];
263
+ const code = definition.code ?? (autoCode ? deriveCode(key) : void 0);
264
+ return [key, code === void 0 ? definition : { ...definition, code }];
265
+ })
266
+ );
247
267
  return {
248
- create: (key, options) => new ProblemDetailsError({ ...definitions[key], ...options }),
249
- get: (key) => definitions[key],
250
- types: () => Object.keys(definitions)
268
+ create: (key, createOptions) => {
269
+ const { code, ...definition } = resolved.get(key) ?? {};
270
+ const extensions = code !== void 0 ? { code, ...createOptions?.extensions } : createOptions?.extensions;
271
+ return new ProblemDetailsError({ ...definition, ...createOptions, extensions });
272
+ },
273
+ get: (key) => resolved.get(key),
274
+ types: () => [...resolved.keys()]
251
275
  };
252
276
  }
253
277
  // Annotate the CommonJS export names for ESM import in node:
package/dist/index.d.cts CHANGED
@@ -96,6 +96,11 @@ interface OtelApiLike {
96
96
  declare class ProblemDetailsError extends Error {
97
97
  /** The normalized RFC 9457 Problem Details object. */
98
98
  readonly problemDetails: ProblemDetails;
99
+ /**
100
+ * Whether the input carried an explicit `type`. Lets the handler apply
101
+ * `typePrefix`/`defaultType` only when the thrower left `type` unset.
102
+ */
103
+ readonly hasExplicitType: boolean;
99
104
  /**
100
105
  * @param input - Missing `type` defaults to `"about:blank"`;
101
106
  * missing `title` is derived from the HTTP status code.
@@ -138,16 +143,31 @@ interface ProblemTypeDefinition {
138
143
  type: string;
139
144
  status: number;
140
145
  title: string;
146
+ /**
147
+ * Explicit `code` extension for this type. Always emitted, regardless of
148
+ * `autoCode`, and takes priority over an `autoCode`-derived value.
149
+ */
150
+ code?: string;
141
151
  }
142
152
  interface CreateOptions<T extends Record<string, unknown> = Record<string, unknown>> {
143
153
  detail?: string;
144
154
  instance?: string;
145
155
  extensions?: T;
146
156
  }
157
+ interface RegistryOptions {
158
+ /**
159
+ * Derive a `code` extension from each registry key (SCREAMING_SNAKE -> kebab-case)
160
+ * when the definition doesn't set an explicit `code`. Default: `false`.
161
+ */
162
+ autoCode?: boolean;
163
+ }
147
164
  interface ProblemTypeRegistry<K extends string> {
148
165
  /** Create a {@link ProblemDetailsError} from a registered problem type key. */
149
166
  create: <T extends Record<string, unknown>>(key: K, options?: CreateOptions<T>) => ProblemDetailsError;
150
- /** Get the base definition (type, status, title) for a registered key. */
167
+ /**
168
+ * Get the resolved definition for a registered key, including any
169
+ * `autoCode`-derived or explicit `code` that `create()` would emit.
170
+ */
151
171
  get: (key: K) => ProblemTypeDefinition;
152
172
  /** List all registered problem type keys. */
153
173
  types: () => K[];
@@ -167,8 +187,11 @@ interface ProblemTypeRegistry<K extends string> {
167
187
  * });
168
188
  * throw problems.create("ORDER_CONFLICT", { detail: "Already exists" });
169
189
  * ```
190
+ *
191
+ * Pass `{ autoCode: true }` to derive a `code` extension from each key, unless the
192
+ * definition sets an explicit `code` or the caller passes `extensions.code` to `create()`.
170
193
  */
171
- declare function createProblemTypeRegistry<K extends string>(definitions: Record<K, ProblemTypeDefinition>): ProblemTypeRegistry<K>;
194
+ declare function createProblemTypeRegistry<K extends string>(definitions: Record<K, ProblemTypeDefinition>, options?: RegistryOptions): ProblemTypeRegistry<K>;
172
195
 
173
196
  /** Look up the standard HTTP reason phrase for a status code (e.g. 404 → `"Not Found"`). */
174
197
  declare function statusToPhrase(status: number): string | undefined;
package/dist/index.d.ts CHANGED
@@ -96,6 +96,11 @@ interface OtelApiLike {
96
96
  declare class ProblemDetailsError extends Error {
97
97
  /** The normalized RFC 9457 Problem Details object. */
98
98
  readonly problemDetails: ProblemDetails;
99
+ /**
100
+ * Whether the input carried an explicit `type`. Lets the handler apply
101
+ * `typePrefix`/`defaultType` only when the thrower left `type` unset.
102
+ */
103
+ readonly hasExplicitType: boolean;
99
104
  /**
100
105
  * @param input - Missing `type` defaults to `"about:blank"`;
101
106
  * missing `title` is derived from the HTTP status code.
@@ -138,16 +143,31 @@ interface ProblemTypeDefinition {
138
143
  type: string;
139
144
  status: number;
140
145
  title: string;
146
+ /**
147
+ * Explicit `code` extension for this type. Always emitted, regardless of
148
+ * `autoCode`, and takes priority over an `autoCode`-derived value.
149
+ */
150
+ code?: string;
141
151
  }
142
152
  interface CreateOptions<T extends Record<string, unknown> = Record<string, unknown>> {
143
153
  detail?: string;
144
154
  instance?: string;
145
155
  extensions?: T;
146
156
  }
157
+ interface RegistryOptions {
158
+ /**
159
+ * Derive a `code` extension from each registry key (SCREAMING_SNAKE -> kebab-case)
160
+ * when the definition doesn't set an explicit `code`. Default: `false`.
161
+ */
162
+ autoCode?: boolean;
163
+ }
147
164
  interface ProblemTypeRegistry<K extends string> {
148
165
  /** Create a {@link ProblemDetailsError} from a registered problem type key. */
149
166
  create: <T extends Record<string, unknown>>(key: K, options?: CreateOptions<T>) => ProblemDetailsError;
150
- /** Get the base definition (type, status, title) for a registered key. */
167
+ /**
168
+ * Get the resolved definition for a registered key, including any
169
+ * `autoCode`-derived or explicit `code` that `create()` would emit.
170
+ */
151
171
  get: (key: K) => ProblemTypeDefinition;
152
172
  /** List all registered problem type keys. */
153
173
  types: () => K[];
@@ -167,8 +187,11 @@ interface ProblemTypeRegistry<K extends string> {
167
187
  * });
168
188
  * throw problems.create("ORDER_CONFLICT", { detail: "Already exists" });
169
189
  * ```
190
+ *
191
+ * Pass `{ autoCode: true }` to derive a `code` extension from each key, unless the
192
+ * definition sets an explicit `code` or the caller passes `extensions.code` to `create()`.
170
193
  */
171
- declare function createProblemTypeRegistry<K extends string>(definitions: Record<K, ProblemTypeDefinition>): ProblemTypeRegistry<K>;
194
+ declare function createProblemTypeRegistry<K extends string>(definitions: Record<K, ProblemTypeDefinition>, options?: RegistryOptions): ProblemTypeRegistry<K>;
172
195
 
173
196
  /** Look up the standard HTTP reason phrase for a status code (e.g. 404 → `"Not Found"`). */
174
197
  declare function statusToPhrase(status: number): string | undefined;
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@ import {
2
2
  PROBLEM_JSON_CONTENT_TYPE,
3
3
  buildProblemResponse,
4
4
  normalizeProblemDetails
5
- } from "./chunk-EL44ATLR.js";
5
+ } from "./chunk-VPS467Z5.js";
6
6
  import {
7
7
  statusToPhrase,
8
8
  statusToSlug
@@ -12,6 +12,11 @@ import {
12
12
  var ProblemDetailsError = class extends Error {
13
13
  /** The normalized RFC 9457 Problem Details object. */
14
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;
15
20
  /**
16
21
  * @param input - Missing `type` defaults to `"about:blank"`;
17
22
  * missing `title` is derived from the HTTP status code.
@@ -21,6 +26,7 @@ var ProblemDetailsError = class extends Error {
21
26
  super(pd.detail ?? pd.title);
22
27
  this.name = "ProblemDetailsError";
23
28
  this.problemDetails = pd;
29
+ this.hasExplicitType = input.type !== void 0;
24
30
  }
25
31
  /** Build a standalone `application/problem+json` Response without the handler middleware. */
26
32
  getResponse() {
@@ -56,7 +62,10 @@ function buildType(status, options) {
56
62
  return options.defaultType ?? "about:blank";
57
63
  }
58
64
  function toResponse(input, c, options) {
59
- let pd = normalizeProblemDetails(input);
65
+ let pd = normalizeProblemDetails({
66
+ ...input,
67
+ type: input.type ?? buildType(input.status, options)
68
+ });
60
69
  if (options.autoInstance && pd.instance === void 0) {
61
70
  pd = { ...pd, instance: c.req.path };
62
71
  }
@@ -81,7 +90,8 @@ function toResponse(input, c, options) {
81
90
  function problemDetailsHandler(options = {}) {
82
91
  return (error, c) => {
83
92
  if (error instanceof ProblemDetailsError) {
84
- return toResponse(error.problemDetails, c, options);
93
+ const pd = error.problemDetails;
94
+ return toResponse(error.hasExplicitType ? pd : { ...pd, type: void 0 }, c, options);
85
95
  }
86
96
  if (options.mapError) {
87
97
  const mapped = options.mapError(error);
@@ -93,7 +103,6 @@ function problemDetailsHandler(options = {}) {
93
103
  return toResponse(
94
104
  {
95
105
  status: error.status,
96
- type: buildType(error.status, options),
97
106
  title: statusToPhrase(error.status),
98
107
  detail: error.message
99
108
  },
@@ -104,7 +113,6 @@ function problemDetailsHandler(options = {}) {
104
113
  return toResponse(
105
114
  {
106
115
  status: 500,
107
- type: buildType(500, options),
108
116
  title: "Internal Server Error",
109
117
  detail: "An unexpected error occurred",
110
118
  extensions: options.includeStack ? { stack: error.stack } : void 0
@@ -116,11 +124,26 @@ function problemDetailsHandler(options = {}) {
116
124
  }
117
125
 
118
126
  // src/registry.ts
119
- function createProblemTypeRegistry(definitions) {
127
+ function deriveCode(key) {
128
+ return key.toLowerCase().replace(/_+/g, "-").replace(/^-+|-+$/g, "");
129
+ }
130
+ function createProblemTypeRegistry(definitions, options) {
131
+ const autoCode = options?.autoCode ?? false;
132
+ const resolved = new Map(
133
+ Object.keys(definitions).map((key) => {
134
+ const definition = definitions[key];
135
+ const code = definition.code ?? (autoCode ? deriveCode(key) : void 0);
136
+ return [key, code === void 0 ? definition : { ...definition, code }];
137
+ })
138
+ );
120
139
  return {
121
- create: (key, options) => new ProblemDetailsError({ ...definitions[key], ...options }),
122
- get: (key) => definitions[key],
123
- types: () => Object.keys(definitions)
140
+ create: (key, createOptions) => {
141
+ const { code, ...definition } = resolved.get(key) ?? {};
142
+ const extensions = code !== void 0 ? { code, ...createOptions?.extensions } : createOptions?.extensions;
143
+ return new ProblemDetailsError({ ...definition, ...createOptions, extensions });
144
+ },
145
+ get: (key) => resolved.get(key),
146
+ types: () => [...resolved.keys()]
124
147
  };
125
148
  }
126
149
  export {
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  buildValidationResponse
3
- } from "../chunk-LW7MK5KY.js";
4
- import "../chunk-EL44ATLR.js";
3
+ } from "../chunk-BBJKRRB3.js";
4
+ import "../chunk-VPS467Z5.js";
5
5
  import "../chunk-P4D7EVU3.js";
6
6
 
7
7
  // src/integrations/standard-schema.ts
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  buildValidationResponse
3
- } from "../chunk-LW7MK5KY.js";
4
- import "../chunk-EL44ATLR.js";
3
+ } from "../chunk-BBJKRRB3.js";
4
+ import "../chunk-VPS467Z5.js";
5
5
  import "../chunk-P4D7EVU3.js";
6
6
 
7
7
  // src/integrations/valibot.ts
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  buildValidationResponse
3
- } from "../chunk-LW7MK5KY.js";
4
- import "../chunk-EL44ATLR.js";
3
+ } from "../chunk-BBJKRRB3.js";
4
+ import "../chunk-VPS467Z5.js";
5
5
  import "../chunk-P4D7EVU3.js";
6
6
 
7
7
  // src/integrations/zod.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hono-problem-details",
3
- "version": "0.8.2",
3
+ "version": "0.10.0",
4
4
  "description": "RFC 9457 Problem Details middleware for Hono",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -137,18 +137,18 @@
137
137
  },
138
138
  "devDependencies": {
139
139
  "@biomejs/biome": "^2.4.14",
140
- "@changesets/changelog-github": "0.6.0",
141
- "@changesets/cli": "2.31.0",
142
- "@hono/standard-validator": "0.2.2",
140
+ "@changesets/changelog-github": "0.7.0",
141
+ "@changesets/cli": "2.31.1",
142
+ "@hono/standard-validator": "0.3.0",
143
143
  "@hono/valibot-validator": "^0.6.1",
144
- "@hono/zod-openapi": "1.3.0",
145
- "@hono/zod-validator": "^0.7.6",
144
+ "@hono/zod-openapi": "1.5.1",
145
+ "@hono/zod-validator": "^0.9.0",
146
146
  "@opentelemetry/api": "^1.0.0",
147
147
  "@standard-schema/spec": "1.1.0",
148
148
  "@vitest/coverage-v8": "^4.1.8",
149
149
  "hono": "^4.12.27",
150
- "knip": "6.14.2",
151
- "lefthook": "2.1.6",
150
+ "knip": "6.27.0",
151
+ "lefthook": "2.1.10",
152
152
  "tsup": "^8.0.0",
153
153
  "typescript": "^6.0.3",
154
154
  "valibot": "^1.3.1",