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 🙏

© 2025 – Pkg Stats / Ryan Hefner

difisoft-nodejs-22-common-openapi-generator

v1.0.2

Published

TypeScript library for generating OpenAPI specifications from endpoint definitions

Downloads

35

Readme

Common OpenAPI Generator

A TypeScript library for generating OpenAPI 3.0 specifications from endpoint definitions with support for OAuth2 security schemes, scope management, and customizable generation.

Features

V2 - TypeScript Compiler API (Recommended)

  • 🚀 IDE-like Analysis: Uses TypeScript Compiler API for accurate type analysis
  • 🔍 Method Signature Analysis: Automatically extracts input/output types from method signatures
  • 📁 Project-aware: Analyzes entire TypeScript projects with proper import resolution
  • 🎯 Path Parameter Detection: Automatically detects path parameters from URI patterns like {id}
  • 🔍 Query Parameter Extraction: Extracts query parameters for GET/DELETE methods
  • 📝 Request Body Detection: Automatically determines when request body is needed
  • 🛠️ Zero Configuration: Works out of the box with sensible defaults
  • 🔧 Type-safe: Full TypeScript support with comprehensive type definitions

V1 - Legacy (Regex-based)

  • 🚀 Easy Integration: Simple API for generating OpenAPI specifications
  • 🔐 OAuth2 Support: Built-in OAuth2 security scheme generation with scope management
  • 🎯 Flexible Configuration: Highly configurable with custom generators and schemas
  • 📝 TypeScript Support: Full TypeScript support with comprehensive type definitions
  • 🛠️ CLI Interface: Command-line interface for build-time generation
  • 🔧 Extensible: Support for custom generators and schema definitions
  • 📊 Auto-detection: Automatic detection of resources and generation of appropriate schemas
  • 🔍 RequestHandler Integration: Seamless integration with common-kafkajs RequestHandler
  • 📄 TypeScript File Support: Directly processes TypeScript RequestHandler files without compilation
  • 🧠 Method Signature Analysis: Automatically analyzes method signatures for better schema generation
  • Zero Configuration: Works out of the box with sensible defaults

Installation

# Using yarn (recommended)
yarn add common-openapi

# Using npm
npm install common-openapi

Quick Start

V2 - TypeScript Compiler API (Recommended)

import { OpenApiGeneratorV2 } from 'common-openapi';

// Create generator with project path
const generator = new OpenApiGeneratorV2('/path/to/your/project');

// Generate from RequestHandler (automatically analyzes TypeScript)
await generator.generateAndSave(
  '/path/to/RequestHandler.ts',
  './openapi.json'
);

V1 - Legacy Usage

import { OpenApiGenerator } from 'common-openapi';

// Create generator with no configuration (uses sensible defaults)
const generator = new OpenApiGenerator();

// Add endpoints
generator.addEndpoints([
  {
    uri: 'get:/api/v1/users',
    handler: 'getUsers'
  },
  {
    uri: 'post:/api/v1/users',
    handler: 'createUser'
  }
]);

// Generate and save OpenAPI specification
await generator.generateAndSave('openapi.json');

With Custom Configuration

import { OpenApiGenerator } from 'common-openapi';

// Create generator with custom configuration
const generator = new OpenApiGenerator({
  info: {
    title: 'My API',
    version: '1.0.0',
    description: 'My awesome API'
  },
  scopeGroup: 'MyService'
});

// Add endpoints
generator.addEndpoints([
  {
    uri: 'get:/api/v1/users',
    handler: 'getUsers'
  },
  {
    uri: 'post:/api/v1/users',
    handler: 'createUser'
  }
]);

// Generate and save OpenAPI specification
await generator.generateAndSave('openapi.json');

Using with RequestHandler (from common-kafkajs)

import { OpenApiGenerator } from 'common-openapi';
import { Container } from 'typedi';
import RequestHandler from './RequestHandler';

// Configure container and get RequestHandler
const requestHandler = Container.get(RequestHandler);

