npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

Iโ€™ve always been into building performant and accessible sites, but lately Iโ€™ve been taking it extremely seriously. So much so that Iโ€™ve been building a tool to help me optimize and monitor the sites that I build to make sure that Iโ€™m making an attempt to offer the best experience to those who visit them. If youโ€™re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, ๐Ÿ‘‹, Iโ€™m Ryan Hefnerย  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If youโ€™re interested in other things Iโ€™m working on, follow me on Twitter or check out the open source projects Iโ€™ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soonโ€“ish.

Open Software & Tools

This site wouldnโ€™t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you ๐Ÿ™

ยฉ 2026 โ€“ย Pkg Stats / Ryan Hefner

swagger-genius

v1.3.9

Published

๐Ÿš€ Instantly generate Swagger/OpenAPI 3.0 API contracts from your TypeScript code. Zero config, supports Zod/Joi/Class-Validator schemas, works with Express/Fastify/NestJS. Perfect swagger.json files in seconds!

Readme

Swagger Genius

Automatically generate comprehensive OpenAPI 3.0 specifications from TypeScript code with zero configuration.

Swagger Genius analyzes your TypeScript codebase to extract API routes, validation schemas, and type definitions, generating production-ready swagger.json files with complete documentation including descriptions, validation rules, and response schemas.

Features

  • Zero Configuration: Works out of the box with sensible defaults
  • Framework Agnostic: Supports Express, Fastify, NestJS, and routing-controllers
  • Multiple Validation Libraries: Zod, Joi, and class-validator support
  • TypeScript Integration: Extracts types, interfaces, and JSDoc comments
  • Cross-File Resolution: Automatically resolves imported schemas and types
  • Complete OpenAPI 3.0: Generates fully compliant specifications
  • Production Ready: Handles complex validation rules and nested schemas

Installation

# Install as development dependency (recommended)
npm install --save-dev swagger-genius

# Or install globally
npm install -g swagger-genius

Quick Start

Initialize configuration:

npx swagger-scan init

Generate API documentation:

npx swagger-scan generate

Your swagger.json file will be generated with complete API documentation.

Configuration

The swagger-scan.json configuration file:

{
  "title": "My API",
  "version": "1.0.0",
  "description": "API documentation",
  "baseUrl": "http://localhost:3000",
  "outputPath": "swagger.json",
  "scanPaths": ["src"],
  "openApiVersion": "3.0.0"
}

Environment Variables

| Variable | Description | |----------|-------------| | SWAGGER_OUTPUT_PATH | Override output file path | | SWAGGER_SCAN_PATHS | Comma-separated list of directories to scan |

Supported Frameworks

Express

import { CreateUserSchema } from './schemas/user';

app.post('/users', validateBody(CreateUserSchema), (req, res) => {
  res.json({ user: req.body });
});

Fastify

import { CreateUserSchema } from './schemas/user';

fastify.post('/users', {
  schema: { body: CreateUserSchema }
}, handler);

NestJS with routing-controllers

import { CreateUserDto } from './dto/user.dto';
import { UserResponse } from './types/user.types';

@JsonController('/api/users')
export class UserController {
  @Post('/')
  @UseBefore(RequestValidatorMiddleware.validate(CreateUserSchema))
  async createUser(@Body() userData: CreateUserDto): Promise<UserResponse> {
    return this.userService.create(userData);
  }
}

Schema Support

Zod Schemas

import { z } from 'zod';

export const CreateUserSchema = z.object({
  /** User's full name */
  name: z.string().min(1).describe('User full name'),
  /** User email address */
  email: z.string().email().describe('User email address'),
  /** User age - must be 18 or older */
  age: z.number().min(18).describe('User age (minimum 18)'),
  /** User phone number */
  phone: z.string().optional().describe('User phone number')
});

Joi Schemas

import Joi from 'joi';

