本文へ移動

Hono Docs ​

Hono のルートの型定義から、OpenAPI 3.0 仕様と TypeScript の型スナップショットを自動生成

Hono Docs は、Hono の OpenAPI ドキュメントを自動生成します。

プロジェクトのルートに設定ファイルを作成(hono-docs.ts) ​

ts
import { defineConfig } from '@rcmade/hono-docs'

export default defineConfig({
  tsConfigPath: './tsconfig.json',
  openApi: {
    openapi: '3.0.0',
    info: { title: 'My API', version: '1.0.0' },
    servers: [{ url: 'http://localhost:3000/api' }],
  },
  outputs: {
    openApiJson: './openapi/openapi.json',
  },
  apis: [
    {
      name: 'Auth Routes',
      apiPrefix: '/auth', // This will be prepended to all `api` values below
      appTypePath: 'src/routes/authRoutes.ts', // Path to your AppType export

      api: [
        // ✅ Custom OpenAPI metadata for the GET /auth/u/{id} endpoint
        {
          api: '/u/{id}', // Final route = /auth/u/{id}
          method: 'get',
          summary: 'Fetch user by ID', // Optional: title shown in docs
          description:
            'Returns a user object based on the provided ID.',
          tag: ['User'],
        },

        // ✅ Another example with metadata for GET /auth
        {
          api: '/', // Final route = /auth/
          method: 'get',
          summary: 'Get current user',
          description:
            "Returns the currently authenticated user's information.",
          tag: ['User Info'],
        },
      ],
    },
  ],
})

ルート定義と AppType ​

このライブラリは、ルートファイルで単一の AppType をエクスポートすることで、変更されたルートのみの更新をサポートします。次のエクスポートが必須です。

ts
export type AppType = typeof yourRoutesVariable

例:

ts
// src/routes/userRoutes.ts
import { Hono } from 'hono'
import * as z from 'zod'

export const userRoutes = new Hono()
  .get('/u/:id', (c) => {
    /* … */
  })
  .post('/', async (c) => {
    /* … */
  })
// Must add AppType
export type AppType = typeof userRoutes
export default userRoutes

Hono アプリケーションにマウントします。

ts
// src/routes/docs.ts
import { Hono } from 'hono'
import { Scalar } from '@scalar/hono-api-reference'
import fs from 'node:fs/promises'
import path from 'node:path'

const docs = new Hono()
  .get(
    '/',
    Scalar({
      url: '/api/docs/open-api',
      theme: 'kepler',
      layout: 'modern',
      defaultHttpClient: { targetKey: 'js', clientKey: 'axios' },
    })
  )
  .get('/open-api', async (c) => {
    const raw = await fs.readFile(
      path.join(process.cwd(), './openapi/openapi.json'),
      'utf-8'
    )
    return c.json(JSON.parse(raw))
  })

export type AppType = typeof docs
export default docs

/api/docs にアクセスすると UI が表示され、/api/docs/open-api で JSON が提供されます。

設定を作成したら、次のコマンドで仕様を生成します。

bash
npx @rcmade/hono-docs generate --config ./hono-docs.ts

CLI の使い方 ​

text
Usage: @rcmade/hono-docs generate --config <your hono-docs.ts path (default root/hono-docs.ts)>

Options:
  -c, --config   Path to your config file (TS or JS)        [string] [required]
  -h, --help     Show help                                 [boolean]

例 ​

最小構成については examples/basic-app/ を参照してください。

MIT ライセンスで公開されています。