// Create generator
const generator = new OpenApiGenerator({
  info: {
    title: 'Favourist Manager API',
    version: '1.0.0',
    description: 'API for managing user favourites'
  },
  scopeGroup: 'FavouristManager'
});

// Generate OpenAPI specification directly from RequestHandler
// This automatically analyzes method signatures and generates proper schemas
await generator.generateFromRequestHandlerAndSave(requestHandler, 'openapi.json');

Using with TypeScript RequestHandler Files

The CLI supports directly processing TypeScript RequestHandler files without compilation:

# Generate from TypeScript RequestHandler file
npx common-openapi --endpoints src/RequestHandler.ts --output openapi.json

# With configuration
npx common-openapi --config config.json --endpoints src/RequestHandler.ts --output openapi.json

# Using yarn
yarn common-openapi --endpoints src/RequestHandler.ts --output openapi.json

The library automatically:

  • Parses the TypeScript file without requiring compilation
  • Extracts the matchingList() method from the RequestHandler class
  • Generates OpenAPI specification from the endpoints
  • Supports both .ts and .js files

Advanced RequestHandler Integration

The library can automatically analyze your RequestHandler's method signatures to generate more accurate OpenAPI specifications:

import { OpenApiGenerator } from 'common-openapi';
import { Container } from 'typedi';
import RequestHandler from './RequestHandler';

// Configure your application
configureLogger(config.logger.config);
configureContainer();

// Get RequestHandler from container
const requestHandler = Container.get(RequestHandler);

// Create generator with detailed configuration
const generator = new OpenApiGenerator({
  info: {
    title: 'My Service API',
    version: '1.0.0',
    description: 'API generated from RequestHandler with method signature analysis'
  },
  scopeGroup: 'MyService',
  schemas: {
    // Define your custom schemas
    User: {
      type: 'object',
      properties: {
        id: { type: 'integer' },
        username: { type: 'string' },
        email: { type: 'string', format: 'email' }
      },
      required: ['id', 'username', 'email']
    }
  }
});

// Generate comprehensive OpenAPI specification
await generator.generateFromRequestHandlerAndSave(requestHandler, 'openapi.json');

CLI Usage

V2 - TypeScript Compiler API (Recommended)

# Generate from RequestHandler with TypeScript analysis
npx generate-openapi-v2 --request-handler ./src/RequestHandler.ts --output ./openapi.json

# With custom project path
npx generate-openapi-v2 --request-handler ./src/RequestHandler.ts --output ./openapi.json --project-path ./src

# With configuration file
npx generate-openapi-v2 --request-handler ./src/RequestHandler.ts --output ./openapi.json --config ./config.json

# Show help
npx generate-openapi-v2 --help

V1 - Legacy CLI

# Generate with configuration file
generate-openapi --config config.json --output openapi.json

# Generate with endpoints file
generate-openapi --endpoints endpoints.json --output openapi.json

# Generate with both config and endpoints
generate-openapi --config config.json --endpoints endpoints.json

# Show help
generate-openapi --help

Package.json Script

{
  "scripts": {
    "generate-openapi": "generate-openapi --config config.json --output openapi.json"
  }
}

Configuration

The configuration is optional. If you don't provide any configuration, the library will use sensible defaults:

Default Configuration

When no configuration is provided, the library uses these defaults:

{
  info: {
    title: 'API',
    version: '1.0.0',
    description: 'Generated API specification'
  },
  servers: [
    {
      url: 'http://localhost:3000',
      description: 'Development server'
    }
  ],
  scopeGroup: 'default',
  securitySchemes: {
    default: {
      type: 'oauth2',
      flows: {
        clientCredentials: {
          tokenUrl: '/oauth2/token'
        }
      }
    }
  },
  tags: [],
  schemas: {},
  customGenerators: {}
}

Generator Configuration

