hono-ban 0.2.5 → 0.2.7

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 (50) hide show
  1. package/dist/esm/formatters/index.js +1 -248
  2. package/dist/esm/index.js +1 -585
  3. package/package.json +10 -26
  4. package/dist/cjs/formatters/index.js +0 -280
  5. package/dist/cjs/formatters/index.js.map +0 -16
  6. package/dist/cjs/formatters/rfc7807/index.js +0 -364
  7. package/dist/cjs/formatters/rfc7807/index.js.map +0 -16
  8. package/dist/cjs/index.js +0 -617
  9. package/dist/cjs/index.js.map +0 -23
  10. package/dist/esm/formatters/index.js.map +0 -16
  11. package/dist/esm/formatters/rfc7807/index.js +0 -333
  12. package/dist/esm/formatters/rfc7807/index.js.map +0 -16
  13. package/dist/esm/index.js.map +0 -23
  14. package/src/__tests__/core/convert-error.test.ts +0 -158
  15. package/src/__tests__/core/create-error.test.ts +0 -113
  16. package/src/__tests__/core/format-error.test.ts +0 -162
  17. package/src/__tests__/factories/factories.test.ts +0 -380
  18. package/src/__tests__/formatters/default-formatter.test.ts +0 -117
  19. package/src/__tests__/middleware/README.md +0 -49
  20. package/src/__tests__/middleware/ban-middleware.test.ts.disabled +0 -23
  21. package/src/__tests__/utils/sanitize.test.ts +0 -117
  22. package/src/__tests__/utils/validate.test.ts +0 -35
  23. package/src/constants/index.ts +0 -6
  24. package/src/constants/status-codes.ts +0 -52
  25. package/src/core/convert-error.ts +0 -74
  26. package/src/core/create-error.ts +0 -65
  27. package/src/core/format-error.ts +0 -76
  28. package/src/core/index.ts +0 -8
  29. package/src/factories/client-errors.ts +0 -492
  30. package/src/factories/index.ts +0 -7
  31. package/src/factories/server-errors.ts +0 -230
  32. package/src/formatters/default/index.ts +0 -72
  33. package/src/formatters/index.ts +0 -13
  34. package/src/formatters/interfaces.ts +0 -7
  35. package/src/formatters/rfc7807/formatter.ts +0 -105
  36. package/src/formatters/rfc7807/hooks.ts +0 -73
  37. package/src/formatters/rfc7807/index.ts +0 -20
  38. package/src/formatters/rfc7807/schemas.ts +0 -88
  39. package/src/index.ts +0 -23
  40. package/src/middleware/ban-middleware.ts +0 -77
  41. package/src/middleware/index.ts +0 -6
  42. package/src/types/common.ts +0 -14
  43. package/src/types/error.ts +0 -46
  44. package/src/types/formatter.ts +0 -61
  45. package/src/types/index.ts +0 -11
  46. package/src/types/options.ts +0 -71
  47. package/src/types/rfc7807.ts +0 -93
  48. package/src/utils/index.ts +0 -7
  49. package/src/utils/sanitize.ts +0 -34
  50. package/src/utils/validate.ts +0 -24