export const CreateUserSchema = Joi.object({
  /** User's full name */
  name: Joi.string().required().description('User full name'),
  /** User email address */
  email: Joi.string().email().description('User email address'),
  /** User age - must be 18 or older */
  age: Joi.number().min(18).description('User age (minimum 18)'),
  /** User phone number */
  phone: Joi.string().description('User phone number')
});

Class-Validator DTOs

import { IsString, IsEmail, IsNumber, Min, IsOptional } from 'class-validator';

export class CreateUserDto {
  /** User's full name */
  @IsString()
  name: string;

  /** User email address */
  @IsEmail()
  email: string;

  /** User age - must be 18 or older */
  @IsNumber()
  @Min(18)
  age: number;

  /** User phone number */
  @IsOptional()
  @IsString()
  phone?: string;
}

TypeScript Type Support

Interfaces

export interface UserResponse {
  /** Unique user identifier */
  id: string;
  /** User's full name */
  name: string;
  /** User email address */
  email: string;
  /** User age */
  age: number;
  /** User phone number */
  phone?: string;
  /** Account creation timestamp */
  createdAt: string;
  /** Last update timestamp */
  updatedAt: string;
}

Type Aliases

export type CreateUserRequest = {
  /** User's full name */
  name: string;
  /** User email address */
  email: string;
  /** User age - must be 18 or older */
  age: number;
  /** User phone number */
  phone?: string;
};

export type UserStatus = 'active' | 'inactive' | 'pending';

Generic Types

export type ApiResponse<T> = {
  /** Response data */
  data: T;
  /** Success indicator */
  success: boolean;
  /** Response message */
  message?: string;
};

Comment Types and Description Sources

Swagger Genius extracts property descriptions from multiple comment formats to generate comprehensive API documentation.

Supported Comment Types

JSDoc Comments (Recommended)

export const CreateUserSchema = z.object({
  /** User's full name */
  name: z.string().min(1),
  /** User email address */
  email: z.string().email(),
  /** User age - must be 18 or older */
  age: z.number().min(18)
});

Schema Method Descriptions

Zod .describe() Method:

export const CreateUserSchema = z.object({
  name: z.string().min(1).describe('User full name'),
  email: z.string().email().describe('User email address'),
  age: z.number().min(18).describe('User age (minimum 18)')
});

Joi .description() Method:

export const CreateUserSchema = Joi.object({
  name: Joi.string().required().description('User full name'),
  email: Joi.string().email().description('User email address'),
  age: Joi.number().min(18).description('User age (minimum 18)')
});

Combined Approach (Best Practice)

export const CreateUserSchema = z.object({
  /** User's full name */
  name: z.string().min(1).describe('User full name'),
  /** User email address */
  email: z.string().email().describe('User email address')
});

Code Quality and Linting

ESLint Configuration

Install and configure JSDoc linting for consistent documentation:

npm install --save-dev eslint-plugin-jsdoc

.eslintrc.json:

{
  "extends": ["plugin:jsdoc/recommended"],
  "rules": {
    "jsdoc/require-description": "error",
    "jsdoc/require-param-description": "error",
    "jsdoc/require-returns-description": "error",
    "jsdoc/check-descriptions": "error",
    "jsdoc/require-jsdoc": [
      "error",
      {
        "require": {
          "FunctionDeclaration": false,
          "MethodDefinition": false,
          "ClassDeclaration": false,
          "ArrowFunctionExpression": false,
          "FunctionExpression": false
        }
      }
    ]
  }
}

Prettier Configuration

.prettierrc:

{
  "printWidth": 80,
  "tabWidth": 2,
  "useTabs": false,
  "semi": true,
  "singleQuote": true,
  "quoteProps": "as-needed",
  "trailingComma": "es5"
}

Pre-commit Hooks

package.json:

{
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.{ts,js}": [
      "eslint --fix",
      "prettier --write",
      "git add"
    ]
  }
}

CLI Commands

# Initialize configuration file
swagger-scan init

# Generate swagger.json
swagger-scan generate

# Custom configuration file
swagger-scan generate -c custom-config.json

# Custom output path
swagger-scan generate -o api-docs.json

