@cerios/openapi-core
v1.1.0
Published
Core utilities for parsing and processing OpenAPI specifications. Shared foundation for OpenAPI code generators.
Readme
@cerios/openapi-core
Core utilities for parsing and processing OpenAPI specifications. This package provides the shared foundation for OpenAPI code generators.
Installation
npm install @cerios/openapi-coreFeatures
- 🔍 OpenAPI Parsing - Parse OpenAPI 3.0/3.1 YAML and JSON specifications
- 🔗 Reference Resolution - Resolve
$refreferences throughout the spec - 🏷️ Operation Filtering - Filter operations by tags, paths, and methods
- 🛠️ Utility Functions - Common utilities for schema processing
- 📦 Batch Execution - Parallel and sequential execution of generators
- 🧪 Test Fixtures - Shared OpenAPI fixtures for testing
Usage
import {
shouldIncludeOperation,
toPascalCase,
toCamelCase,
resolveRefName,
LRUCache,
loadOpenAPISpec,
} from "@cerios/openapi-core";
// Load and parse an OpenAPI spec
const spec = await loadOpenAPISpec("openapi.yaml");
// Extract schema name from $ref
const schemaName = resolveRefName("#/components/schemas/User"); // "User"
// Filter operations
const include = shouldIncludeOperation(operation, path, method, {
includeTags: ["users"],
excludePaths: ["/internal/*"],
});
// Name utilities
const className = toPascalCase("user-profile"); // "UserProfile"
const methodName = toCamelCase("get-user-by-id"); // "getUserById"API Reference
Types
OpenAPISpec- OpenAPI specification structureOpenAPISchema- Schema definition structureOpenAPIParameter- Parameter definitionOpenAPIRequestBody- Request body definitionOpenAPIResponse- Response definitionOperationFilters- Operation filtering optionsExecutionMode- Parallel/sequential execution modeBaseGeneratorOptions- Base options for all generators
Spec Parsing
loadOpenAPISpec()- Load and parse an OpenAPI spec fileloadOpenAPISpecCached()- Load spec with LRU caching
Reference Resolution
resolveRefName()- Extract name from$refpathresolveRequestBodyRef()- Resolve request body referencesresolveResponseRef()- Resolve response referencesmergeParameters()- Merge path and operation parameters
Operation Filtering
shouldIncludeOperation()- Check if operation matches filtersvalidateFilters()- Validate filter configurationcreateFilterStatistics()- Create filter statistics trackerformatFilterStatistics()- Format statistics for display
Name Utilities
toPascalCase()- Convert string to PascalCasetoCamelCase()- Convert string to camelCaseresolveRefName()- Extract name from $ref pathgetOperationName()- Get operation name from operationId or pathgenerateMethodNameFromPath()- Generate method name from pathcapitalize()- Capitalize first letter
Method Naming
pathToPascalCase()- Convert path to PascalCase (e.g.,/users/{userId}→UsersByUserId)generateHttpMethodName()- Generate method name from HTTP method + pathextractPathParams()- Extract parameter names from path templatesanitizeOperationId()- Sanitize operationId for TypeScriptsanitizeParamName()- Sanitize parameter name for TypeScript
Schema Traversal
extractSchemaRefs()- Extract all$refnames from schema treeexpandTransitiveReferences()- Expand to include transitively referenced schemasdetectCircularReferences()- Detect circular reference chainstopologicalSortSchemas()- Sort schemas by dependenciesanalyzeSchemaUsage()- Analyze request/response context usageclassifyEnumType()- Classify enum values as string/number/boolean/mixed
Header Filters
shouldIgnoreHeader()- Check if header matches ignore patternsfilterHeaders()- Filter headers excluding ignored onesvalidateIgnorePatterns()- Validate and warn about unmatched patterns
Pattern Utilities
stripPrefix()- Strip prefix from schema namesstripSuffix()- Strip suffix from stringsstripAffixes()- Strip both prefix and suffixstripPathPrefix()- Strip prefix from paths (supports glob)isGlobPattern()- Check if string is a glob pattern
String Utilities
escapeJSDoc()- Escape JSDoc contentescapeDescription()- Escape description textescapePattern()- Escape regex patterngetPrimaryType()- Get primary type from schemahasMultipleTypes()- Check if schema has multiple typesisNullable()- Check if schema is nullable
Content Type Utilities
getResponseParseMethod()- Determine response parsing method (json, text, blob, etc.)
Config Loader
createConfigLoader()- Factory for type-safe config loaders with cosmiconfig + Zod validationmergeCliWithConfig()- Merge CLI options with config values (CLI takes precedence)
CLI Utilities
findSpecFiles()- Find OpenAPI spec files in directorygetRandomCeriosMessage()- Get random CLI greeting message
Classes
LRUCache- Least Recently Used cache implementationGeneratorError- Base error class for generatorsSpecValidationError- OpenAPI spec validation errorsFileOperationError- File I/O errorsConfigValidationError- Configuration errorsCircularReferenceError- Circular reference detection errorsCliOptionsError- CLI options validation errorsSchemaGenerationError- Schema generation errors
Batch Execution
executeBatch()- Execute multiple generatorsgetBatchExitCode()- Calculate exit code from resultsGenerator- Interface for generator implementations
License
MIT
