├── .github └── workflows │ ├── ci.yml │ └── release.yml ├── .gitignore ├── .npmrc ├── .vscode └── settings.json ├── LICENSE ├── README.md ├── build.config.ts ├── eslint.config.js ├── package.json ├── pnpm-lock.yaml ├── pnpm-workspace.yaml ├── scripts ├── post-build.ts └── update-http-statuses.ts ├── src ├── http-status-codes.ts ├── http-status-phrases.ts ├── index.ts ├── middlewares │ ├── index.ts │ ├── not-found.ts │ ├── on-error.test.ts │ ├── on-error.ts │ └── serve-emoji-favicon.ts └── openapi │ ├── default-hook.ts │ ├── helpers │ ├── index.ts │ ├── json-content-one-of.test.ts │ ├── json-content-one-of.ts │ ├── json-content-required.ts │ ├── json-content.ts │ ├── one-of.ts │ └── types.ts │ ├── index.ts │ └── schemas │ ├── create-error-schema.ts │ ├── create-message-object.ts │ ├── get-params-schema.ts │ ├── id-params.ts │ ├── id-uuid-params.ts │ ├── index.ts │ ├── slug-params.test.ts │ └── slug-params.ts ├── test └── index.test.ts └── tsconfig.json /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | pull_request: 9 | branches: 10 | - main 11 | 12 | jobs: 13 | lint: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v4 17 | - uses: pnpm/action-setup@v4 18 | with: 19 | run_install: false 20 | - uses: actions/setup-node@v4 21 | with: 22 | node-version: lts/* 23 | cache: pnpm 24 | 25 | - run: pnpm i -g @antfu/ni 26 | - run: nci 27 | - run: nr lint 28 | - run: nr typecheck 29 | 30 | test: 31 | runs-on: ${{ matrix.os }} 32 | 33 | strategy: 34 | matrix: 35 | node: [lts/*] 36 | os: [ubuntu-latest, macos-latest] 37 | fail-fast: false 38 | 39 | steps: 40 | - uses: actions/checkout@v4 41 | - uses: pnpm/action-setup@v4 42 | with: 43 | run_install: false 44 | - name: Set node ${{ matrix.node }} 45 | uses: actions/setup-node@v4 46 | with: 47 | node-version: ${{ matrix.node }} 48 | cache: pnpm 49 | 50 | - run: pnpm i -g @antfu/ni 51 | - run: nci 52 | - run: nr build 53 | - run: nr test 54 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | permissions: 4 | id-token: write 5 | contents: write 6 | 7 | on: 8 | push: 9 | tags: 10 | - "v*" 11 | 12 | jobs: 13 | release: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v4 17 | with: 18 | fetch-depth: 0 19 | - uses: pnpm/action-setup@v4 20 | - uses: actions/setup-node@v4 21 | with: 22 | node-version: lts/* 23 | registry-url: https://registry.npmjs.org/ 24 | 25 | - run: pnpm dlx changelogithub 26 | env: 27 | GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} 28 | 29 | # # Uncomment the following lines to publish to npm on CI 30 | # 31 | # - run: pnpm install 32 | # - run: pnpm publish -r --access public 33 | # env: 34 | # NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}} 35 | # NPM_CONFIG_PROVENANCE: true 36 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .cache 2 | .DS_Store 3 | .idea 4 | *.log 5 | *.tgz 6 | coverage 7 | dist 8 | lib-cov 9 | logs 10 | node_modules 11 | temp 12 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | ignore-workspace-root-check=true 2 | shell-emulator=true 3 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | // Disable the default formatter, use eslint instead 3 | "prettier.enable": false, 4 | "editor.formatOnSave": false, 5 | 6 | // Auto fix 7 | "editor.codeActionsOnSave": { 8 | "source.fixAll.eslint": "explicit", 9 | "source.organizeImports": "never" 10 | }, 11 | 12 | // Silent the stylistic rules in you IDE, but still auto fix them 13 | "eslint.rules.customizations": [ 14 | { "rule": "style/*", "severity": "off" }, 15 | { "rule": "*-indent", "severity": "off" }, 16 | { "rule": "*-spacing", "severity": "off" }, 17 | { "rule": "*-spaces", "severity": "off" }, 18 | { "rule": "*-order", "severity": "off" }, 19 | { "rule": "*-dangle", "severity": "off" }, 20 | { "rule": "*-newline", "severity": "off" }, 21 | { "rule": "*quotes", "severity": "off" }, 22 | { "rule": "*semi", "severity": "off" } 23 | ], 24 | 25 | // Enable eslint for all supported languages 26 | "eslint.validate": [ 27 | "javascript", 28 | "javascriptreact", 29 | "typescript", 30 | "typescriptreact", 31 | "vue", 32 | "html", 33 | "markdown", 34 | "json", 35 | "jsonc", 36 | "yaml" 37 | ] 38 | } 39 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 w3cj 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # stoker 2 | 3 | [![npm version][npm-version-src]][npm-version-href] 4 | [![npm downloads][npm-downloads-src]][npm-downloads-href] 5 | [![bundle][bundle-src]][bundle-href] 6 | [![JSDocs][jsdocs-src]][jsdocs-href] 7 | [![License][license-src]][license-href] 8 | 9 | _stoke the flame 🤙🔥_ 10 | 11 | Utilities for [hono](https://www.npmjs.com/package/hono) and [@hono/zod-openapi](https://www.npmjs.com/package/@hono/zod-openapi). 12 | 13 | To see real world usage of these utilities, checkout the [hono-open-api-starter routes example](https://github.com/w3cj/hono-open-api-starter/blob/main/src/routes/tasks/tasks.routes.ts) 14 | 15 | - [stoker](#stoker) 16 | - [Utilities](#utilities) 17 | - [stoker/http-status-codes](#stokerhttp-status-codes) 18 | - [Example Usage](#example-usage) 19 | - [stoker/http-status-phrases](#stokerhttp-status-phrases) 20 | - [Example Usage](#example-usage-1) 21 | - [Middlewares](#middlewares) 22 | - [stoker/middlewares/not-found](#stokermiddlewaresnot-found) 23 | - [Example Usage](#example-usage-2) 24 | - [stoker/middlewares/on-error](#stokermiddlewareson-error) 25 | - [Example Usage](#example-usage-3) 26 | - [stoker/middlewares/serve-emoji-favicon](#stokermiddlewaresserve-emoji-favicon) 27 | - [Example Usage](#example-usage-4) 28 | - [Open API](#open-api) 29 | - [Default Hook](#default-hook) 30 | - [Example Usage](#example-usage-5) 31 | - [Helpers](#helpers) 32 | - [stoker/openapi/helpers/json-content](#stokeropenapihelpersjson-content) 33 | - [Example Usage](#example-usage-6) 34 | - [stoker/openapi/helpers/json-content-required](#stokeropenapihelpersjson-content-required) 35 | - [Example Usage](#example-usage-7) 36 | - [stoker/openapi/helpers/json-content-one-of](#stokeropenapihelpersjson-content-one-of) 37 | - [Example Usage](#example-usage-8) 38 | - [stoker/openapi/helpers/one-of](#stokeropenapihelpersone-of) 39 | - [Schemas](#schemas) 40 | - [stoker/openapi/schemas/id-params](#stokeropenapischemasid-params) 41 | - [Example Usage](#example-usage-9) 42 | - [stoker/openapi/schemas/slug-params](#stokeropenapischemasslug-params) 43 | - [Example Usage](#example-usage-10) 44 | - [stoker/openapi/schemas/id-uuid-params](#stokeropenapischemasid-uuid-params) 45 | - [Example Usage](#example-usage-11) 46 | - [stoker/openapi/schemas/get-params-schema](#stokeropenapischemasget-params-schema) 47 | - [Example Usage](#example-usage-12) 48 | - [stoker/openapi/schemas/create-message-object](#stokeropenapischemascreate-message-object) 49 | - [Example Usage](#example-usage-13) 50 | - [stoker/openapi/schemas/create-error-schema](#stokeropenapischemascreate-error-schema) 51 | - [Example Usage](#example-usage-14) 52 | - [Credits](#credits) 53 | 54 | ## Utilities 55 | 56 | ### stoker/http-status-codes 57 | 58 | HTTP status code constants. Provides individual typed / documented exports. Use anywhere you need a status code instead of hard coding raw numbers. 59 | 60 | > Sourced from [http-status-codes](https://www.npmjs.com/package/http-status-codes) | RFC1945 (HTTP/1.0), RFC2616 (HTTP/1.1), RFC2518 (WebDAV), RFC6585 (Additional HTTP Status Codes), and RFC7538 (Permanent Redirect). 61 | 62 | > Why not use the `http-status-codes` package directly? `http-status-codes` exports enums which do not work well with the `@hono/zod-openapi` type system and the built in `StatusCode` type from `hono/utils/http-status`. 63 | 64 | #### Example Usage 65 | 66 | ```ts 67 | import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi"; 68 | 69 | import * as HttpStatusCodes from "stoker/http-status-codes"; 70 | 71 | const app = new OpenAPIHono(); 72 | 73 | app.notFound((c) => { 74 | return c.json({ 75 | message: `Not Found - ${c.req.path}`, 76 | }, HttpStatusCodes.NOT_FOUND); 77 | }); 78 | 79 | app.onError((err, c) => { 80 | return c.json( 81 | { 82 | message: err.message, 83 | }, 84 | HttpStatusCodes.INTERNAL_SERVER_ERROR, 85 | ); 86 | }); 87 | 88 | app.openapi( 89 | createRoute({ 90 | path: "/", 91 | tags: ["Index"], 92 | description: "Index route", 93 | method: "get", 94 | responses: { 95 | [HttpStatusCodes.OK]: { 96 | content: { 97 | "application/json": { 98 | schema: z.object({ 99 | message: z.string(), 100 | }), 101 | }, 102 | }, 103 | description: "Index route", 104 | }, 105 | }, 106 | }), 107 | (c) => { 108 | return c.json({ message: "Hello World" }, HttpStatusCodes.OK); 109 | }, 110 | ); 111 | 112 | export default app; 113 | ``` 114 | 115 | ### stoker/http-status-phrases 116 | 117 | HTTP status phrase constants. 118 | 119 | #### Example Usage 120 | 121 | ```ts 122 | import * as HttpStatusPhrases from "stoker/http-status-phrases"; 123 | 124 | console.log(HttpStatusPhrases.NOT_FOUND); // Not Found 125 | ``` 126 | 127 | ## Middlewares 128 | 129 | ### stoker/middlewares/not-found 130 | 131 | A default 404 handler. 132 | 133 | - Responds with JSON object 134 | - Message property includes not found path 135 | - Sets status code to 404 136 | 137 | #### Example Usage 138 | 139 | ```ts 140 | import { Hono } from "hono"; 141 | 142 | import notFound from "stoker/middlewares/not-found"; 143 | 144 | const app = new Hono(); 145 | 146 | app.notFound(notFound); 147 | 148 | export default app; 149 | ``` 150 | 151 | ### stoker/middlewares/on-error 152 | 153 | A default error handler. 154 | 155 | - Responds with JSON object 156 | - Message property includes error message 157 | - Stack trace included when NODE_ENV !== "production" 158 | - Sets status code to existing status code if already set OR 500 159 | 160 | #### Example Usage 161 | 162 | ```ts 163 | import { Hono } from "hono"; 164 | 165 | import onError from "stoker/middlewares/on-error"; 166 | 167 | const app = new Hono(); 168 | 169 | app.onError(onError); 170 | 171 | export default app; 172 | ``` 173 | 174 | ### stoker/middlewares/serve-emoji-favicon 175 | 176 | Serve an svg emoji as a favicon from `/favicon.ico` 177 | 178 | #### Example Usage 179 | 180 | ```ts 181 | import { Hono } from "hono"; 182 | 183 | import serveEmojiFavicon from "stoker/middlewares/serve-emoji-favicon"; 184 | 185 | const app = new Hono(); 186 | 187 | app.use(serveEmojiFavicon("🔥")); 188 | 189 | export default app; 190 | ``` 191 | 192 | ## Open API 193 | 194 | ### Default Hook 195 | 196 | A default error hook you can include in your OpenAPIHono instance. Includes the `success` status and `ZodError` 197 | 198 | #### Example Usage 199 | 200 | ```ts 201 | import { OpenAPIHono } from "@hono/zod-openapi"; 202 | 203 | import defaultHook from "stoker/openapi/default-hook"; 204 | 205 | /* 206 | Any validation errors will respond with status code 422 and body: 207 | { 208 | success: false, 209 | error: {}, // Full Zod Error 210 | } 211 | */ 212 | const app = new OpenAPIHono({ 213 | defaultHook, 214 | }); 215 | 216 | export default app; 217 | ``` 218 | 219 | ### Helpers 220 | 221 | #### stoker/openapi/helpers/json-content 222 | 223 | Create a content / schema description with a type of `application/json` 224 | 225 | ##### Example Usage 226 | 227 | ```ts 228 | import { z } from "@hono/zod-openapi"; 229 | 230 | import jsonContent from "stoker/openapi/helpers/json-content"; 231 | 232 | const schema = z.object({ 233 | message: z.string(), 234 | }); 235 | 236 | /* 237 | * Equivalent to: 238 | { 239 | content: { 240 | "application/json": { 241 | schema, 242 | }, 243 | }, 244 | description: "Retrieve the user", 245 | } 246 | */ 247 | const response = jsonContent( 248 | schema, 249 | "Retrieve the message" 250 | ); 251 | ``` 252 | 253 | #### stoker/openapi/helpers/json-content-required 254 | 255 | Useful for json body schema validators. 256 | 257 | Create a content / schema description with a type of `application/json` and required set to `true` 258 | 259 | ##### Example Usage 260 | 261 | ```ts 262 | import { z } from "@hono/zod-openapi"; 263 | 264 | import jsonContentRequired from "stoker/openapi/helpers/json-content-required"; 265 | 266 | const schema = z.object({ 267 | message: z.string(), 268 | }); 269 | 270 | /* 271 | * Equivalent to: 272 | { 273 | content: { 274 | "application/json": { 275 | schema, 276 | }, 277 | }, 278 | description: "Retrieve the user", 279 | required: true 280 | } 281 | */ 282 | const response = jsonContentRequired( 283 | schema, 284 | "Retrieve the message" 285 | ); 286 | ``` 287 | 288 | #### stoker/openapi/helpers/json-content-one-of 289 | 290 | > Peer dependency of `@asteasolutions/zod-to-openapi` 291 | 292 | > WARNING: Not recommended right now, type hints from @hono/zod-openapi are not correct when using this helper. If you don't absolutely need `oneOf` in your specification, use zod `or` (anyOf) instead. 293 | 294 | Create a json content / schema description where the schema can be [oneOf](https://swagger.io/docs/specification/v3_0/data-models/oneof-anyof-allof-not/#oneof) multiple schemas. Useful when you have multiple possible validation response schemas. 295 | 296 | ##### Example Usage 297 | 298 | ```ts 299 | import { z } from "@hono/zod-openapi"; 300 | 301 | import jsonContentOneOf from "stoker/openapi/helpers/json-content-one-of"; 302 | import createErrorSchema from "stoker/openapi/schemas/create-error-schema"; 303 | import IdParamsSchema from "stoker/openapi/schemas/id-params"; 304 | 305 | const bodySchema = z.object({ 306 | name: z.string(), 307 | }); 308 | 309 | /* 310 | * Equivalent to: 311 | { 312 | content: { 313 | "application/json": { 314 | schema: { 315 | oneOf: SchemaObject[] 316 | }, 317 | }, 318 | }, 319 | description: "Invalid Id params or Invalid Body" 320 | } 321 | */ 322 | const result = jsonContentOneOf( 323 | [createErrorSchema(IdParamsSchema), createErrorSchema(bodySchema)], 324 | "Invalid Id params or Invalid Body" 325 | ); 326 | ``` 327 | 328 | #### stoker/openapi/helpers/one-of 329 | 330 | > Peer dependency of `@asteasolutions/zod-to-openapi` 331 | 332 | Used internally by `stoker/openapi/helpers/json-content-one-of` but exported here in case you need to access the generated schemas for other use cases. 333 | 334 | ```ts 335 | import { z } from "@hono/zod-openapi"; 336 | 337 | import oneOf from "stoker/openapi/helpers/one-of"; 338 | import createErrorSchema from "stoker/openapi/schemas/create-error-schema"; 339 | import IdParamsSchema from "stoker/openapi/schemas/id-params"; 340 | 341 | const bodySchema = z.object({ 342 | name: z.string(), 343 | }); 344 | 345 | /* 346 | * Returns: SchemaObject[] 347 | */ 348 | const result = oneOf([createErrorSchema(IdParamsSchema), createErrorSchema(bodySchema)]); 349 | ``` 350 | 351 | ### Schemas 352 | 353 | Commonly used zod schemas for use when creating routes with `@hono/zod-openapi` 354 | 355 | #### stoker/openapi/schemas/id-params 356 | 357 | Validate `id` in path params as a number. 358 | 359 | ##### Example Usage 360 | 361 | ```ts 362 | import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi"; 363 | 364 | import * as HttpStatusCodes from "stoker/http-status-codes"; 365 | import jsonContent from "stoker/openapi/helpers/json-content"; 366 | import IdParamsSchema from "stoker/openapi/schemas/id-params"; 367 | 368 | const app = new OpenAPIHono(); 369 | 370 | app.openapi( 371 | createRoute({ 372 | method: "get", 373 | path: "/users/{id}", 374 | request: { 375 | params: IdParamsSchema, 376 | }, 377 | responses: { 378 | [HttpStatusCodes.OK]: jsonContent( 379 | z.object({ 380 | id: z.number(), 381 | }), 382 | "Retrieve the user", 383 | ), 384 | }, 385 | }), 386 | (c) => { 387 | // id is a valid number 388 | const { id } = c.req.valid("param"); 389 | return c.json({ 390 | id, 391 | }, HttpStatusCodes.OK); 392 | }, 393 | ); 394 | 395 | export default app; 396 | ``` 397 | 398 | #### stoker/openapi/schemas/slug-params 399 | 400 | Validate `slug` in path params as a slug. 401 | 402 | ##### Example Usage 403 | 404 | ```ts 405 | import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi"; 406 | 407 | import * as HttpStatusCodes from "stoker/http-status-codes"; 408 | import jsonContent from "stoker/openapi/helpers/json-content"; 409 | import SlugParamsSchema from "stoker/openapi/schemas/slug-params"; 410 | 411 | const app = new OpenAPIHono(); 412 | 413 | app.openapi( 414 | createRoute({ 415 | method: "get", 416 | path: "/posts/{slug}", 417 | request: { 418 | params: SlugParamsSchema, 419 | }, 420 | responses: { 421 | [HttpStatusCodes.OK]: jsonContent( 422 | z.object({ 423 | slug: z.string(), 424 | }), 425 | "Retrieve the post", 426 | ), 427 | }, 428 | }), 429 | (c) => { 430 | // slug is a valid slug 431 | const { slug } = c.req.valid("param"); 432 | return c.json({ 433 | slug, 434 | }, HttpStatusCodes.OK); 435 | }, 436 | ); 437 | 438 | export default app; 439 | ``` 440 | 441 | #### stoker/openapi/schemas/id-uuid-params 442 | 443 | Validate `id` in path params as a uuid. 444 | 445 | ##### Example Usage 446 | 447 | ```ts 448 | import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi"; 449 | 450 | import * as HttpStatusCodes from "stoker/http-status-codes"; 451 | import jsonContent from "stoker/openapi/helpers/json-content"; 452 | import IdUUIDParamsSchema from "stoker/openapi/schemas/id-uuid-params"; 453 | 454 | const app = new OpenAPIHono(); 455 | 456 | app.openapi( 457 | createRoute({ 458 | method: "get", 459 | path: "/users/{id}", 460 | request: { 461 | params: IdUUIDParamsSchema, 462 | }, 463 | responses: { 464 | [HttpStatusCodes.OK]: jsonContent( 465 | z.object({ 466 | id: z.uuid(), 467 | }), 468 | "Retrieve the user", 469 | ), 470 | }, 471 | }), 472 | (c) => { 473 | // id is a valid uuid 474 | const { id } = c.req.valid("param"); 475 | return c.json({ 476 | id, 477 | }, HttpStatusCodes.OK); 478 | }, 479 | ); 480 | 481 | export default app; 482 | ``` 483 | 484 | #### stoker/openapi/schemas/get-params-schema 485 | 486 | Validate a custom named path param using Zod string validators by calling the function `getParamsSchema({ name, validator })`. 487 | 488 | Name defaults to `id`. 489 | Validator defaults to `uuid` and supports type `"uuid" | "nanoid" | "cuid" | "cuid2" | "ulid"`. 490 | 491 | ##### Example Usage 492 | 493 | ```ts 494 | import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi"; 495 | 496 | import * as HttpStatusCodes from "stoker/http-status-codes"; 497 | import jsonContent from "stoker/openapi/helpers/json-content"; 498 | import getParamsSchema from "stoker/openapi/schemas/get-params-schema"; 499 | 500 | const app = new OpenAPIHono(); 501 | 502 | app.openapi( 503 | createRoute({ 504 | method: "get", 505 | path: "/users/{userId}", 506 | request: { 507 | params: getParamsSchema({ 508 | name: "userId", 509 | validator: "nanoid", 510 | }), 511 | }, 512 | responses: { 513 | [HttpStatusCodes.OK]: jsonContent( 514 | z.object({ 515 | userId: z.nanoid(), 516 | }), 517 | "Retrieve the user", 518 | ), 519 | }, 520 | }), 521 | (c) => { 522 | // userId is a valid nanoid 523 | const { userId } = c.req.valid("param"); 524 | return c.json({ 525 | userId, 526 | }, HttpStatusCodes.OK); 527 | }, 528 | ); 529 | 530 | export default app; 531 | ``` 532 | 533 | #### stoker/openapi/schemas/create-message-object 534 | 535 | Create an object schema with a message string property. Useful for error messages. 536 | 537 | ##### Example Usage 538 | 539 | ```ts 540 | import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi"; 541 | 542 | import * as HttpStatusCodes from "stoker/http-status-codes"; 543 | import * as HttpStatusPhrases from "stoker/http-status-phrases"; 544 | import jsonContent from "stoker/openapi/helpers/json-content"; 545 | import createMessageObjectSchema from "stoker/openapi/schemas/create-message-object"; 546 | import IdParamsSchema from "stoker/openapi/schemas/id-params"; 547 | 548 | const app = new OpenAPIHono(); 549 | 550 | app.openapi( 551 | createRoute({ 552 | method: "get", 553 | path: "/some-thing-that-might-not-be-found", 554 | responses: { 555 | [HttpStatusCodes.NOT_FOUND]: jsonContent( 556 | createMessageObjectSchema(HttpStatusPhrases.NOT_FOUND), 557 | HttpStatusPhrases.NOT_FOUND, 558 | ), 559 | }, 560 | }), 561 | (c) => { 562 | return c.json({ 563 | message: HttpStatusPhrases.NOT_FOUND, 564 | }, HttpStatusCodes.NOT_FOUND); 565 | }, 566 | ); 567 | 568 | export default app; 569 | ``` 570 | 571 | #### stoker/openapi/schemas/create-error-schema 572 | 573 | Create an example error schema with zod error / validation messages based on given schema. 574 | 575 | ##### Example Usage 576 | 577 | ```ts 578 | import { createRoute, z } from "@hono/zod-openapi"; 579 | 580 | import * as HttpStatusCodes from "stoker/http-status-codes"; 581 | import jsonContent from "stoker/openapi/helpers/json-content"; 582 | import createErrorSchema from "stoker/openapi/schemas/create-error-schema"; 583 | 584 | const TaskSchema = z.object({ 585 | name: z.string(), 586 | completed: z.boolean().default(false), 587 | }); 588 | 589 | export const createTask = createRoute({ 590 | method: "post", 591 | path: "/task", 592 | request: { 593 | body: jsonContent(TaskSchema, "The Task"), 594 | }, 595 | responses: { 596 | // ... OK response here 597 | [HttpStatusCodes.UNPROCESSABLE_ENTITY]: jsonContent( 598 | // Creates example schema with validation messages for name / completed 599 | createErrorSchema(TaskSchema), 600 | "Invalid task", 601 | ), 602 | }, 603 | }); 604 | ``` 605 | 606 | ## Credits 607 | 608 | Project bootstrapped with [antfu/starter-ts](https://github.com/antfu/starter-ts) 609 | 610 | 611 | 612 | [npm-version-src]: https://img.shields.io/npm/v/stoker?style=flat&colorA=080f12&colorB=1fa669 613 | [npm-version-href]: https://npmjs.com/package/stoker 614 | [npm-downloads-src]: https://img.shields.io/npm/dm/stoker?style=flat&colorA=080f12&colorB=1fa669 615 | [npm-downloads-href]: https://npmjs.com/package/stoker 616 | [bundle-src]: https://img.shields.io/bundlephobia/minzip/stoker?style=flat&colorA=080f12&colorB=1fa669&label=minzip 617 | [bundle-href]: https://bundlephobia.com/result?p=stoker 618 | [license-src]: https://img.shields.io/github/license/w3cj/stoker.svg?style=flat&colorA=080f12&colorB=1fa669 619 | [license-href]: https://github.com/w3cj/stoker/blob/main/LICENSE 620 | [jsdocs-src]: https://img.shields.io/badge/jsdocs-reference-080f12?style=flat&colorA=080f12&colorB=1fa669 621 | [jsdocs-href]: https://www.jsdocs.io/package/stoker 622 | -------------------------------------------------------------------------------- /build.config.ts: -------------------------------------------------------------------------------- 1 | import { defineBuildConfig } from "unbuild"; 2 | 3 | export default defineBuildConfig({ 4 | entries: [ 5 | { 6 | input: "src/", 7 | outDir: "dist/esm/", 8 | format: "esm", 9 | ext: "js", 10 | }, 11 | { 12 | input: "src/", 13 | outDir: "dist/cjs/", 14 | format: "cjs", 15 | ext: "js", 16 | }, 17 | ], 18 | declaration: "compatible", 19 | clean: true, 20 | }); 21 | -------------------------------------------------------------------------------- /eslint.config.js: -------------------------------------------------------------------------------- 1 | // @ts-check 2 | import antfu from "@antfu/eslint-config"; 3 | 4 | export default antfu({ 5 | type: "lib", 6 | typescript: true, 7 | formatters: true, 8 | lessOpinionated: true, 9 | stylistic: { 10 | indent: 2, 11 | semi: true, 12 | quotes: "double", 13 | }, 14 | }, { 15 | rules: { 16 | "func-style": ["error", "expression"], 17 | "import/extensions": ["error", "ignorePackages"], 18 | "ts/explicit-function-return-type": ["off"], 19 | "perfectionist/sort-imports": ["error", { 20 | tsconfigRootDir: ".", 21 | }], 22 | "unicorn/filename-case": ["error", { 23 | case: "kebabCase", 24 | ignore: ["^.*\.md$"], 25 | }], 26 | }, 27 | }); 28 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "stoker", 3 | "type": "module", 4 | "version": "1.4.2", 5 | "packageManager": "pnpm@9.14.2", 6 | "description": "Utilities for hono and @hono/zod-openapi", 7 | "author": "w3cj ", 8 | "license": "MIT", 9 | "homepage": "https://github.com/w3cj/stoker", 10 | "repository": { 11 | "type": "git", 12 | "url": "git+https://github.com/w3cj/stoker.git" 13 | }, 14 | "bugs": "https://github.com/w3cj/stoker/issues", 15 | "keywords": [ 16 | "hono", 17 | "@hono/zod-openapi", 18 | "http", 19 | "status codes" 20 | ], 21 | "sideEffects": false, 22 | "exports": { 23 | ".": { 24 | "import": { 25 | "types": "./dist/esm/index.d.ts", 26 | "default": "./dist/esm/index.js" 27 | }, 28 | "require": { 29 | "types": "./dist/cjs/index.d.ts", 30 | "default": "./dist/cjs/index.js" 31 | } 32 | }, 33 | "./http-status-codes": { 34 | "import": { 35 | "types": "./dist/esm/http-status-codes.d.ts", 36 | "default": "./dist/esm/http-status-codes.js" 37 | }, 38 | "require": { 39 | "types": "./dist/cjs/http-status-codes.d.ts", 40 | "default": "./dist/cjs/http-status-codes.js" 41 | } 42 | }, 43 | "./http-status-phrases": { 44 | "import": { 45 | "types": "./dist/esm/http-status-phrases.d.ts", 46 | "default": "./dist/esm/http-status-phrases.js" 47 | }, 48 | "require": { 49 | "types": "./dist/cjs/http-status-phrases.d.ts", 50 | "default": "./dist/cjs/http-status-phrases.js" 51 | } 52 | }, 53 | "./middlewares": { 54 | "import": { 55 | "types": "./dist/esm/middlewares/index.d.ts", 56 | "default": "./dist/esm/middlewares/index.js" 57 | }, 58 | "require": { 59 | "types": "./dist/cjs/middlewares/index.d.ts", 60 | "default": "./dist/cjs/middlewares/index.js" 61 | } 62 | }, 63 | "./middlewares/not-found": { 64 | "import": { 65 | "types": "./dist/esm/middlewares/not-found.d.ts", 66 | "default": "./dist/esm/middlewares/not-found.js" 67 | }, 68 | "require": { 69 | "types": "./dist/cjs/middlewares/not-found.d.ts", 70 | "default": "./dist/cjs/middlewares/not-found.js" 71 | } 72 | }, 73 | "./middlewares/on-error": { 74 | "import": { 75 | "types": "./dist/esm/middlewares/on-error.d.ts", 76 | "default": "./dist/esm/middlewares/on-error.js" 77 | }, 78 | "require": { 79 | "types": "./dist/cjs/middlewares/on-error.d.ts", 80 | "default": "./dist/cjs/middlewares/on-error.js" 81 | } 82 | }, 83 | "./middlewares/serve-emoji-favicon": { 84 | "import": { 85 | "types": "./dist/esm/middlewares/serve-emoji-favicon.d.ts", 86 | "default": "./dist/esm/middlewares/serve-emoji-favicon.js" 87 | }, 88 | "require": { 89 | "types": "./dist/cjs/middlewares/serve-emoji-favicon.d.ts", 90 | "default": "./dist/cjs/middlewares/serve-emoji-favicon.js" 91 | } 92 | }, 93 | "./openapi": { 94 | "import": { 95 | "types": "./dist/esm/openapi/index.d.ts", 96 | "default": "./dist/esm/openapi/index.js" 97 | }, 98 | "require": { 99 | "types": "./dist/cjs/openapi/index.d.ts", 100 | "default": "./dist/cjs/openapi/index.js" 101 | } 102 | }, 103 | "./openapi/default-hook": { 104 | "import": { 105 | "types": "./dist/esm/openapi/default-hook.d.ts", 106 | "default": "./dist/esm/openapi/default-hook.js" 107 | }, 108 | "require": { 109 | "types": "./dist/cjs/openapi/default-hook.d.ts", 110 | "default": "./dist/cjs/openapi/default-hook.js" 111 | } 112 | }, 113 | "./openapi/helpers": { 114 | "import": { 115 | "types": "./dist/esm/openapi/helpers/index.d.ts", 116 | "default": "./dist/esm/openapi/helpers/index.js" 117 | }, 118 | "require": { 119 | "types": "./dist/cjs/openapi/helpers/index.d.ts", 120 | "default": "./dist/cjs/openapi/helpers/index.js" 121 | } 122 | }, 123 | "./openapi/helpers/json-content": { 124 | "import": { 125 | "types": "./dist/esm/openapi/helpers/json-content.d.ts", 126 | "default": "./dist/esm/openapi/helpers/json-content.js" 127 | }, 128 | "require": { 129 | "types": "./dist/cjs/openapi/helpers/json-content.d.ts", 130 | "default": "./dist/cjs/openapi/helpers/json-content.js" 131 | } 132 | }, 133 | "./openapi/helpers/json-content-required": { 134 | "import": { 135 | "types": "./dist/esm/openapi/helpers/json-content-required.d.ts", 136 | "default": "./dist/esm/openapi/helpers/json-content-required.js" 137 | }, 138 | "require": { 139 | "types": "./dist/cjs/openapi/helpers/json-content-required.d.ts", 140 | "default": "./dist/cjs/openapi/helpers/json-content-required.js" 141 | } 142 | }, 143 | "./openapi/helpers/json-content-one-of": { 144 | "import": { 145 | "types": "./dist/esm/openapi/helpers/json-content-one-of.d.ts", 146 | "default": "./dist/esm/openapi/helpers/json-content-one-of.js" 147 | }, 148 | "require": { 149 | "types": "./dist/cjs/openapi/helpers/json-content-one-of.d.ts", 150 | "default": "./dist/cjs/openapi/helpers/json-content-one-of.js" 151 | } 152 | }, 153 | "./openapi/helpers/one-of": { 154 | "import": { 155 | "types": "./dist/esm/openapi/helpers/one-of.d.ts", 156 | "default": "./dist/esm/openapi/helpers/one-of.js" 157 | }, 158 | "require": { 159 | "types": "./dist/cjs/openapi/helpers/one-of.d.ts", 160 | "default": "./dist/cjs/openapi/helpers/one-of.js" 161 | } 162 | }, 163 | "./openapi/schemas": { 164 | "import": { 165 | "types": "./dist/esm/openapi/schemas/index.d.ts", 166 | "default": "./dist/esm/openapi/schemas/index.js" 167 | }, 168 | "require": { 169 | "types": "./dist/cjs/openapi/schemas/index.d.ts", 170 | "default": "./dist/cjs/openapi/schemas/index.js" 171 | } 172 | }, 173 | "./openapi/schemas/id-params": { 174 | "import": { 175 | "types": "./dist/esm/openapi/schemas/id-params.d.ts", 176 | "default": "./dist/esm/openapi/schemas/id-params.js" 177 | }, 178 | "require": { 179 | "types": "./dist/cjs/openapi/schemas/id-params.d.ts", 180 | "default": "./dist/cjs/openapi/schemas/id-params.js" 181 | } 182 | }, 183 | "./openapi/schemas/id-uuid-params": { 184 | "import": { 185 | "types": "./dist/esm/openapi/schemas/id-uuid-params.d.ts", 186 | "default": "./dist/esm/openapi/schemas/id-uuid-params.js" 187 | }, 188 | "require": { 189 | "types": "./dist/cjs/openapi/schemas/id-uuid-params.d.ts", 190 | "default": "./dist/cjs/openapi/schemas/id-uuid-params.js" 191 | } 192 | }, 193 | "./openapi/schemas/slug-params": { 194 | "import": { 195 | "types": "./dist/esm/openapi/schemas/slug-params.d.ts", 196 | "default": "./dist/esm/openapi/schemas/slug-params.js" 197 | }, 198 | "require": { 199 | "types": "./dist/cjs/openapi/schemas/slug-params.d.ts", 200 | "default": "./dist/cjs/openapi/schemas/slug-params.js" 201 | } 202 | }, 203 | "./openapi/schemas/get-params-schema": { 204 | "import": { 205 | "types": "./dist/esm/openapi/schemas/get-params-schema.d.ts", 206 | "default": "./dist/esm/openapi/schemas/get-params-schema.js" 207 | }, 208 | "require": { 209 | "types": "./dist/cjs/openapi/schemas/get-params-schema.d.ts", 210 | "default": "./dist/cjs/openapi/schemas/get-params-schema.js" 211 | } 212 | }, 213 | "./openapi/schemas/create-message-object": { 214 | "import": { 215 | "types": "./dist/esm/openapi/schemas/create-message-object.d.ts", 216 | "default": "./dist/esm/openapi/schemas/create-message-object.js" 217 | }, 218 | "require": { 219 | "types": "./dist/cjs/openapi/schemas/create-message-object.d.ts", 220 | "default": "./dist/cjs/openapi/schemas/create-message-object.js" 221 | } 222 | }, 223 | "./openapi/schemas/create-error-schema": { 224 | "import": { 225 | "types": "./dist/esm/openapi/schemas/create-error-schema.d.ts", 226 | "default": "./dist/esm/openapi/schemas/create-error-schema.js" 227 | }, 228 | "require": { 229 | "types": "./dist/cjs/openapi/schemas/create-error-schema.d.ts", 230 | "default": "./dist/cjs/openapi/schemas/create-error-schema.js" 231 | } 232 | } 233 | }, 234 | "main": "./dist/cjs/index.js", 235 | "module": "./dist/esm/index.js", 236 | "types": "./dist/esm/index.d.ts", 237 | "typesVersions": { 238 | "*": { 239 | "stoker": [ 240 | "./dist/esm/index.d.ts" 241 | ], 242 | "http-status-codes": [ 243 | "./dist/esm/http-status-codes.d.ts" 244 | ], 245 | "http-status-phrases": [ 246 | "./dist/esm/http-status-phrases.d.ts" 247 | ], 248 | "middlewares": [ 249 | "./dist/esm/middlewares/index.d.ts" 250 | ], 251 | "middlewares/not-found": [ 252 | "./dist/esm/middlewares/not-found.d.ts" 253 | ], 254 | "middlewares/on-error": [ 255 | "./dist/esm/middlewares/on-error.d.ts" 256 | ], 257 | "middlewares/serve-emoji-favicon": [ 258 | "./dist/esm/middlewares/serve-emoji-favicon.d.ts" 259 | ], 260 | "openapi": [ 261 | "./dist/esm/openapi/index.d.ts" 262 | ], 263 | "openapi/default-hook": [ 264 | "./dist/esm/openapi/default-hook.d.ts" 265 | ], 266 | "openapi/helpers": [ 267 | "./dist/esm/openapi/helpers/index.d.ts" 268 | ], 269 | "openapi/helpers/json-content": [ 270 | "./dist/esm/openapi/helpers/json-content.d.ts" 271 | ], 272 | "openapi/helpers/json-content-required": [ 273 | "./dist/esm/openapi/helpers/json-content-required.d.ts" 274 | ], 275 | "openapi/helpers/json-content-one-of": [ 276 | "./dist/esm/openapi/helpers/json-content-one-of.d.ts" 277 | ], 278 | "openapi/helpers/one-of": [ 279 | "./dist/esm/openapi/helpers/one-of.d.ts" 280 | ], 281 | "openapi/schemas": [ 282 | "./dist/esm/openapi/schemas/index.d.ts" 283 | ], 284 | "openapi/schemas/id-params": [ 285 | "./dist/esm/openapi/schemas/id-params.d.ts" 286 | ], 287 | "openapi/schemas/id-uuid-params": [ 288 | "./dist/esm/openapi/schemas/id-uuid-params.d.ts" 289 | ], 290 | "openapi/schemas/slug-params": [ 291 | "./dist/esm/openapi/schemas/slug-params.d.ts" 292 | ], 293 | "openapi/schemas/get-params-schema": [ 294 | "./dist/esm/openapi/schemas/get-params-schema.d.ts" 295 | ], 296 | "openapi/schemas/create-message-object": [ 297 | "./dist/esm/openapi/schemas/create-message-object.d.ts" 298 | ], 299 | "openapi/schemas/create-error-schema": [ 300 | "./dist/esm/openapi/schemas/create-error-schema.d.ts" 301 | ] 302 | } 303 | }, 304 | "files": [ 305 | "dist" 306 | ], 307 | "scripts": { 308 | "build": "unbuild && tsx scripts/post-build.ts", 309 | "dev": "unbuild --stub", 310 | "lint": "eslint .", 311 | "prepublishOnly": "nr build", 312 | "release": "bumpp && npm publish", 313 | "start": "esno src/index.ts", 314 | "test": "vitest", 315 | "typecheck": "tsc --noEmit", 316 | "prepare": "simple-git-hooks", 317 | "update-http-statuses": "esno scripts/update-http-statuses.ts" 318 | }, 319 | "peerDependencies": { 320 | "@asteasolutions/zod-to-openapi": "^7.0.0", 321 | "@hono/zod-openapi": ">=0.16.0", 322 | "hono": "^4.0.0", 323 | "openapi3-ts": "^4.4.0" 324 | }, 325 | "peerDependenciesMeta": { 326 | "@hono/zod-openapi": { 327 | "optional": true 328 | } 329 | }, 330 | "devDependencies": { 331 | "@antfu/eslint-config": "^3.10.0", 332 | "@antfu/ni": "^0.23.1", 333 | "@antfu/utils": "^0.7.10", 334 | "@asteasolutions/zod-to-openapi": "^7.2.0", 335 | "@hono/zod-openapi": "^0.18.0", 336 | "@types/node": "^22.10.0", 337 | "bumpp": "^9.8.1", 338 | "eslint": "^9.15.0", 339 | "eslint-plugin-format": "^0.1.2", 340 | "esno": "^4.8.0", 341 | "fast-glob": "^3.3.2", 342 | "hono": "^4.6.12", 343 | "lint-staged": "^15.2.10", 344 | "openapi3-ts": "^4.4.0", 345 | "pnpm": "^9.9.0", 346 | "simple-git-hooks": "^2.11.1", 347 | "ts-morph": "^24.0.0", 348 | "tsx": "^4.19.2", 349 | "typescript": "^5.7.2", 350 | "unbuild": "^2.0.0", 351 | "vite": "^6.0.0", 352 | "vitest": "^2.1.5" 353 | }, 354 | "simple-git-hooks": { 355 | "pre-commit": "pnpm lint-staged" 356 | }, 357 | "lint-staged": { 358 | "*": "eslint --fix" 359 | } 360 | } 361 | -------------------------------------------------------------------------------- /pnpm-workspace.yaml: -------------------------------------------------------------------------------- 1 | packages: 2 | - playground 3 | - docs 4 | - packages/* 5 | - examples/* 6 | -------------------------------------------------------------------------------- /scripts/post-build.ts: -------------------------------------------------------------------------------- 1 | import fg from "fast-glob"; 2 | import fs from "node:fs/promises"; 3 | import { resolve } from "node:path"; 4 | import { fileURLToPath } from "node:url"; 5 | 6 | await fs.writeFile("./dist/cjs/package.json", JSON.stringify({ type: "commonjs" }, null, 2), "utf-8"); 7 | 8 | const dir = fileURLToPath(new URL("..", import.meta.url)); 9 | const dts = await fg(resolve(dir, "dist/cjs/**/*.d.ts")); 10 | 11 | await Promise.all(dts.map(async (file) => { 12 | const source = await fs.readFile(file, "utf-8"); 13 | if (source.match(/export default /)) { 14 | await fs.writeFile(file, source.replace("export default ", "export = "), "utf-8"); 15 | } 16 | })); 17 | -------------------------------------------------------------------------------- /scripts/update-http-statuses.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Adapted from https://github.com/prettymuchbryce/http-status-codes/blob/c840bc674ab043551b87194d1ebb5415f222abbe/scripts/update-codes.ts 3 | * Generates legacy format only. 4 | */ 5 | 6 | import { execSync } from "node:child_process"; 7 | import { 8 | Project, 9 | VariableDeclarationKind, 10 | } from "ts-morph"; 11 | 12 | interface JsonCodeComment { 13 | doc: string; 14 | description: string; 15 | } 16 | 17 | interface JsonCode { 18 | code: number; 19 | phrase: string; 20 | constant: string; 21 | comment: JsonCodeComment; 22 | isDeprecated?: boolean; 23 | } 24 | 25 | const run = async () => { 26 | console.log("Updating src/http-status-codes.ts and src/http-status-phrases.ts"); 27 | 28 | const project = new Project({ 29 | tsConfigFilePath: "tsconfig.json", 30 | }); 31 | 32 | const response = await fetch("https://raw.githubusercontent.com/prettymuchbryce/http-status-codes/refs/heads/master/codes.json"); 33 | if (!response.ok) { 34 | throw new Error(`Error retrieving codes: ${response.statusText}`); 35 | } 36 | const Codes = await response.json() as JsonCode[]; 37 | 38 | const statusCodeFile = project.createSourceFile("src/http-status-codes.ts", {}, { 39 | overwrite: true, 40 | }); 41 | 42 | statusCodeFile.insertStatements(0, "// Generated file. Do not edit\n"); 43 | statusCodeFile.insertStatements(1, `// Codes retrieved on ${new Date().toUTCString()} from https://raw.githubusercontent.com/prettymuchbryce/http-status-codes/refs/heads/master/codes.json`); 44 | 45 | Codes.forEach(({ 46 | code, 47 | constant, 48 | comment, 49 | isDeprecated, 50 | }) => { 51 | statusCodeFile.addVariableStatement({ 52 | isExported: true, 53 | declarationKind: VariableDeclarationKind.Const, 54 | declarations: [{ 55 | name: constant, 56 | initializer: code.toString(), 57 | }], 58 | }).addJsDoc({ 59 | description: `${isDeprecated ? "@deprecated\n" : ""}${comment.doc}\n\n${comment.description}`, 60 | }); 61 | }); 62 | 63 | const phrasesFile = project.createSourceFile("src/http-status-phrases.ts", {}, { 64 | overwrite: true, 65 | }); 66 | 67 | phrasesFile.insertStatements(0, "// Generated file. Do not edit\n"); 68 | phrasesFile.insertStatements(1, `// Phrases retrieved on ${new Date().toUTCString()} from https://raw.githubusercontent.com/prettymuchbryce/http-status-codes/refs/heads/master/codes.json`); 69 | 70 | Codes.forEach(({ 71 | constant, 72 | phrase, 73 | comment, 74 | isDeprecated, 75 | }) => { 76 | phrasesFile.addVariableStatement({ 77 | isExported: true, 78 | declarationKind: VariableDeclarationKind.Const, 79 | declarations: [{ 80 | name: constant, 81 | initializer: `"${phrase}"`, 82 | }], 83 | }).addJsDoc({ 84 | description: `${isDeprecated ? "@deprecated\n" : ""}${comment.doc}\n\n${comment.description}`, 85 | }); 86 | }); 87 | 88 | await project.save(); 89 | await execSync("npx eslint --fix ./src/http-status-codes.ts ./src/http-status-phrases.ts"); 90 | console.log("Successfully generated src/http-status-codes.ts and src/http-status-phrases.ts"); 91 | }; 92 | 93 | run(); 94 | -------------------------------------------------------------------------------- /src/http-status-codes.ts: -------------------------------------------------------------------------------- 1 | // Generated file. Do not edit 2 | // Codes retrieved on Thu, 03 Oct 2024 12:05:14 GMT from https://raw.githubusercontent.com/prettymuchbryce/http-status-codes/refs/heads/master/codes.json 3 | /** 4 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.3 5 | * 6 | * The request has been received but not yet acted upon. It is non-committal, meaning that there is no way in HTTP to later send an asynchronous response indicating the outcome of processing the request. It is intended for cases where another process or server handles the request, or for batch processing. 7 | */ 8 | export const ACCEPTED = 202; 9 | /** 10 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.3 11 | * 12 | * This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response. 13 | */ 14 | export const BAD_GATEWAY = 502; 15 | /** 16 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.1 17 | * 18 | * This response means that server could not understand the request due to invalid syntax. 19 | */ 20 | export const BAD_REQUEST = 400; 21 | /** 22 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.8 23 | * 24 | * This response is sent when a request conflicts with the current state of the server. 25 | */ 26 | export const CONFLICT = 409; 27 | /** 28 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.1 29 | * 30 | * This interim response indicates that everything so far is OK and that the client should continue with the request or ignore it if it is already finished. 31 | */ 32 | export const CONTINUE = 100; 33 | /** 34 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.2 35 | * 36 | * The request has succeeded and a new resource has been created as a result of it. This is typically the response sent after a PUT request. 37 | */ 38 | export const CREATED = 201; 39 | /** 40 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.14 41 | * 42 | * This response code means the expectation indicated by the Expect request header field can't be met by the server. 43 | */ 44 | export const EXPECTATION_FAILED = 417; 45 | /** 46 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.5 47 | * 48 | * The request failed due to failure of a previous request. 49 | */ 50 | export const FAILED_DEPENDENCY = 424; 51 | /** 52 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.3 53 | * 54 | * The client does not have access rights to the content, i.e. they are unauthorized, so server is rejecting to give proper response. Unlike 401, the client's identity is known to the server. 55 | */ 56 | export const FORBIDDEN = 403; 57 | /** 58 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.5 59 | * 60 | * This error response is given when the server is acting as a gateway and cannot get a response in time. 61 | */ 62 | export const GATEWAY_TIMEOUT = 504; 63 | /** 64 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.9 65 | * 66 | * This response would be sent when the requested content has been permenantly deleted from server, with no forwarding address. Clients are expected to remove their caches and links to the resource. The HTTP specification intends this status code to be used for "limited-time, promotional services". APIs should not feel compelled to indicate resources that have been deleted with this status code. 67 | */ 68 | export const GONE = 410; 69 | /** 70 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.6 71 | * 72 | * The HTTP version used in the request is not supported by the server. 73 | */ 74 | export const HTTP_VERSION_NOT_SUPPORTED = 505; 75 | /** 76 | * Official Documentation @ https://tools.ietf.org/html/rfc2324#section-2.3.2 77 | * 78 | * Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout. 79 | */ 80 | export const IM_A_TEAPOT = 418; 81 | /** 82 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.6 83 | * 84 | * The 507 (Insufficient Storage) status code means the method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request. This condition is considered to be temporary. If the request which received this status code was the result of a user action, the request MUST NOT be repeated until it is requested by a separate user action. 85 | */ 86 | export const INSUFFICIENT_SPACE_ON_RESOURCE = 419; 87 | /** 88 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.6 89 | * 90 | * The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process. 91 | */ 92 | export const INSUFFICIENT_STORAGE = 507; 93 | /** 94 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.1 95 | * 96 | * The server encountered an unexpected condition that prevented it from fulfilling the request. 97 | */ 98 | export const INTERNAL_SERVER_ERROR = 500; 99 | /** 100 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.10 101 | * 102 | * The server rejected the request because the Content-Length header field is not defined and the server requires it. 103 | */ 104 | export const LENGTH_REQUIRED = 411; 105 | /** 106 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.4 107 | * 108 | * The resource that is being accessed is locked. 109 | */ 110 | export const LOCKED = 423; 111 | /** 112 | * @deprecated 113 | * Official Documentation @ https://tools.ietf.org/rfcdiff?difftype=--hwdiff&url2=draft-ietf-webdav-protocol-06.txt 114 | * 115 | * A deprecated response used by the Spring Framework when a method has failed. 116 | */ 117 | export const METHOD_FAILURE = 420; 118 | /** 119 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.5 120 | * 121 | * The request method is known by the server but has been disabled and cannot be used. For example, an API may forbid DELETE-ing a resource. The two mandatory methods, GET and HEAD, must never be disabled and should not return this error code. 122 | */ 123 | export const METHOD_NOT_ALLOWED = 405; 124 | /** 125 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.2 126 | * 127 | * This response code means that URI of requested resource has been changed. Probably, new URI would be given in the response. 128 | */ 129 | export const MOVED_PERMANENTLY = 301; 130 | /** 131 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.3 132 | * 133 | * This response code means that URI of requested resource has been changed temporarily. New changes in the URI might be made in the future. Therefore, this same URI should be used by the client in future requests. 134 | */ 135 | export const MOVED_TEMPORARILY = 302; 136 | /** 137 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.2 138 | * 139 | * A Multi-Status response conveys information about multiple resources in situations where multiple status codes might be appropriate. 140 | */ 141 | export const MULTI_STATUS = 207; 142 | /** 143 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.1 144 | * 145 | * The request has more than one possible responses. User-agent or user should choose one of them. There is no standardized way to choose one of the responses. 146 | */ 147 | export const MULTIPLE_CHOICES = 300; 148 | /** 149 | * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-6 150 | * 151 | * The 511 status code indicates that the client needs to authenticate to gain network access. 152 | */ 153 | export const NETWORK_AUTHENTICATION_REQUIRED = 511; 154 | /** 155 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.5 156 | * 157 | * There is no content to send for this request, but the headers may be useful. The user-agent may update its cached headers for this resource with the new ones. 158 | */ 159 | export const NO_CONTENT = 204; 160 | /** 161 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.4 162 | * 163 | * This response code means returned meta-information set is not exact set as available from the origin server, but collected from a local or a third party copy. Except this condition, 200 OK response should be preferred instead of this response. 164 | */ 165 | export const NON_AUTHORITATIVE_INFORMATION = 203; 166 | /** 167 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.6 168 | * 169 | * This response is sent when the web server, after performing server-driven content negotiation, doesn't find any content following the criteria given by the user agent. 170 | */ 171 | export const NOT_ACCEPTABLE = 406; 172 | /** 173 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.4 174 | * 175 | * The server can not find requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. Servers may also send this response instead of 403 to hide the existence of a resource from an unauthorized client. This response code is probably the most famous one due to its frequent occurence on the web. 176 | */ 177 | export const NOT_FOUND = 404; 178 | /** 179 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.2 180 | * 181 | * The request method is not supported by the server and cannot be handled. The only methods that servers are required to support (and therefore that must not return this code) are GET and HEAD. 182 | */ 183 | export const NOT_IMPLEMENTED = 501; 184 | /** 185 | * Official Documentation @ https://tools.ietf.org/html/rfc7232#section-4.1 186 | * 187 | * This is used for caching purposes. It is telling to client that response has not been modified. So, client can continue to use same cached version of response. 188 | */ 189 | export const NOT_MODIFIED = 304; 190 | /** 191 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.1 192 | * 193 | * The request has succeeded. The meaning of a success varies depending on the HTTP method: 194 | * GET: The resource has been fetched and is transmitted in the message body. 195 | * HEAD: The entity headers are in the message body. 196 | * POST: The resource describing the result of the action is transmitted in the message body. 197 | * TRACE: The message body contains the request message as received by the server 198 | */ 199 | export const OK = 200; 200 | /** 201 | * Official Documentation @ https://tools.ietf.org/html/rfc7233#section-4.1 202 | * 203 | * This response code is used because of range header sent by the client to separate download into multiple streams. 204 | */ 205 | export const PARTIAL_CONTENT = 206; 206 | /** 207 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.2 208 | * 209 | * This response code is reserved for future use. Initial aim for creating this code was using it for digital payment systems however this is not used currently. 210 | */ 211 | export const PAYMENT_REQUIRED = 402; 212 | /** 213 | * Official Documentation @ https://tools.ietf.org/html/rfc7538#section-3 214 | * 215 | * This means that the resource is now permanently located at another URI, specified by the Location: HTTP Response header. This has the same semantics as the 301 Moved Permanently HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request. 216 | */ 217 | export const PERMANENT_REDIRECT = 308; 218 | /** 219 | * Official Documentation @ https://tools.ietf.org/html/rfc7232#section-4.2 220 | * 221 | * The client has indicated preconditions in its headers which the server does not meet. 222 | */ 223 | export const PRECONDITION_FAILED = 412; 224 | /** 225 | * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-3 226 | * 227 | * The origin server requires the request to be conditional. Intended to prevent the 'lost update' problem, where a client GETs a resource's state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict. 228 | */ 229 | export const PRECONDITION_REQUIRED = 428; 230 | /** 231 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.1 232 | * 233 | * This code indicates that the server has received and is processing the request, but no response is available yet. 234 | */ 235 | export const PROCESSING = 102; 236 | /** 237 | * Official Documentation @ https://www.rfc-editor.org/rfc/rfc8297#page-3 238 | * 239 | * This code indicates to the client that the server is likely to send a final response with the header fields included in the informational response. 240 | */ 241 | export const EARLY_HINTS = 103; 242 | /** 243 | * Official Documentation @ https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.15 244 | * 245 | * The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol. 246 | */ 247 | export const UPGRADE_REQUIRED = 426; 248 | /** 249 | * Official Documentation @ https://tools.ietf.org/html/rfc7235#section-3.2 250 | * 251 | * This is similar to 401 but authentication is needed to be done by a proxy. 252 | */ 253 | export const PROXY_AUTHENTICATION_REQUIRED = 407; 254 | /** 255 | * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-5 256 | * 257 | * The server is unwilling to process the request because its header fields are too large. The request MAY be resubmitted after reducing the size of the request header fields. 258 | */ 259 | export const REQUEST_HEADER_FIELDS_TOO_LARGE = 431; 260 | /** 261 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.7 262 | * 263 | * This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers, like Chrome, Firefox 27+, or IE9, use HTTP pre-connection mechanisms to speed up surfing. Also note that some servers merely shut down the connection without sending this message. 264 | */ 265 | export const REQUEST_TIMEOUT = 408; 266 | /** 267 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.11 268 | * 269 | * Request entity is larger than limits defined by server; the server might close the connection or return an Retry-After header field. 270 | */ 271 | export const REQUEST_TOO_LONG = 413; 272 | /** 273 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.12 274 | * 275 | * The URI requested by the client is longer than the server is willing to interpret. 276 | */ 277 | export const REQUEST_URI_TOO_LONG = 414; 278 | /** 279 | * Official Documentation @ https://tools.ietf.org/html/rfc7233#section-4.4 280 | * 281 | * The range specified by the Range header field in the request can't be fulfilled; it's possible that the range is outside the size of the target URI's data. 282 | */ 283 | export const REQUESTED_RANGE_NOT_SATISFIABLE = 416; 284 | /** 285 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.6 286 | * 287 | * This response code is sent after accomplishing request to tell user agent reset document view which sent this request. 288 | */ 289 | export const RESET_CONTENT = 205; 290 | /** 291 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.4 292 | * 293 | * Server sent this response to directing client to get requested resource to another URI with an GET request. 294 | */ 295 | export const SEE_OTHER = 303; 296 | /** 297 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.4 298 | * 299 | * The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent. This responses should be used for temporary conditions and the Retry-After: HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached. 300 | */ 301 | export const SERVICE_UNAVAILABLE = 503; 302 | /** 303 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.2 304 | * 305 | * This code is sent in response to an Upgrade request header by the client, and indicates the protocol the server is switching too. 306 | */ 307 | export const SWITCHING_PROTOCOLS = 101; 308 | /** 309 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.7 310 | * 311 | * Server sent this response to directing client to get requested resource to another URI with same method that used prior request. This has the same semantic than the 302 Found HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request. 312 | */ 313 | export const TEMPORARY_REDIRECT = 307; 314 | /** 315 | * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-4 316 | * 317 | * The user has sent too many requests in a given amount of time ("rate limiting"). 318 | */ 319 | export const TOO_MANY_REQUESTS = 429; 320 | /** 321 | * Official Documentation @ https://tools.ietf.org/html/rfc7235#section-3.1 322 | * 323 | * Although the HTTP standard specifies "unauthorized", semantically this response means "unauthenticated". That is, the client must authenticate itself to get the requested response. 324 | */ 325 | export const UNAUTHORIZED = 401; 326 | /** 327 | * Official Documentation @ https://tools.ietf.org/html/rfc7725 328 | * 329 | * The user-agent requested a resource that cannot legally be provided, such as a web page censored by a government. 330 | */ 331 | export const UNAVAILABLE_FOR_LEGAL_REASONS = 451; 332 | /** 333 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.3 334 | * 335 | * The request was well-formed but was unable to be followed due to semantic errors. 336 | */ 337 | export const UNPROCESSABLE_ENTITY = 422; 338 | /** 339 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.13 340 | * 341 | * The media format of the requested data is not supported by the server, so the server is rejecting the request. 342 | */ 343 | export const UNSUPPORTED_MEDIA_TYPE = 415; 344 | /** 345 | * @deprecated 346 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.6 347 | * 348 | * Was defined in a previous version of the HTTP specification to indicate that a requested response must be accessed by a proxy. It has been deprecated due to security concerns regarding in-band configuration of a proxy. 349 | */ 350 | export const USE_PROXY = 305; 351 | /** 352 | * Official Documentation @ https://datatracker.ietf.org/doc/html/rfc7540#section-9.1.2 353 | * 354 | * Defined in the specification of HTTP/2 to indicate that a server is not able to produce a response for the combination of scheme and authority that are included in the request URI. 355 | */ 356 | export const MISDIRECTED_REQUEST = 421; 357 | -------------------------------------------------------------------------------- /src/http-status-phrases.ts: -------------------------------------------------------------------------------- 1 | // Generated file. Do not edit 2 | // Phrases retrieved on Thu, 03 Oct 2024 12:05:14 GMT from https://raw.githubusercontent.com/prettymuchbryce/http-status-codes/refs/heads/master/codes.json 3 | /** 4 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.3 5 | * 6 | * The request has been received but not yet acted upon. It is non-committal, meaning that there is no way in HTTP to later send an asynchronous response indicating the outcome of processing the request. It is intended for cases where another process or server handles the request, or for batch processing. 7 | */ 8 | export const ACCEPTED = "Accepted"; 9 | /** 10 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.3 11 | * 12 | * This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response. 13 | */ 14 | export const BAD_GATEWAY = "Bad Gateway"; 15 | /** 16 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.1 17 | * 18 | * This response means that server could not understand the request due to invalid syntax. 19 | */ 20 | export const BAD_REQUEST = "Bad Request"; 21 | /** 22 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.8 23 | * 24 | * This response is sent when a request conflicts with the current state of the server. 25 | */ 26 | export const CONFLICT = "Conflict"; 27 | /** 28 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.1 29 | * 30 | * This interim response indicates that everything so far is OK and that the client should continue with the request or ignore it if it is already finished. 31 | */ 32 | export const CONTINUE = "Continue"; 33 | /** 34 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.2 35 | * 36 | * The request has succeeded and a new resource has been created as a result of it. This is typically the response sent after a PUT request. 37 | */ 38 | export const CREATED = "Created"; 39 | /** 40 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.14 41 | * 42 | * This response code means the expectation indicated by the Expect request header field can't be met by the server. 43 | */ 44 | export const EXPECTATION_FAILED = "Expectation Failed"; 45 | /** 46 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.5 47 | * 48 | * The request failed due to failure of a previous request. 49 | */ 50 | export const FAILED_DEPENDENCY = "Failed Dependency"; 51 | /** 52 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.3 53 | * 54 | * The client does not have access rights to the content, i.e. they are unauthorized, so server is rejecting to give proper response. Unlike 401, the client's identity is known to the server. 55 | */ 56 | export const FORBIDDEN = "Forbidden"; 57 | /** 58 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.5 59 | * 60 | * This error response is given when the server is acting as a gateway and cannot get a response in time. 61 | */ 62 | export const GATEWAY_TIMEOUT = "Gateway Timeout"; 63 | /** 64 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.9 65 | * 66 | * This response would be sent when the requested content has been permenantly deleted from server, with no forwarding address. Clients are expected to remove their caches and links to the resource. The HTTP specification intends this status code to be used for "limited-time, promotional services". APIs should not feel compelled to indicate resources that have been deleted with this status code. 67 | */ 68 | export const GONE = "Gone"; 69 | /** 70 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.6 71 | * 72 | * The HTTP version used in the request is not supported by the server. 73 | */ 74 | export const HTTP_VERSION_NOT_SUPPORTED = "HTTP Version Not Supported"; 75 | /** 76 | * Official Documentation @ https://tools.ietf.org/html/rfc2324#section-2.3.2 77 | * 78 | * Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout. 79 | */ 80 | export const IM_A_TEAPOT = "I'm a teapot"; 81 | /** 82 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.6 83 | * 84 | * The 507 (Insufficient Storage) status code means the method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request. This condition is considered to be temporary. If the request which received this status code was the result of a user action, the request MUST NOT be repeated until it is requested by a separate user action. 85 | */ 86 | export const INSUFFICIENT_SPACE_ON_RESOURCE = "Insufficient Space on Resource"; 87 | /** 88 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.6 89 | * 90 | * The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process. 91 | */ 92 | export const INSUFFICIENT_STORAGE = "Insufficient Storage"; 93 | /** 94 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.1 95 | * 96 | * The server encountered an unexpected condition that prevented it from fulfilling the request. 97 | */ 98 | export const INTERNAL_SERVER_ERROR = "Internal Server Error"; 99 | /** 100 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.10 101 | * 102 | * The server rejected the request because the Content-Length header field is not defined and the server requires it. 103 | */ 104 | export const LENGTH_REQUIRED = "Length Required"; 105 | /** 106 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.4 107 | * 108 | * The resource that is being accessed is locked. 109 | */ 110 | export const LOCKED = "Locked"; 111 | /** 112 | * @deprecated 113 | * Official Documentation @ https://tools.ietf.org/rfcdiff?difftype=--hwdiff&url2=draft-ietf-webdav-protocol-06.txt 114 | * 115 | * A deprecated response used by the Spring Framework when a method has failed. 116 | */ 117 | export const METHOD_FAILURE = "Method Failure"; 118 | /** 119 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.5 120 | * 121 | * The request method is known by the server but has been disabled and cannot be used. For example, an API may forbid DELETE-ing a resource. The two mandatory methods, GET and HEAD, must never be disabled and should not return this error code. 122 | */ 123 | export const METHOD_NOT_ALLOWED = "Method Not Allowed"; 124 | /** 125 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.2 126 | * 127 | * This response code means that URI of requested resource has been changed. Probably, new URI would be given in the response. 128 | */ 129 | export const MOVED_PERMANENTLY = "Moved Permanently"; 130 | /** 131 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.3 132 | * 133 | * This response code means that URI of requested resource has been changed temporarily. New changes in the URI might be made in the future. Therefore, this same URI should be used by the client in future requests. 134 | */ 135 | export const MOVED_TEMPORARILY = "Moved Temporarily"; 136 | /** 137 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.2 138 | * 139 | * A Multi-Status response conveys information about multiple resources in situations where multiple status codes might be appropriate. 140 | */ 141 | export const MULTI_STATUS = "Multi-Status"; 142 | /** 143 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.1 144 | * 145 | * The request has more than one possible responses. User-agent or user should choose one of them. There is no standardized way to choose one of the responses. 146 | */ 147 | export const MULTIPLE_CHOICES = "Multiple Choices"; 148 | /** 149 | * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-6 150 | * 151 | * The 511 status code indicates that the client needs to authenticate to gain network access. 152 | */ 153 | export const NETWORK_AUTHENTICATION_REQUIRED = "Network Authentication Required"; 154 | /** 155 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.5 156 | * 157 | * There is no content to send for this request, but the headers may be useful. The user-agent may update its cached headers for this resource with the new ones. 158 | */ 159 | export const NO_CONTENT = "No Content"; 160 | /** 161 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.4 162 | * 163 | * This response code means returned meta-information set is not exact set as available from the origin server, but collected from a local or a third party copy. Except this condition, 200 OK response should be preferred instead of this response. 164 | */ 165 | export const NON_AUTHORITATIVE_INFORMATION = "Non Authoritative Information"; 166 | /** 167 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.6 168 | * 169 | * This response is sent when the web server, after performing server-driven content negotiation, doesn't find any content following the criteria given by the user agent. 170 | */ 171 | export const NOT_ACCEPTABLE = "Not Acceptable"; 172 | /** 173 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.4 174 | * 175 | * The server can not find requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. Servers may also send this response instead of 403 to hide the existence of a resource from an unauthorized client. This response code is probably the most famous one due to its frequent occurence on the web. 176 | */ 177 | export const NOT_FOUND = "Not Found"; 178 | /** 179 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.2 180 | * 181 | * The request method is not supported by the server and cannot be handled. The only methods that servers are required to support (and therefore that must not return this code) are GET and HEAD. 182 | */ 183 | export const NOT_IMPLEMENTED = "Not Implemented"; 184 | /** 185 | * Official Documentation @ https://tools.ietf.org/html/rfc7232#section-4.1 186 | * 187 | * This is used for caching purposes. It is telling to client that response has not been modified. So, client can continue to use same cached version of response. 188 | */ 189 | export const NOT_MODIFIED = "Not Modified"; 190 | /** 191 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.1 192 | * 193 | * The request has succeeded. The meaning of a success varies depending on the HTTP method: 194 | * GET: The resource has been fetched and is transmitted in the message body. 195 | * HEAD: The entity headers are in the message body. 196 | * POST: The resource describing the result of the action is transmitted in the message body. 197 | * TRACE: The message body contains the request message as received by the server 198 | */ 199 | export const OK = "OK"; 200 | /** 201 | * Official Documentation @ https://tools.ietf.org/html/rfc7233#section-4.1 202 | * 203 | * This response code is used because of range header sent by the client to separate download into multiple streams. 204 | */ 205 | export const PARTIAL_CONTENT = "Partial Content"; 206 | /** 207 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.2 208 | * 209 | * This response code is reserved for future use. Initial aim for creating this code was using it for digital payment systems however this is not used currently. 210 | */ 211 | export const PAYMENT_REQUIRED = "Payment Required"; 212 | /** 213 | * Official Documentation @ https://tools.ietf.org/html/rfc7538#section-3 214 | * 215 | * This means that the resource is now permanently located at another URI, specified by the Location: HTTP Response header. This has the same semantics as the 301 Moved Permanently HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request. 216 | */ 217 | export const PERMANENT_REDIRECT = "Permanent Redirect"; 218 | /** 219 | * Official Documentation @ https://tools.ietf.org/html/rfc7232#section-4.2 220 | * 221 | * The client has indicated preconditions in its headers which the server does not meet. 222 | */ 223 | export const PRECONDITION_FAILED = "Precondition Failed"; 224 | /** 225 | * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-3 226 | * 227 | * The origin server requires the request to be conditional. Intended to prevent the 'lost update' problem, where a client GETs a resource's state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict. 228 | */ 229 | export const PRECONDITION_REQUIRED = "Precondition Required"; 230 | /** 231 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.1 232 | * 233 | * This code indicates that the server has received and is processing the request, but no response is available yet. 234 | */ 235 | export const PROCESSING = "Processing"; 236 | /** 237 | * Official Documentation @ https://www.rfc-editor.org/rfc/rfc8297#page-3 238 | * 239 | * This code indicates to the client that the server is likely to send a final response with the header fields included in the informational response. 240 | */ 241 | export const EARLY_HINTS = "Early Hints"; 242 | /** 243 | * Official Documentation @ https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.15 244 | * 245 | * The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol. 246 | */ 247 | export const UPGRADE_REQUIRED = "Upgrade Required"; 248 | /** 249 | * Official Documentation @ https://tools.ietf.org/html/rfc7235#section-3.2 250 | * 251 | * This is similar to 401 but authentication is needed to be done by a proxy. 252 | */ 253 | export const PROXY_AUTHENTICATION_REQUIRED = "Proxy Authentication Required"; 254 | /** 255 | * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-5 256 | * 257 | * The server is unwilling to process the request because its header fields are too large. The request MAY be resubmitted after reducing the size of the request header fields. 258 | */ 259 | export const REQUEST_HEADER_FIELDS_TOO_LARGE = "Request Header Fields Too Large"; 260 | /** 261 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.7 262 | * 263 | * This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers, like Chrome, Firefox 27+, or IE9, use HTTP pre-connection mechanisms to speed up surfing. Also note that some servers merely shut down the connection without sending this message. 264 | */ 265 | export const REQUEST_TIMEOUT = "Request Timeout"; 266 | /** 267 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.11 268 | * 269 | * Request entity is larger than limits defined by server; the server might close the connection or return an Retry-After header field. 270 | */ 271 | export const REQUEST_TOO_LONG = "Request Entity Too Large"; 272 | /** 273 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.12 274 | * 275 | * The URI requested by the client is longer than the server is willing to interpret. 276 | */ 277 | export const REQUEST_URI_TOO_LONG = "Request-URI Too Long"; 278 | /** 279 | * Official Documentation @ https://tools.ietf.org/html/rfc7233#section-4.4 280 | * 281 | * The range specified by the Range header field in the request can't be fulfilled; it's possible that the range is outside the size of the target URI's data. 282 | */ 283 | export const REQUESTED_RANGE_NOT_SATISFIABLE = "Requested Range Not Satisfiable"; 284 | /** 285 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.6 286 | * 287 | * This response code is sent after accomplishing request to tell user agent reset document view which sent this request. 288 | */ 289 | export const RESET_CONTENT = "Reset Content"; 290 | /** 291 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.4 292 | * 293 | * Server sent this response to directing client to get requested resource to another URI with an GET request. 294 | */ 295 | export const SEE_OTHER = "See Other"; 296 | /** 297 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.4 298 | * 299 | * The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent. This responses should be used for temporary conditions and the Retry-After: HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached. 300 | */ 301 | export const SERVICE_UNAVAILABLE = "Service Unavailable"; 302 | /** 303 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.2 304 | * 305 | * This code is sent in response to an Upgrade request header by the client, and indicates the protocol the server is switching too. 306 | */ 307 | export const SWITCHING_PROTOCOLS = "Switching Protocols"; 308 | /** 309 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.7 310 | * 311 | * Server sent this response to directing client to get requested resource to another URI with same method that used prior request. This has the same semantic than the 302 Found HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request. 312 | */ 313 | export const TEMPORARY_REDIRECT = "Temporary Redirect"; 314 | /** 315 | * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-4 316 | * 317 | * The user has sent too many requests in a given amount of time ("rate limiting"). 318 | */ 319 | export const TOO_MANY_REQUESTS = "Too Many Requests"; 320 | /** 321 | * Official Documentation @ https://tools.ietf.org/html/rfc7235#section-3.1 322 | * 323 | * Although the HTTP standard specifies "unauthorized", semantically this response means "unauthenticated". That is, the client must authenticate itself to get the requested response. 324 | */ 325 | export const UNAUTHORIZED = "Unauthorized"; 326 | /** 327 | * Official Documentation @ https://tools.ietf.org/html/rfc7725 328 | * 329 | * The user-agent requested a resource that cannot legally be provided, such as a web page censored by a government. 330 | */ 331 | export const UNAVAILABLE_FOR_LEGAL_REASONS = "Unavailable For Legal Reasons"; 332 | /** 333 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.3 334 | * 335 | * The request was well-formed but was unable to be followed due to semantic errors. 336 | */ 337 | export const UNPROCESSABLE_ENTITY = "Unprocessable Entity"; 338 | /** 339 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.13 340 | * 341 | * The media format of the requested data is not supported by the server, so the server is rejecting the request. 342 | */ 343 | export const UNSUPPORTED_MEDIA_TYPE = "Unsupported Media Type"; 344 | /** 345 | * @deprecated 346 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.6 347 | * 348 | * Was defined in a previous version of the HTTP specification to indicate that a requested response must be accessed by a proxy. It has been deprecated due to security concerns regarding in-band configuration of a proxy. 349 | */ 350 | export const USE_PROXY = "Use Proxy"; 351 | /** 352 | * Official Documentation @ https://datatracker.ietf.org/doc/html/rfc7540#section-9.1.2 353 | * 354 | * Defined in the specification of HTTP/2 to indicate that a server is not able to produce a response for the combination of scheme and authority that are included in the request URI. 355 | */ 356 | export const MISDIRECTED_REQUEST = "Misdirected Request"; 357 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export * as middlewares from "./middlewares/index.js"; 2 | export * as openapi from "./openapi/index.js"; 3 | -------------------------------------------------------------------------------- /src/middlewares/index.ts: -------------------------------------------------------------------------------- 1 | export { default as notFound } from "./not-found.js"; 2 | export { default as onError } from "./on-error.js"; 3 | export { default as serveEmojiFavicon } from "./serve-emoji-favicon.js"; 4 | -------------------------------------------------------------------------------- /src/middlewares/not-found.ts: -------------------------------------------------------------------------------- 1 | import type { NotFoundHandler } from "hono"; 2 | 3 | import { NOT_FOUND } from "../http-status-codes.js"; 4 | import { NOT_FOUND as NOT_FOUND_MESSAGE } from "../http-status-phrases.js"; 5 | 6 | const notFound: NotFoundHandler = (c) => { 7 | return c.json({ 8 | message: `${NOT_FOUND_MESSAGE} - ${c.req.path}`, 9 | }, NOT_FOUND); 10 | }; 11 | 12 | export default notFound; 13 | -------------------------------------------------------------------------------- /src/middlewares/on-error.test.ts: -------------------------------------------------------------------------------- 1 | import path from "node:path"; 2 | import { describe, expect, it } from "vitest"; 3 | 4 | import onError from "./on-error.js"; 5 | 6 | describe("onError", () => { 7 | it("should use NODE_ENV from context if defined", async () => { 8 | const { Context } = await import(path.join(process.cwd(), "node_modules/hono/dist/context.js")); 9 | const req = new Request("http://localhost/"); 10 | const context = new Context(req); 11 | context.env = { 12 | NODE_ENV: "production", 13 | }; 14 | const response = await onError( 15 | new Error("Test error"), 16 | context, 17 | ); 18 | expect(response.status).toBe(500); 19 | const json = await response.json(); 20 | expect(json).toEqual({ 21 | message: "Test error", 22 | stack: undefined, 23 | }); 24 | }); 25 | 26 | it("should use NODE_ENV from process.env otherwise", async () => { 27 | const { Context } = await import(path.join(process.cwd(), "node_modules/hono/dist/context.js")); 28 | const req = new Request("http://localhost/"); 29 | const context = new Context(req); 30 | process.env.NODE_ENV = "production"; 31 | const response = await onError( 32 | new Error("Test error"), 33 | context, 34 | ); 35 | expect(response.status).toBe(500); 36 | const json = await response.json(); 37 | expect(json).toEqual({ 38 | message: "Test error", 39 | stack: undefined, 40 | }); 41 | }); 42 | }); 43 | -------------------------------------------------------------------------------- /src/middlewares/on-error.ts: -------------------------------------------------------------------------------- 1 | import type { ErrorHandler } from "hono"; 2 | import type { StatusCode } from "hono/utils/http-status"; 3 | 4 | import { INTERNAL_SERVER_ERROR, OK } from "../http-status-codes.js"; 5 | 6 | const onError: ErrorHandler = (err, c) => { 7 | const currentStatus = "status" in err 8 | ? err.status 9 | : c.newResponse(null).status; 10 | const statusCode = currentStatus !== OK 11 | ? (currentStatus as StatusCode) 12 | : INTERNAL_SERVER_ERROR; 13 | // eslint-disable-next-line node/prefer-global/process 14 | const env = c.env?.NODE_ENV || process.env?.NODE_ENV; 15 | return c.json( 16 | { 17 | message: err.message, 18 | 19 | stack: env === "production" 20 | ? undefined 21 | : err.stack, 22 | }, 23 | statusCode, 24 | ); 25 | }; 26 | 27 | export default onError; 28 | -------------------------------------------------------------------------------- /src/middlewares/serve-emoji-favicon.ts: -------------------------------------------------------------------------------- 1 | import type { MiddlewareHandler } from "hono"; 2 | 3 | const serveEmojiFavicon = (emoji: string): MiddlewareHandler => { 4 | return async (c, next) => { 5 | if (c.req.path === "/favicon.ico") { 6 | c.header("Content-Type", "image/svg+xml"); 7 | return c.body(`${emoji}`); 8 | } 9 | return next(); 10 | }; 11 | }; 12 | 13 | export default serveEmojiFavicon; 14 | -------------------------------------------------------------------------------- /src/openapi/default-hook.ts: -------------------------------------------------------------------------------- 1 | import type { Hook } from "@hono/zod-openapi"; 2 | 3 | import { UNPROCESSABLE_ENTITY } from "../http-status-codes.js"; 4 | 5 | const defaultHook: Hook = (result, c) => { 6 | if (!result.success) { 7 | return c.json( 8 | { 9 | success: result.success, 10 | error: result.error, 11 | }, 12 | UNPROCESSABLE_ENTITY, 13 | ); 14 | } 15 | }; 16 | 17 | export default defaultHook; 18 | -------------------------------------------------------------------------------- /src/openapi/helpers/index.ts: -------------------------------------------------------------------------------- 1 | export { default as jsonContentOneOf } from "./json-content-one-of.js"; 2 | export { default as jsonContentRequired } from "./json-content-required.js"; 3 | export { default as jsonContent } from "./json-content.js"; 4 | export { default as oneOf } from "./one-of.js"; 5 | -------------------------------------------------------------------------------- /src/openapi/helpers/json-content-one-of.test.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable ts/ban-ts-comment */ 2 | import { z } from "@hono/zod-openapi"; 3 | import { describe, expect, it } from "vitest"; 4 | 5 | import jsonContentOneOf from "./json-content-one-of.js"; 6 | 7 | describe("jsonContentOneOf", () => { 8 | it("accepts a single schema", () => { 9 | const result = jsonContentOneOf([ 10 | z.object({ message: z.string() }), 11 | ], "Test 1"); 12 | const oneOf = result.content["application/json"].schema.oneOf; 13 | expect(oneOf.length).toBe(1); 14 | const definition = oneOf[0]; 15 | // @ts-expect-error 16 | expect(definition.type).toBe("object"); 17 | // @ts-expect-error 18 | expect(definition.properties.message).toBeDefined(); 19 | }); 20 | 21 | it("accepts multiple schemas", () => { 22 | const result = jsonContentOneOf([ 23 | z.object({ message: z.string() }), 24 | z.object({ 25 | message: z.string(), 26 | error: z.array( 27 | z.object({ code: z.string() }), 28 | ), 29 | }), 30 | ], "Test 2"); 31 | const oneOf = result.content["application/json"].schema.oneOf; 32 | expect(oneOf.length).toBe(2); 33 | const definition1 = oneOf[0]; 34 | // @ts-expect-error 35 | expect(definition1.type).toBe("object"); 36 | // @ts-expect-error 37 | expect(definition1.properties.message).toBeDefined(); 38 | 39 | const definition2 = oneOf[1]; 40 | // @ts-expect-error 41 | expect(definition2.type).toBe("object"); 42 | // @ts-expect-error 43 | expect(definition2.properties.error).toBeDefined(); 44 | }); 45 | }); 46 | -------------------------------------------------------------------------------- /src/openapi/helpers/json-content-one-of.ts: -------------------------------------------------------------------------------- 1 | import type { ZodSchema } from "./types.ts"; 2 | 3 | import oneOf from "./one-of.js"; 4 | 5 | const jsonContentOneOf = < 6 | T extends ZodSchema, 7 | >(schemas: T[], 8 | description: string, 9 | ) => { 10 | return { 11 | content: { 12 | "application/json": { 13 | schema: { 14 | oneOf: oneOf(schemas), 15 | }, 16 | }, 17 | }, 18 | description, 19 | }; 20 | }; 21 | 22 | export default jsonContentOneOf; 23 | -------------------------------------------------------------------------------- /src/openapi/helpers/json-content-required.ts: -------------------------------------------------------------------------------- 1 | import type { ZodSchema } from "./types.ts"; 2 | 3 | import jsonContent from "./json-content.js"; 4 | 5 | const jsonContentRequired = < 6 | T extends ZodSchema, 7 | >(schema: T, 8 | description: string, 9 | ) => { 10 | return { 11 | ...jsonContent(schema, description), 12 | required: true, 13 | }; 14 | }; 15 | 16 | export default jsonContentRequired; 17 | -------------------------------------------------------------------------------- /src/openapi/helpers/json-content.ts: -------------------------------------------------------------------------------- 1 | import type { ZodSchema } from "./types.ts"; 2 | 3 | const jsonContent = < 4 | T extends ZodSchema, 5 | >(schema: T, 6 | description: string, 7 | ) => { 8 | return { 9 | content: { 10 | "application/json": { 11 | schema, 12 | }, 13 | }, 14 | description, 15 | }; 16 | }; 17 | 18 | export default jsonContent; 19 | -------------------------------------------------------------------------------- /src/openapi/helpers/one-of.ts: -------------------------------------------------------------------------------- 1 | import { 2 | OpenApiGeneratorV3, 3 | OpenAPIRegistry, 4 | } from "@asteasolutions/zod-to-openapi"; 5 | 6 | import type { ZodSchema } from "./types.ts"; 7 | 8 | const oneOf = < 9 | T extends ZodSchema, 10 | >(schemas: T[]) => { 11 | const registry = new OpenAPIRegistry(); 12 | 13 | schemas.forEach((schema, index) => { 14 | registry.register(index.toString(), schema); 15 | }); 16 | 17 | const generator = new OpenApiGeneratorV3(registry.definitions); 18 | const components = generator.generateComponents(); 19 | 20 | return components.components?.schemas ? Object.values(components.components!.schemas!) : []; 21 | }; 22 | 23 | export default oneOf; 24 | -------------------------------------------------------------------------------- /src/openapi/helpers/types.ts: -------------------------------------------------------------------------------- 1 | import type { z } from "@hono/zod-openapi"; 2 | 3 | // eslint-disable-next-line ts/ban-ts-comment 4 | // @ts-expect-error 5 | export type ZodSchema = z.ZodUnion | z.AnyZodObject | z.ZodArray; 6 | -------------------------------------------------------------------------------- /src/openapi/index.ts: -------------------------------------------------------------------------------- 1 | export { default as defaultHook } from "./default-hook.js"; 2 | export * as helpers from "./helpers/index.js"; 3 | export * as schemas from "./schemas/index.js"; 4 | -------------------------------------------------------------------------------- /src/openapi/schemas/create-error-schema.ts: -------------------------------------------------------------------------------- 1 | import { z } from "@hono/zod-openapi"; 2 | 3 | import type { ZodSchema } from "../helpers/types.ts"; 4 | 5 | const createErrorSchema = < 6 | T extends ZodSchema, 7 | >(schema: T) => { 8 | const { error } = schema.safeParse( 9 | schema._def.typeName 10 | === z.ZodFirstPartyTypeKind.ZodArray 11 | ? [] 12 | : {}, 13 | ); 14 | return z.object({ 15 | success: z.boolean().openapi({ 16 | example: false, 17 | }), 18 | error: z 19 | .object({ 20 | issues: z.array( 21 | z.object({ 22 | code: z.string(), 23 | path: z.array( 24 | z.union([z.string(), z.number()]), 25 | ), 26 | message: z.string().optional(), 27 | }), 28 | ), 29 | name: z.string(), 30 | }) 31 | .openapi({ 32 | example: error, 33 | }), 34 | }); 35 | }; 36 | 37 | export default createErrorSchema; 38 | -------------------------------------------------------------------------------- /src/openapi/schemas/create-message-object.ts: -------------------------------------------------------------------------------- 1 | import { z } from "@hono/zod-openapi"; 2 | 3 | const createMessageObjectSchema = (exampleMessage: string = "Hello World") => { 4 | return z.object({ 5 | message: z.string(), 6 | }).openapi({ 7 | example: { 8 | message: exampleMessage, 9 | }, 10 | }); 11 | }; 12 | 13 | export default createMessageObjectSchema; 14 | -------------------------------------------------------------------------------- /src/openapi/schemas/get-params-schema.ts: -------------------------------------------------------------------------------- 1 | import { z } from "@hono/zod-openapi"; 2 | 3 | type Validator = "uuid" | "nanoid" | "cuid" | "cuid2" | "ulid"; 4 | 5 | export interface ParamsSchema { 6 | name?: string; 7 | validator?: Validator | undefined; 8 | } 9 | 10 | const examples: Record = { 11 | uuid: "4651e634-a530-4484-9b09-9616a28f35e3", 12 | nanoid: "V1StGXR8_Z5jdHi6B-myT", 13 | cuid: "cjld2cjxh0000qzrmn831i7rn", 14 | cuid2: "tz4a98xxat96iws9zmbrgj3a", 15 | ulid: "01ARZ3NDEKTSV4RRFFQ69G5FAV", 16 | }; 17 | 18 | const getParamsSchema = ({ 19 | name = "id", 20 | validator = "uuid", 21 | }: ParamsSchema) => { 22 | return z.object({ 23 | [name]: z.string()[validator]().openapi({ 24 | param: { 25 | name, 26 | in: "path", 27 | required: true, 28 | }, 29 | required: [name], 30 | example: examples[validator], 31 | }), 32 | }); 33 | }; 34 | 35 | export default getParamsSchema; 36 | -------------------------------------------------------------------------------- /src/openapi/schemas/id-params.ts: -------------------------------------------------------------------------------- 1 | import { z } from "@hono/zod-openapi"; 2 | 3 | const IdParamsSchema = z.object({ 4 | id: z.coerce.number().openapi({ 5 | param: { 6 | name: "id", 7 | in: "path", 8 | required: true, 9 | }, 10 | required: ["id"], 11 | example: 42, 12 | }), 13 | }); 14 | 15 | export default IdParamsSchema; 16 | -------------------------------------------------------------------------------- /src/openapi/schemas/id-uuid-params.ts: -------------------------------------------------------------------------------- 1 | import { z } from "@hono/zod-openapi"; 2 | 3 | const IdUUIDParamsSchema = z.object({ 4 | id: z.string().uuid().openapi({ 5 | param: { 6 | name: "id", 7 | in: "path", 8 | required: true, 9 | }, 10 | required: ["id"], 11 | example: "4651e634-a530-4484-9b09-9616a28f35e3", 12 | }), 13 | }); 14 | 15 | export default IdUUIDParamsSchema; 16 | -------------------------------------------------------------------------------- /src/openapi/schemas/index.ts: -------------------------------------------------------------------------------- 1 | export { default as createErrorSchema } from "./create-error-schema.js"; 2 | export { default as createMessageObjectSchema } from "./create-message-object.js"; 3 | export { default as IdParamsSchema } from "./id-params.js"; 4 | export { default as IdUUIDParamsSchema } from "./id-uuid-params.js"; 5 | export { default as SlugParamsSchema } from "./slug-params.js"; 6 | -------------------------------------------------------------------------------- /src/openapi/schemas/slug-params.test.ts: -------------------------------------------------------------------------------- 1 | import { describe, expect, it } from "vitest"; 2 | 3 | import SlugParamsSchema from "./slug-params.js"; 4 | 5 | describe("slug-params", () => { 6 | it("allows letters", () => { 7 | const slug = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 8 | const { data, error } = SlugParamsSchema.safeParse({ 9 | slug, 10 | }); 11 | expect(data?.slug).toBe(slug); 12 | expect(error).toBeUndefined(); 13 | }); 14 | it("allows numbers", () => { 15 | const slug = "0123456789"; 16 | const { data, error } = SlugParamsSchema.safeParse({ 17 | slug, 18 | }); 19 | expect(data?.slug).toBe(slug); 20 | expect(error).toBeUndefined(); 21 | }); 22 | it("allows numbers and letters", () => { 23 | const slug = "0123456789abcdeABCDE"; 24 | const { data, error } = SlugParamsSchema.safeParse({ 25 | slug, 26 | }); 27 | expect(data?.slug).toBe(slug); 28 | expect(error).toBeUndefined(); 29 | }); 30 | it("allows dashes", () => { 31 | const slug = "test-slug-here"; 32 | const { data, error } = SlugParamsSchema.safeParse({ 33 | slug, 34 | }); 35 | expect(data?.slug).toBe(slug); 36 | expect(error).toBeUndefined(); 37 | }); 38 | it("allows underscores", () => { 39 | const slug = "test_slug_here"; 40 | const { data, error } = SlugParamsSchema.safeParse({ 41 | slug, 42 | }); 43 | expect(data?.slug).toBe(slug); 44 | expect(error).toBeUndefined(); 45 | }); 46 | it("does not allow special characters only", () => { 47 | const slug = "!@#$%^&*()+-="; 48 | const { error } = SlugParamsSchema.safeParse({ 49 | slug, 50 | }); 51 | expect(error).toBeDefined(); 52 | }); 53 | it("does not allow special characters with allowed characters", () => { 54 | const slug = "abc-DEF_ABC-!@#$%^&*()+-="; 55 | const { error } = SlugParamsSchema.safeParse({ 56 | slug, 57 | }); 58 | expect(error).toBeDefined(); 59 | }); 60 | }); 61 | -------------------------------------------------------------------------------- /src/openapi/schemas/slug-params.ts: -------------------------------------------------------------------------------- 1 | import { z } from "@hono/zod-openapi"; 2 | 3 | // Regular expression to validate slug format: alphanumeric, underscores, and dashes 4 | const slugReg = /^[\w-]+$/; 5 | const SLUG_ERROR_MESSAGE = "Slug can only contain letters, numbers, dashes, and underscores"; 6 | 7 | const SlugParamsSchema = z.object({ 8 | slug: z.string() 9 | .regex(slugReg, SLUG_ERROR_MESSAGE) 10 | .openapi({ 11 | param: { 12 | name: "slug", 13 | in: "path", 14 | required: true, 15 | }, 16 | required: ["slug"], 17 | example: "my-cool-article", 18 | }), 19 | }); 20 | 21 | export default SlugParamsSchema; 22 | -------------------------------------------------------------------------------- /test/index.test.ts: -------------------------------------------------------------------------------- 1 | import { describe, expect, it } from "vitest"; 2 | 3 | describe("should", () => { 4 | it("exported", () => { 5 | expect(1).toEqual(1); 6 | }); 7 | }); 8 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ESNext", 4 | "lib": ["ESNext"], 5 | "module": "ESNext", 6 | "moduleResolution": "Bundler", 7 | "resolveJsonModule": true, 8 | "strict": true, 9 | "strictNullChecks": true, 10 | "noEmit": true, 11 | "outDir": "dist", 12 | "removeComments": false, 13 | "esModuleInterop": true, 14 | "skipDefaultLibCheck": true, 15 | "skipLibCheck": true 16 | } 17 | } 18 | --------------------------------------------------------------------------------