# Custom scan paths
swagger-scan generate -p "src,controllers"

# Custom title and version
swagger-scan generate -t "My API" -v "2.0.0"

Generated Output

Request Schema Example

{
  "CreateUserRequest": {
    "type": "object",
    "required": ["name", "email", "age"],
    "properties": {
      "name": {
        "type": "string",
        "minLength": 1,
        "description": "User's full name"
      },
      "email": {
        "type": "string",
        "format": "email",
        "description": "User email address"
      },
      "age": {
        "type": "number",
        "minimum": 18,
        "description": "User age (minimum 18)"
      },
      "phone": {
        "type": "string",
        "description": "User phone number"
      }
    }
  }
}

Complete API Endpoint

{
  "/api/users": {
    "post": {
      "summary": "Create user",
      "description": "Create a new user with the provided information",
      "requestBody": {
        "required": true,
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/CreateUserRequest"
            }
          }
        }
      },
      "responses": {
        "201": {
          "description": "User created successfully",
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UserResponse"
              }
            }
          }
        },
        "400": {
          "description": "Validation error",
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ErrorResponse"
              }
            }
          }
        }
      }
    }
  }
}

Cross-File Schema Resolution

Swagger Genius automatically resolves schemas and types across multiple files:

controllers/user.controller.ts:

import { CreateUserSchema, UserResponse } from '../schemas/user.schemas';
import { RequestValidatorMiddleware } from '../middleware/validation';

@JsonController('/api/users')
export class UserController {
  @Post('/')
  @UseBefore(RequestValidatorMiddleware.validate(CreateUserSchema))
  async createUser(@Body() userData: CreateUserDto): Promise<UserResponse> {
    return this.userService.create(userData);
  }
}

schemas/user.schemas.ts:

export const CreateUserSchema = z.object({
  /** User's full name */
  name: z.string().describe('User name'),
  /** User email address */
  email: z.string().email().describe('User email')
});

export interface UserResponse {
  /** Unique user identifier */
  id: string;
  /** User's full name */
  name: string;
  /** User email address */
  email: string;
}

Programmatic Usage

import { SwaggerScanner } from 'swagger-genius';

const scanner = new SwaggerScanner();

await scanner.generateSwagger({
  title: 'My API',
  version: '1.0.0',
  outputPath: 'swagger.json',
  scanPaths: ['src']
});

Troubleshooting

Descriptions Not Appearing

Check Comment Format:

// Incorrect - single asterisk
/* User name */
name: z.string()

// Correct - double asterisk JSDoc
/** User name */
name: z.string()

Verify Schema Export:

// Incorrect - not exported
const CreateUserSchema = z.object({...});

// Correct - exported
export const CreateUserSchema = z.object({...});

Check Scan Paths:

{
  "scanPaths": [
    "src/schemas",
    "src/controllers",
    "src/types"
  ]
}

Validation Not Detected

Verify Middleware Pattern:

// Correct pattern
@Post('/')
@UseBefore(RequestValidatorMiddleware.validate(CreateUserSchema))
async createUser(@Body() userData: CreateUserDto) {}

Check Import Statements:

// Ensure proper imports
import { CreateUserSchema } from '@/lib/validations';
import { RequestValidatorMiddleware } from '@/middleware/validation';

Debug Mode

# Enable debug logging
DEBUG=swagger-scan npx swagger-scan generate

# Verbose output
npx swagger-scan generate --verbose

What Gets Generated

  • Request body schemas with validation rules
  • Query parameters with type information
  • Path parameters with descriptions
  • Header parameters and validation
  • Response schemas from TypeScript return types
  • Nested objects and array definitions
  • Optional and required field specifications
  • Format validation (email, date, etc.)
  • Comprehensive error responses

License

MIT License - see LICENSE file for details.

Contributing

Contributions are welcome! Please read our contributing guidelines and submit pull requests to our GitHub repository.

Support

For issues, feature requests, or questions, please visit our GitHub repository or contact our support team.