interface OpenApiGeneratorConfig {
  info: {
    title: string;
    version: string;
    description?: string;
    contact?: {
      name?: string;
      email?: string;
      url?: string;
    };
    license?: {
      name: string;
      url?: string;
    };
  };
  servers?: Array<{
    url: string;
    description?: string;
  }>;
  scopeGroup?: string;
  defaultSecurityScheme?: string;
  securitySchemes?: Record<string, any>;
  tags?: Array<{
    name: string;
    description?: string;
  }>;
  schemas?: Record<string, any>;
  customGenerators?: {
    scopeName?: (method: string, path: string, config?: any) => string;
    operationId?: (method: string, path: string, config?: any) => string;
    summary?: (method: string, path: string, config?: any) => string;
    description?: (method: string, path: string, config?: any) => string;
    tags?: (method: string, path: string, config?: any) => string[];
  };
}

Endpoint Configuration

interface ApiEndpoint {
  uri: string;                    // e.g., "get:/api/v1/users"
  handler: any;                   // Handler function or name
  scopeName?: string;             // Custom scope name
  scopeGroup?: string;            // Custom scope group
  summary?: string;               // Custom summary
  description?: string;           // Custom description
  tags?: string[];                // Custom tags
  parameters?: EndpointParameter[];
  requestBody?: EndpointRequestBody;
  responses?: EndpointResponses;
  security?: EndpointSecurity[];
  deprecated?: boolean;
}

Examples

Minimal Example (No Configuration)

import { OpenApiGenerator } from 'common-openapi';

// Create generator with no configuration
const generator = new OpenApiGenerator();

// Add endpoints
generator.addEndpoints([
  {
    uri: 'get:/api/v1/users',
    handler: 'getUsers'
  },
  {
    uri: 'post:/api/v1/users',
    handler: 'createUser'
  }
]);

// Generate OpenAPI specification
await generator.generateAndSave('openapi.json');

Example Configuration File

{
  "info": {
    "title": "Favourist Manager API",
    "version": "1.0.0",
    "description": "API for managing user favourites",
    "contact": {
      "name": "API Support",
      "email": "[email protected]"
    }
  },
  "servers": [
    {
      "url": "http://localhost:3000",
      "description": "Development server"
    }
  ],
  "scopeGroup": "FavouristManager",
  "securitySchemes": {
    "default": {
      "type": "oauth2",
      "flows": {
        "clientCredentials": {
          "tokenUrl": "/oauth2/token"
        }
      }
    }
  },
  "tags": [
    {
      "name": "Favourites",
      "description": "Favourite management operations"
    }
  ]
}

Example Endpoints File

[
  {
    "uri": "get:/api/v1/favourites",
    "handler": "getFavourites",
    "summary": "Get all favourites",
    "tags": ["Favourites"]
  },
  {
    "uri": "post:/api/v1/favourites",
    "handler": "createFavourite",
    "summary": "Create a new favourite",
    "tags": ["Favourites"]
  },
  {
    "uri": "get:/api/v1/favourites/:id",
    "handler": "getFavouriteById",
    "summary": "Get favourite by ID",
    "tags": ["Favourites"]
  }
]

API Reference

OpenApiGenerator

Constructor

constructor(config: OpenApiGeneratorConfig)

Methods

  • addEndpoints(endpoints: ApiEndpoint[]): void - Add multiple endpoints
  • addEndpoint(endpoint: ApiEndpoint): void - Add a single endpoint
  • clearEndpoints(): void - Clear all endpoints
  • generateOpenApiSpec(): OpenApiSpec - Generate OpenAPI specification
  • generateAndSave(outputPath: string): Promise<void> - Generate and save to file
  • getConfig(): OpenApiGeneratorConfig - Get current configuration
  • updateConfig(newConfig: Partial<OpenApiGeneratorConfig>): void - Update configuration
  • getEndpoints(): ApiEndpoint[] - Get current endpoints

Utilities

EndpointParser

  • parseUri(uri: string): ParsedEndpoint - Parse endpoint URI
  • generateScopeName(method: string, path: string, scopeGroup?: string): string - Generate scope name
  • generateOperationId(method: string, path: string): string - Generate operation ID
  • generateSummary(method: string, path: string): string - Generate summary
  • generateDescription(method: string, path: string, serviceName?: string): string - Generate description
  • generateTags(path: string): string[] - Generate tags