package/dist/esm/index.js CHANGED
@@ -1,585 +1 @@
1
- // src/constants/status-codes.ts
2
- var STATUS_CODES = {
3
- 400: "Bad Request",
4
- 401: "Unauthorized",
5
- 402: "Payment Required",
6
- 403: "Forbidden",
7
- 404: "Not Found",
8
- 405: "Method Not Allowed",
9
- 406: "Not Acceptable",
10
- 407: "Proxy Authentication Required",
11
- 408: "Request Timeout",
12
- 409: "Conflict",
13
- 410: "Gone",
14
- 411: "Length Required",
15
- 412: "Precondition Failed",
16
- 413: "Payload Too Large",
17
- 414: "URI Too Long",
18
- 415: "Unsupported Media Type",
19
- 416: "Range Not Satisfiable",
20
- 417: "Expectation Failed",
21
- 418: "I'm a teapot",
22
- 421: "Misdirected Request",
23
- 422: "Unprocessable Entity",
24
- 423: "Locked",
25
- 424: "Failed Dependency",
26
- 425: "Too Early",
27
- 426: "Upgrade Required",
28
- 428: "Precondition Required",
29
- 429: "Too Many Requests",
30
- 431: "Request Header Fields Too Large",
31
- 451: "Unavailable For Legal Reasons",
32
- 500: "Internal Server Error",
33
- 501: "Not Implemented",
34
- 502: "Bad Gateway",
35
- 503: "Service Unavailable",
36
- 504: "Gateway Timeout",
37
- 505: "HTTP Version Not Supported",
38
- 506: "Variant Also Negotiates",
39
- 507: "Insufficient Storage",
40
- 508: "Loop Detected",
41
- 510: "Not Extended",
42
- 511: "Network Authentication Required"
43
- };
44
-
45
- // src/utils/validate.ts
46
- function validateStatusCode(code) {
47
- if (typeof code !== "number" || isNaN(code)) {
48
- return 500;
49
- }
50
- if (code < 400 || code >= 600) {
51
- return 500;
52
- }
53
- return code;
54
- }
55
-
56
- // src/core/create-error.ts
57
- function createError(options) {
58
- const status = validateStatusCode(options.statusCode ?? 500);
59
- const error = {
60
- status,
61
- message: options.message ?? STATUS_CODES[status],
62
- isBan: true
63
- };
64
- if (options.data !== undefined) {
65
- error.data = options.data;
66
- }
67
- if (options.headers) {
68
- error.headers = { ...options.headers };
69
- }
70
- if (options.allow) {
71
- error.allow = Array.isArray(options.allow) ? [...options.allow] : [options.allow];
72
- }
73
- if (options.cause) {
74
- error.cause = options.cause;
75
- if (options.cause instanceof Error) {
76
- error.causeStack = options.cause.stack;
77
- }
78
- }
79
- Error.captureStackTrace(error, createError);
80
- return error;
81
- }
82
-
83
- // src/core/convert-error.ts
84
- function isBanError(err, statusCode) {
85
- return typeof err === "object" && err !== null && "isBan" in err && err.isBan === true && (!statusCode || err.status === statusCode);
86
- }
87
- function convertToBanError(err, options = {}) {
88
- if (isBanError(err)) {
89
- const merged = {
90
- status: options.statusCode ?? err.status,
91
- message: options.message ?? err.message,
92
- isBan: true,
93
- data: options.data !== undefined ? options.data : err.data,
94
- headers: {
95
- ...err.headers,
96
- ...options.headers
97
- },
98
- allow: options.allow ? Array.isArray(options.allow) ? [...options.allow] : [options.allow] : err.allow,
99
- cause: options.cause ?? err.cause,
100
- stack: err.stack
101
- };
102
- return merged;
103
- }
104
- if (err instanceof Error) {
105
- return createError({
106
- ...options,
107
- message: options.message ?? err.message,
108
- cause: err
109
- });
110
- }
111
- return createError({
112
- ...options,
113
- message: options.message ?? (typeof err === "string" ? err : "Unknown error"),
114
- cause: err
115
- });
116
- }
117
-
118
- // src/core/format-error.ts
119
- function formatError(error, formatter, options = {}) {
120
- return formatter.format(error, options.headers, options.sanitize, options.includeStackTrace);
121
- }
122
- function createErrorResponse(error, formatted) {
123
- const headers = new Headers({
124
- "Content-Type": "application/json",
125
- ...error.headers
126
- });
127
- if (error.allow?.length) {
128
- headers.set("Allow", error.allow.join(", "));
129
- }
130
- const isDeveloperError = error.data && typeof error.data === "object" && "isDeveloperError" in error.data && error.data.isDeveloperError === true;
131
- if (isDeveloperError && false) {
132
- }
133
- return new Response(JSON.stringify(formatted), {
134
- status: error.status,
135
- headers
136
- });
137
- }
138
- // src/utils/sanitize.ts
139
- function sanitizeObject(obj, keysToRemove) {
140
- if (!keysToRemove.length) {
141
- return obj;
142
- }
143
- if (Array.isArray(obj)) {
144
- return obj.map((item) => sanitizeObject(item, keysToRemove));
145
- }
146
- if (obj !== null && typeof obj === "object") {
147
- return Object.entries(obj).reduce((acc, [key, value]) => {
148
- if (keysToRemove.includes(key)) {
149
- return acc;
150
- }
151
- acc[key] = sanitizeObject(value, keysToRemove);
152
- return acc;
153
- }, {});
154
- }
155
- return obj;
156
- }
157
-
158
- // src/formatters/default/index.ts
159
- var defaultFormatter = {
160
- contentType: "application/json",
161
- format(error, headers = {}, sanitize = [], includeStackTrace = false) {
162
- const { status, message, data } = error;
163
- const payload = {
164
- statusCode: status,
165
- error: STATUS_CODES[status] || "Unknown Error"
166
- };
167
- if (typeof message === "string") {
168
- payload.message = message;
169
- }
170
- const isDeveloperError = data && typeof data === "object" && "isDeveloperError" in data && data.isDeveloperError === true;
171
- if (includeStackTrace || isDeveloperError) {
172
- if (error.stack) {
173
- payload.stack = error.stack;
174
- }
175
- if (error.causeStack) {
176
- payload.causeStack = error.causeStack;
177
- }
178
- }
179
- if (data !== undefined) {
180
- payload.data = data;
181
- }
182
- const output = {
183
- statusCode: status,
184
- payload: sanitizeObject(payload, sanitize)
185
- };
186
- return output;
187
- }
188
- };
189
-
190
- // src/formatters/rfc7807/schemas.ts
191
- import { z } from "@hono/zod-openapi";
192
- var RFC7807ValidationParamSchema = z.object({
193
- name: z.string().openapi({
194
- example: "username",
195
- description: "The field name that failed validation"
196
- }),
197
- reason: z.string().openapi({
198
- example: "String must contain at least 3 character(s)",
199
- description: "The reason for validation failure"
200
- })
201
- });
202
- var RFC7807ConstraintViolationSchema = z.object({
203
- name: z.string().openapi({
204
- example: "email",
205
- description: "The field name that violated a constraint"
206
- }),
207
- reason: z.string().openapi({
208
- example: "Email already exists",
209
- description: "The reason for the constraint violation"
210
- }),
211
- resource: z.string().openapi({
212
- example: "user",
213
- description: "The resource type that contains the constraint"
214
- }),
215
- constraint: z.string().openapi({
216
- example: "unique",
217
- description: "The type of constraint that was violated"
218
- })
219
- });
220
- var RFC7807ErrorDataSchema = z.object({
221
- "invalid-params": z.array(RFC7807ValidationParamSchema).optional(),
222
- violations: z.array(RFC7807ConstraintViolationSchema).optional()
223
- });
224
- var RFC7807DetailsSchema = z.object({
225
- type: z.string().url().openapi({
226
- example: "https://api.example.com/problems/validation-error",
227
- description: "A URI reference that identifies the problem type"
228
- }),
229
- title: z.string().openapi({
230
- example: "Validation Failed",
231
- description: "A short, human-readable summary of the problem type"
232
- }),
233
- status: z.number().int().min(400).max(599).openapi({
234
- example: 400,
235
- description: "The HTTP status code"
236
- }),
237
- detail: z.string().optional().openapi({
238
- example: "The request contains invalid fields",
239
- description: "A human-readable explanation specific to this occurrence of the problem"
240
- }),
241
- instance: z.string().url().optional().openapi({
242
- example: "urn:uuid:6b56944d-5e89-4b4d-9ca7-c1be3d1f0e3f",
243
- description: "A URI reference that identifies the specific occurrence of the problem"
244
- }),
245
- timestamp: z.string().datetime().optional().openapi({
246
- example: "2025-02-26T12:34:56.789Z",
247
- description: "When the error occurred"
248
- })
249
- }).merge(RFC7807ErrorDataSchema);
250
-
251
- // src/formatters/rfc7807/formatter.ts
252
- function createRFC7807Formatter(options = {}) {
253
- const baseUrl = options.baseUrl || "https://api.example.com/problems";
254
- return {
255
- contentType: "application/problem+json",
256
- format(error) {
257
- const base = {
258
- type: `${baseUrl}/${error.status}`,
259
- title: STATUS_CODES[error.status] || "Unknown Error",
260
- status: error.status,
261
- detail: error.message,
262
- instance: `urn:uuid:${crypto.randomUUID()}`,
263
- timestamp: new Date().toISOString()
264
- };
265
- if (error.data?.["invalid-params"]) {
266
- return RFC7807DetailsSchema.parse({
267
- ...base,
268
- "invalid-params": error.data["invalid-params"]
269
- });
270
- }
271
- if (error.data?.violations) {
272
- return RFC7807DetailsSchema.parse({
273
- ...base,
274
- violations: error.data.violations
275
- });
276
- }
277
- return RFC7807DetailsSchema.parse(base);
278
- }
279
- };
280
- }
281
- function createRFC7807ValidationError(params) {
282
- return {
283
- "invalid-params": RFC7807ValidationParamSchema.array().parse(params)
284
- };
285
- }
286
- function createRFC7807ZodValidationError(error) {
287
- return {
288
- "invalid-params": RFC7807ValidationParamSchema.array().parse(error.errors.map((e) => ({
289
- name: e.path.join("."),
290
- reason: e.message
291
- })))
292
- };
293
- }
294
- function createRFC7807ConstraintViolation(name, reason, resource, constraint = "unique") {
295
- return {
296
- violations: RFC7807ConstraintViolationSchema.array().parse([
297
- {
298
- name,
299
- reason,
300
- resource,
301
- constraint
302
- }
303
- ])
304
- };
305
- }
306
- // src/formatters/rfc7807/hooks.ts
307
- import { ZodError } from "zod";
308
-
309
- // src/factories/client-errors.ts
310
- function createErrorWithStatus(statusCode, messageOrOptions, options) {
311
- if (typeof messageOrOptions === "string") {
312
- return createError({
313
- ...options,
314
- statusCode,
315
- message: messageOrOptions
316
- });
317
- }
318
- return createError({ ...messageOrOptions, ...options, statusCode });
319
- }
320
- function badRequest(messageOrOptions, options) {
321
- return createErrorWithStatus(400, messageOrOptions, options);
322
- }
323
- function unauthorized(messageOrOptions, options) {
324
- return createErrorWithStatus(401, messageOrOptions, options);
325
- }
326
- function paymentRequired(messageOrOptions, options) {
327
- return createErrorWithStatus(402, messageOrOptions, options);
328
- }
329
- function forbidden(messageOrOptions, options) {
330
- return createErrorWithStatus(403, messageOrOptions, options);
331
- }
332
- function notFound(messageOrOptions, options) {
333
- return createErrorWithStatus(404, messageOrOptions, options);
334
- }
335
- function methodNotAllowed(messageOrOptions, options) {
336
- return createErrorWithStatus(405, messageOrOptions, options);
337
- }
338
- function notAcceptable(messageOrOptions, options) {
339
- return createErrorWithStatus(406, messageOrOptions, options);
340
- }
341
- function proxyAuthRequired(messageOrOptions, options) {
342
- return createErrorWithStatus(407, messageOrOptions, options);
343
- }
344
- function clientTimeout(messageOrOptions, options) {
345
- return createErrorWithStatus(408, messageOrOptions, options);
346
- }
347
- function conflict(messageOrOptions, options) {
348
- return createErrorWithStatus(409, messageOrOptions, options);
349
- }
350
- function resourceGone(messageOrOptions, options) {
351
- return createErrorWithStatus(410, messageOrOptions, options);
352
- }
353
- function lengthRequired(messageOrOptions, options) {
354
- return createErrorWithStatus(411, messageOrOptions, options);
355
- }
356
- function preconditionFailed(messageOrOptions, options) {
357
- return createErrorWithStatus(412, messageOrOptions, options);
358
- }
359
- function entityTooLarge(messageOrOptions, options) {
360
- return createErrorWithStatus(413, messageOrOptions, options);
361
- }
362
- function uriTooLong(messageOrOptions, options) {
363
- return createErrorWithStatus(414, messageOrOptions, options);
364
- }
365
- function unsupportedMediaType(messageOrOptions, options) {
366
- return createErrorWithStatus(415, messageOrOptions, options);
367
- }
368
- function rangeNotSatisfiable(messageOrOptions, options) {
369
- return createErrorWithStatus(416, messageOrOptions, options);
370
- }
371
- function expectationFailed(messageOrOptions, options) {
372
- return createErrorWithStatus(417, messageOrOptions, options);
373
- }
374
- function teapot(messageOrOptions, options) {
375
- return createErrorWithStatus(418, messageOrOptions, options);
376
- }
377
- function misdirectedRequest(messageOrOptions, options) {
378
- return createErrorWithStatus(421, messageOrOptions, options);
379
- }
380
- function badData(messageOrOptions, options) {
381
- return createErrorWithStatus(422, messageOrOptions, options);
382
- }
383
- function locked(messageOrOptions, options) {
384
- return createErrorWithStatus(423, messageOrOptions, options);
385
- }
386
- function failedDependency(messageOrOptions, options) {
387
- return createErrorWithStatus(424, messageOrOptions, options);
388
- }
389
- function tooEarly(messageOrOptions, options) {
390
- return createErrorWithStatus(425, messageOrOptions, options);
391
- }
392
- function upgradeRequired(messageOrOptions, options) {
393
- return createErrorWithStatus(426, messageOrOptions, options);
394
- }
395
- function preconditionRequired(messageOrOptions, options) {
396
- return createErrorWithStatus(428, messageOrOptions, options);
397
- }
398
- function tooManyRequests(messageOrOptions, options) {
399
- return createErrorWithStatus(429, messageOrOptions, options);
400
- }
401
- function headerFieldsTooLarge(messageOrOptions, options) {
402
- return createErrorWithStatus(431, messageOrOptions, options);
403
- }
404
- function illegal(messageOrOptions, options) {
405
- return createErrorWithStatus(451, messageOrOptions, options);
406
- }
407
-
408
- // src/factories/server-errors.ts
409
- function createErrorWithStatus2(statusCode, messageOrOptions, options) {
410
- if (typeof messageOrOptions === "string") {
411
- return createError({
412
- ...options,
413
- statusCode,
414
- message: messageOrOptions
415
- });
416
- }
417
- return createError({ ...messageOrOptions, ...options, statusCode });
418
- }
419
- function internal(messageOrOptions, options) {
420
- return createErrorWithStatus2(500, messageOrOptions, options);
421
- }
422
- function notImplemented(messageOrOptions, options) {
423
- return createErrorWithStatus2(501, messageOrOptions, options);
424
- }
425
- function badGateway(messageOrOptions, options) {
426
- return createErrorWithStatus2(502, messageOrOptions, options);
427
- }
428
- function serverUnavailable(messageOrOptions, options) {
429
- return createErrorWithStatus2(503, messageOrOptions, options);
430
- }
431
- function gatewayTimeout(messageOrOptions, options) {
432
- return createErrorWithStatus2(504, messageOrOptions, options);
433
- }
434
- function httpVersionNotSupported(messageOrOptions, options) {
435
- return createErrorWithStatus2(505, messageOrOptions, options);
436
- }
437
- function variantAlsoNegotiates(messageOrOptions, options) {
438
- return createErrorWithStatus2(506, messageOrOptions, options);
439
- }
440
- function insufficientStorage(messageOrOptions, options) {
441
- return createErrorWithStatus2(507, messageOrOptions, options);
442
- }
443
- function loopDetected(messageOrOptions, options) {
444
- return createErrorWithStatus2(508, messageOrOptions, options);
445
- }
446
- function notExtended(messageOrOptions, options) {
447
- return createErrorWithStatus2(510, messageOrOptions, options);
448
- }
449
- function networkAuthRequired(messageOrOptions, options) {
450
- return createErrorWithStatus2(511, messageOrOptions, options);
451
- }
452
- function badImplementation(messageOrOptions, options) {
453
- const mergedOptions = typeof messageOrOptions === "string" ? { ...options, message: messageOrOptions } : { ...messageOrOptions, ...options };
454
- const mergedData = {
455
- isDeveloperError: true,
456
- ...mergedOptions.data || {}
457
- };
458
- return createError({
459
- ...mergedOptions,
460
- statusCode: 500,
461
- data: mergedData
462
- });
463
- }
464
-
465
- // src/formatters/rfc7807/hooks.ts
466
- function createRFC7807Hook(options) {
467
- return (result, c) => {
468
- if (!result.success && "error" in result && result.error instanceof ZodError) {
469
- const validationData = createRFC7807ZodValidationError(result.error);
470
- throw badRequest({
471
- message: options?.message || "Validation Error",
472
- data: validationData,
473
- formatter: options?.formatter,
474
- headers: options?.headers,
475
- sanitize: options?.sanitize,
476
- includeStackTrace: options?.includeStackTrace
477
- });
478
- }
479
- };
480
- }
481
- var rfc7807Hook = createRFC7807Hook();
482
- // src/middleware/ban-middleware.ts
483
- var DEFAULT_OPTIONS = {
484
- formatter: defaultFormatter,
485
- sanitize: [],
486
- includeStackTrace: false,
487
- headers: {}
488
- };
489
- function ban(options = {}) {
490
- const resolvedOptions = {
491
- ...DEFAULT_OPTIONS,
492
- ...options,
493
- formatter: options.formatter ? options.formatter : DEFAULT_OPTIONS.formatter,
494
- headers: {
495
- ...DEFAULT_OPTIONS.headers,
496
- ...options.headers
497
- },
498
- sanitize: [...DEFAULT_OPTIONS.sanitize, ...options.sanitize || []]
499
- };
500
- return async (_, next) => {
501
- try {
502
- await next();
503
- } catch (err) {
504
- const formatter = resolvedOptions.formatter;
505
- const error = convertToBanError(err, {
506
- formatter,
507
- headers: resolvedOptions.headers,
508
- sanitize: resolvedOptions.sanitize,
509
- includeStackTrace: resolvedOptions.includeStackTrace
510
- });
511
- const formatted = formatError(error, formatter, {
512
- headers: resolvedOptions.headers,
513
- sanitize: resolvedOptions.sanitize,
514
- includeStackTrace: resolvedOptions.includeStackTrace
515
- });
516
- return createErrorResponse(error, formatted);
517
- }
518
- };
519
- }
520
- // src/index.ts
521
- var src_default = ban;
522
- export {
523
- variantAlsoNegotiates,
524
- uriTooLong,
525
- upgradeRequired,
526
- unsupportedMediaType,
527
- unauthorized,
528
- tooManyRequests,
529
- tooEarly,
530
- teapot,
531
- serverUnavailable,
532
- rfc7807Hook,
533
- resourceGone,
534
- rangeNotSatisfiable,
535
- proxyAuthRequired,
536
- preconditionRequired,
537
- preconditionFailed,
538
- paymentRequired,
539
- notImplemented,
540
- notFound,
541
- notExtended,
542
- notAcceptable,
543
- networkAuthRequired,
544
- misdirectedRequest,
545
- methodNotAllowed,
546
- loopDetected,
547
- locked,
548
- lengthRequired,
549
- isBanError,
550
- internal,
551
- insufficientStorage,
552
- illegal,
553
- httpVersionNotSupported,
554
- headerFieldsTooLarge,
555
- gatewayTimeout,
556
- formatError,
557
- forbidden,
558
- failedDependency,
559
- expectationFailed,
560
- entityTooLarge,
561
- defaultFormatter,
562
- src_default as default,
563
- createRFC7807ZodValidationError,
564
- createRFC7807ValidationError,
565
- createRFC7807Hook,
566
- createRFC7807Formatter,
567
- createRFC7807ConstraintViolation,
568
- createErrorResponse,
569
- createError,
570
- convertToBanError,
571
- conflict,
572
- clientTimeout,
573
- badRequest,
574
- badImplementation,
575
- badGateway,
576
- badData,
577
- STATUS_CODES,
578
- RFC7807ValidationParamSchema,
579
- RFC7807ErrorDataSchema,
580
- RFC7807DetailsSchema,
581
- RFC7807ConstraintViolationSchema
582
- };
583
-
584
- //# debugId=A1FE8EEEB28CCDAC64756E2164756E21
585
- //# sourceMappingURL=index.js.map
1
+ var V={400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};function N(x){if(typeof x!=="number"||isNaN(x))return 500;if(x<400||x>=600)return 500;return x}function J(x){let f=N(x.statusCode??500),K={status:f,message:x.message??V[f],isBan:!0};if(x.data!==void 0)K.data=x.data;if(x.headers)K.headers={...x.headers};if(x.allow)K.allow=Array.isArray(x.allow)?[...x.allow]:[x.allow];if(x.cause){if(K.cause=x.cause,x.cause instanceof Error)K.causeStack=x.cause.stack}return Error.captureStackTrace(K,J),K}function D(x,f){return typeof x==="object"&&x!==null&&"isBan"in x&&x.isBan===!0&&(!f||x.status===f)}function L(x,f={}){if(D(x))return{status:f.statusCode??x.status,message:f.message??x.message,isBan:!0,data:f.data!==void 0?f.data:x.data,headers:{...x.headers,...f.headers},allow:f.allow?Array.isArray(f.allow)?[...f.allow]:[f.allow]:x.allow,cause:f.cause??x.cause,stack:x.stack};if(x instanceof Error)return J({...f,message:f.message??x.message,cause:x});return J({...f,message:f.message??(typeof x==="string"?x:"Unknown error"),cause:x})}function R(x,f,K={}){return f.format(x,K.headers,K.sanitize,K.includeStackTrace)}function _(x,f){let K=new Headers({"Content-Type":"application/json",...x.headers});if(x.allow?.length)K.set("Allow",x.allow.join(", "));let j=x.data&&typeof x.data==="object"&&"isDeveloperError"in x.data&&x.data.isDeveloperError===!0;return new Response(JSON.stringify(f),{status:x.status,headers:K})}function b(x,f){if(!f.length)return x;if(Array.isArray(x))return x.map((K)=>b(K,f));if(x!==null&&typeof x==="object")return Object.entries(x).reduce((K,[j,Y])=>{if(f.includes(j))return K;return K[j]=b(Y,f),K},{});return x}var I={contentType:"application/json",format(x,f={},K=[],j=!1){let{status:Y,message:Z,data:X}=x,$={statusCode:Y,error:V[Y]||"Unknown Error"};if(typeof Z==="string")$.message=Z;let U=X&&typeof X==="object"&&"isDeveloperError"in X&&X.isDeveloperError===!0;if(j||U){if(x.stack)$.stack=x.stack;if(x.causeStack)$.causeStack=x.causeStack}if(X!==void 0)$.data=X;return{statusCode:Y,payload:b($,K)}}};import{z as G}from"@hono/zod-openapi";var q=G.object({name:G.string().openapi({example:"username",description:"The field name that failed validation"}),reason:G.string().openapi({example:"String must contain at least 3 character(s)",description:"The reason for validation failure"})}),w=G.object({name:G.string().openapi({example:"email",description:"The field name that violated a constraint"}),reason:G.string().openapi({example:"Email already exists",description:"The reason for the constraint violation"}),resource:G.string().openapi({example:"user",description:"The resource type that contains the constraint"}),constraint:G.string().openapi({example:"unique",description:"The type of constraint that was violated"})}),A=G.object({"invalid-params":G.array(q).optional(),violations:G.array(w).optional()}),H=G.object({type:G.string().url().openapi({example:"https://api.example.com/problems/validation-error",description:"A URI reference that identifies the problem type"}),title:G.string().openapi({example:"Validation Failed",description:"A short, human-readable summary of the problem type"}),status:G.number().int().min(400).max(599).openapi({example:400,description:"The HTTP status code"}),detail:G.string().optional().openapi({example:"The request contains invalid fields",description:"A human-readable explanation specific to this occurrence of the problem"}),instance:G.string().url().optional().openapi({example:"urn:uuid:6b56944d-5e89-4b4d-9ca7-c1be3d1f0e3f",description:"A URI reference that identifies the specific occurrence of the problem"}),timestamp:G.string().datetime().optional().openapi({example:"2025-02-26T12:34:56.789Z",description:"When the error occurred"})}).merge(A);function z(x={}){let f=x.baseUrl||"https://api.example.com/problems";return{contentType:"application/problem+json",format(K){let j={type:`${f}/${K.status}`,title:V[K.status]||"Unknown Error",status:K.status,detail:K.message,instance:`urn:uuid:${crypto.randomUUID()}`,timestamp:new Date().toISOString()};if(K.data?.["invalid-params"])return H.parse({...j,"invalid-params":K.data["invalid-params"]});if(K.data?.violations)return H.parse({...j,violations:K.data.violations});return H.parse(j)}}}function v(x){return{"invalid-params":q.array().parse(x)}}function y(x){return{"invalid-params":q.array().parse(x.errors.map((f)=>({name:f.path.join("."),reason:f.message})))}}function T(x,f,K,j="unique"){return{violations:w.array().parse([{name:x,reason:f,resource:K,constraint:j}])}}import{ZodError as C}from"zod";function M(x,f,K){if(typeof f==="string")return J({...K,statusCode:x,message:f});return J({...f,...K,statusCode:x})}function F(x,f){return M(400,x,f)}function x7(x,f){return M(401,x,f)}function f7(x,f){return M(402,x,f)}function K7(x,f){return M(403,x,f)}function M7(x,f){return M(404,x,f)}function j7(x,f){return M(405,x,f)}function G7(x,f){return M(406,x,f)}function J7(x,f){return M(407,x,f)}function Q7(x,f){return M(408,x,f)}function X7(x,f){return M(409,x,f)}function Y7(x,f){return M(410,x,f)}function $7(x,f){return M(411,x,f)}function V7(x,f){return M(412,x,f)}function Z7(x,f){return M(413,x,f)}function q7(x,f){return M(414,x,f)}function H7(x,f){return M(415,x,f)}function b7(x,f){return M(416,x,f)}function w7(x,f){return M(417,x,f)}function k7(x,f){return M(418,x,f)}function y7(x,f){return M(421,x,f)}function B7(x,f){return M(422,x,f)}function N7(x,f){return M(423,x,f)}function L7(x,f){return M(424,x,f)}function R7(x,f){return M(425,x,f)}function _7(x,f){return M(426,x,f)}function I7(x,f){return M(428,x,f)}function A7(x,f){return M(429,x,f)}function F7(x,f){return M(431,x,f)}function P7(x,f){return M(451,x,f)}function Q(x,f,K){if(typeof f==="string")return J({...K,statusCode:x,message:f});return J({...f,...K,statusCode:x})}function z7(x,f){return Q(500,x,f)}function v7(x,f){return Q(501,x,f)}function T7(x,f){return Q(502,x,f)}function C7(x,f){return Q(503,x,f)}function l7(x,f){return Q(504,x,f)}function W7(x,f){return Q(505,x,f)}function h7(x,f){return Q(506,x,f)}function S7(x,f){return Q(507,x,f)}function E7(x,f){return Q(508,x,f)}function u7(x,f){return Q(510,x,f)}function d7(x,f){return Q(511,x,f)}function c7(x,f){let K=typeof x==="string"?{...f,message:x}:{...x,...f},j={isDeveloperError:!0,...K.data||{}};return J({...K,statusCode:500,data:j})}function P(x){return(f,K)=>{if(!f.success&&"error"in f&&f.error instanceof C){let j=y(f.error);throw F({message:x?.message||"Validation Error",data:j,formatter:x?.formatter,headers:x?.headers,sanitize:x?.sanitize,includeStackTrace:x?.includeStackTrace})}}}var l=P();var k={formatter:I,sanitize:[],includeStackTrace:!1,headers:{}};function B(x={}){let f={...k,...x,formatter:x.formatter?x.formatter:k.formatter,headers:{...k.headers,...x.headers},sanitize:[...k.sanitize,...x.sanitize||[]]};return async(K,j)=>{try{await j()}catch(Y){let Z=f.formatter,X=L(Y,{formatter:Z,headers:f.headers,sanitize:f.sanitize,includeStackTrace:f.includeStackTrace}),$=R(X,Z,{headers:f.headers,sanitize:f.sanitize,includeStackTrace:f.includeStackTrace});return _(X,$)}}}var Yx=B;export{h7 as variantAlsoNegotiates,q7 as uriTooLong,_7 as upgradeRequired,H7 as unsupportedMediaType,x7 as unauthorized,A7 as tooManyRequests,R7 as tooEarly,k7 as teapot,C7 as serverUnavailable,l as rfc7807Hook,Y7 as resourceGone,b7 as rangeNotSatisfiable,J7 as proxyAuthRequired,I7 as preconditionRequired,V7 as preconditionFailed,f7 as paymentRequired,v7 as notImplemented,M7 as notFound,u7 as notExtended,G7 as notAcceptable,d7 as networkAuthRequired,y7 as misdirectedRequest,j7 as methodNotAllowed,E7 as loopDetected,N7 as locked,$7 as lengthRequired,D as isBanError,z7 as internal,S7 as insufficientStorage,P7 as illegal,W7 as httpVersionNotSupported,F7 as headerFieldsTooLarge,l7 as gatewayTimeout,R as formatError,K7 as forbidden,L7 as failedDependency,w7 as expectationFailed,Z7 as entityTooLarge,I as defaultFormatter,Yx as default,y as createRFC7807ZodValidationError,v as createRFC7807ValidationError,P as createRFC7807Hook,z as createRFC7807Formatter,T as createRFC7807ConstraintViolation,_ as createErrorResponse,J as createError,L as convertToBanError,X7 as conflict,Q7 as clientTimeout,F as badRequest,c7 as badImplementation,T7 as badGateway,B7 as badData,V as STATUS_CODES,q as RFC7807ValidationParamSchema,A as RFC7807ErrorDataSchema,H as RFC7807DetailsSchema,w as RFC7807ConstraintViolationSchema};
package/package.json CHANGED
@@ -1,47 +1,31 @@
1
1
  {
2
2
  "name": "hono-ban",
3
- "version": "0.2.5",
3
+ "version": "0.2.7",
4
4
  "description": "HTTP-friendly error objects for Hono, inspired by Boom",
5
5
  "type": "module",
6
- "main": "dist/cjs/index.js",
7
- "module": "dist/esm/index.js",
6
+ "main": "dist/esm/index.js",
8
7
  "types": "dist/types/index.d.ts",
9
8
  "files": [
10
9
  "dist/*",
11
- "src",
12
- "LICENSE.md",
13
- "README.md"
10
+ "LICENSE.md"
14
11
  ],
15
12
  "exports": {
16
13
  ".": {
17
- "import": {
18
- "types": "./dist/types/index.d.ts",
19
- "default": "./dist/esm/index.js"
20
- },
21
- "require": {
22
- "types": "./dist/types/index.d.ts",
23
- "default": "./dist/cjs/index.js"
24
- }
14
+ "types": "./dist/types/index.d.ts",
15
+ "default": "./dist/esm/index.js"
25
16
  },
26
17
  "./formatters/rfc7807": {
27
- "import": {
28
- "types": "./dist/types/formatters/rfc7807/index.d.ts",
29
- "default": "./dist/esm/formatters/rfc7807/index.js"
30
- },
31
- "require": {
32
- "types": "./dist/types/formatters/rfc7807/index.d.ts",
33
- "default": "./dist/cjs/formatters/rfc7807/index.js"
34
- }
18
+ "types": "./dist/types/formatters/rfc7807/index.d.ts",
19
+ "default": "./dist/esm/formatters/rfc7807/index.js"
35
20
  }
36
21
  },
37
22
  "sideEffects": false,
38
23
  "scripts": {
39
- "build": "bun run build:esm && bun run build:cjs && bun run build:declaration",
40
- "build:esm": "bun build --target=node --format=esm --packages=external --outdir=dist/esm --sourcemap=linked ./src/index.ts && bun build --target=node --format=esm --packages=external --outdir=dist/esm/formatters --sourcemap=linked ./src/formatters/rfc7807/index.ts",
41
- "build:cjs": "bun build --target=node --format=cjs --packages=external --outdir=dist/cjs --sourcemap=linked ./src/index.ts && bun build --target=node --format=cjs --packages=external --outdir=dist/cjs/formatters --sourcemap=linked ./src/formatters/rfc7807/index.ts",
24
+ "build": "bun run build:esm && bun run build:declaration",
25
+ "build:esm": "bun build --target=node --format=esm --packages=external --outdir=dist/esm --minify ./src/index.ts && bun build --target=node --format=esm --packages=external --outdir=dist/esm/formatters --minify ./src/formatters/rfc7807/index.ts",
42
26
  "build:declaration": "tsc --emitDeclarationOnly --project tsconfig.types.json",
43
27
  "postbuild": "rimraf tsconfig.types.tsbuildinfo",
44
- "dev": "bun build --target=node --packages=external --outdir=dist --watch ./src/index.ts",
28
+ "dev": "bun build --target=node --format=esm --packages=external --outdir=dist/esm --watch ./src/index.ts",
45
29
  "test": "bun test",
46
30
  "test:watch": "bun test --watch",
47
31
  "test:coverage": "bun test --coverage",