SchemaGenerator

  • generateErrorResponseSchema(): OpenApiSchema - Generate error response schema
  • generateHealthCheckSchema(): OpenApiSchema - Generate health check schema
  • generatePaginationSchema(): OpenApiSchema - Generate pagination schema
  • generateResourceSchema(resourceName: string, properties: Record<string, any>): OpenApiSchema - Generate resource schema
  • generateArrayResponseSchema(itemSchema: OpenApiSchema | string): OpenApiSchema - Generate array response schema
  • generatePaginatedResponseSchema(itemSchema: OpenApiSchema | string): OpenApiSchema - Generate paginated response schema

Advanced Usage

Custom Generators

const generator = new OpenApiGenerator({
  // ... other config
  customGenerators: {
    scopeName: (method, path, config) => {
      return `${config.scopeGroup}${method}${path.split('/').pop()}`;
    },
    operationId: (method, path) => {
      return `${method}_${path.replace(/\//g, '_')}`;
    },
    summary: (method, path) => {
      return `${method.toUpperCase()} ${path}`;
    }
  }
});

Custom Schemas

const generator = new OpenApiGenerator({
  // ... other config
  schemas: {
    CustomUser: {
      type: 'object',
      properties: {
        id: { type: 'integer' },
        name: { type: 'string' },
        email: { type: 'string', format: 'email' }
      },
      required: ['id', 'name', 'email']
    }
  }
});

Security Configuration

const generator = new OpenApiGenerator({
  // ... other config
  securitySchemes: {
    oauth2: {
      type: 'oauth2',
      flows: {
        clientCredentials: {
          tokenUrl: '/oauth2/token',
          scopes: {
            'read:users': 'Read user information',
            'write:users': 'Write user information'
          }
        }
      }
    },
    apiKey: {
      type: 'apiKey',
      name: 'X-API-Key',
      in: 'header'
    }
  }
});

Integration with Build Process

Using with TypeScript

// scripts/generate-openapi.ts
import 'reflect-metadata';
import { configureContainer } from '../src/config/container';
import { Container } from 'typedi';
import { configureLogger, logger } from 'common-model';
import { OpenApiGenerator } from 'common-openapi';
import RequestHandler from '../src/consumers/RequestHandler';

async function generateOpenApi() {
  try {
    // Configure container and logger
    configureLogger(config.logger.config);
    configureContainer();
    
    // Get RequestHandler and endpoints
    const requestHandler = Container.get(RequestHandler);
    const endpoints = requestHandler.matchingList();
    
    // Create generator
    const generator = new OpenApiGenerator({
      info: {
        title: 'My API',
        version: '1.0.0',
        description: 'My awesome API'
      },
      scopeGroup: 'MyService'
    });
    
    // Add endpoints and generate
    generator.addEndpoints(endpoints);
    await generator.generateAndSave('openapi.json');
    
    logger.info('OpenAPI specification generated successfully');
  } catch (error) {
    logger.error('Failed to generate OpenAPI specification:', error);
    process.exit(1);
  }
}

generateOpenApi();

Package.json Scripts

{
  "scripts": {
    "build": "yarn clean && tsc && tsc-alias && yarn generate-openapi",
    "generate-openapi": "npx ts-node -r tsconfig-paths/register scripts/generate-openapi.ts"
  }
}

Development

Building

# Install dependencies
yarn install

# Build the library
yarn build

# Run tests
yarn test

# Lint code
yarn lint

# Format code
yarn format

Project Structure

src/
├── interfaces/          # TypeScript interfaces
│   ├── OpenApiSpec.ts
│   └── EndpointConfig.ts
├── generators/          # Generation utilities
│   ├── PathGenerator.ts
│   └── SecurityGenerator.ts
├── utils/              # Utility functions
│   ├── EndpointParser.ts
│   └── SchemaGenerator.ts
├── cli/                # CLI interface
│   └── cli.ts
├── OpenApiGenerator.ts # Main generator class
└── index.ts           # Main export file

License

MIT

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

Support

For support and questions, please contact the development team or create an issue in the repository.