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

@genapi/parser

v4.1.0

Published

<!-- automd:badges -->

Readme

@genapi/parser

npm version npm downloads

Parses OpenAPI/Swagger documents into internal data graphs (paths, parameters, schema, etc.) for pipeline compilation and code generation.

Installation

pnpm add @genapi/parser

API

Transform

transformBaseURL(source)

Injects baseURL from config into spec when config.baseURL is set.

Example:

transformBaseURL(spec)
// configRead.config.meta.baseURL and configRead.graphs.variables may be set from spec.host/schemes

transformOperation(options)

Applies config.transform.operation (global) and config.patch.operations (static) to a single operation.

The returned object contains the final name, parameters, and responseType. Note: parameters are always the same array instance passed in; when overridden by a patch, the array is mutated in place (cleared and re-filled) so callers using a const reference remain valid.

Example:

const result = transformOperation({ configRead, name: 'getUserUsingGET', parameters, responseType: 'User' })
// result.name, result.parameters, result.responseType (after transform + patch)

transformQueryParams(name)

Transforms query params for codegen: optional URLSearchParams snippet and option list updates.

Example:

const urlSuffix = transformQueryParams('query', { body: [], options: ['query'], url: '/api' })
// urlSuffix may be '?${querystr}', body/options mutated

transformUrlSyntax(url)

Wraps URL in template literal or string literal and optionally prefixes baseURL.

Example:

transformUrlSyntax('/user/${paths.id}', { baseURL: true }) // '${baseURL}/user/${paths.id}' as template
transformUrlSyntax('/api') // "'/api'"

Traverse

traversePaths(paths, callback)

Walks OpenAPI paths and invokes a callback for each path + method with merged parameters and options.

Example:

traversePaths(spec.paths, (config) => {
  const { path, method, parameters } = config
  // handle each operation
})

createParser(pathHandler)

Creates a unified parser entry that reuses the common flow: parse spec → inject context → transform baseURL/definitions → traverse paths. Presets only need to implement pathHandler, avoiding duplicated parser() and transformPaths boilerplate.

Example:

const parser = createParser((config, ctx) => {
  const meta = parseMethodMetadata(config)
  ctx.functions.push({ name: meta.name, parameters: meta.parameters, body: [] })
})
const configRead = parser(configRead)

fillParameters(options, parameters)

Merges path-level parameters with operation-level parameters; operation params override by name.

Example:

fillParameters(pathItem.get, pathParams) // [...pathParams, ...get.parameters] with dedup by name

isParameter(p: { $ref? })

Type guard: checks if the value is an inline parameter (has name and in), not a $ref.

Example:

if (isParameter(item)) { const { name, in: loc } = item }

isRequiredParameter(fields)

Returns whether any of the given fields are required (and not index signature / any).

Example:

isRequiredParameter([{ name: 'id', required: true, type: 'string' }]) // true
isRequiredParameter([{ name: 'tag', required: false }]) // false

literalFieldsToString(fields)

A single option for codegen: either a bare identifier or a [key, value] pair (or spread).

Example:

'a'
yields
{
a
};
['a',
'b']
yields
{
a:
b
};
['...',
'c']
yields
{
...c
}
Converts an array of LiteralField into a single comma-separated code string for object literals.

Example:

literalFieldsToString([['method', "'GET'"], 'body']) // "method:'GET', body"

parseHeaderCommits(source)

Extracts OpenAPI info (title, description, swagger, version) into comment lines for generated file header.

Example:

const comments = parseHeaderCommits(swaggerSpec)
// ['@title My API', '@swagger 2.0', '@version 1.0']

parseMethodMetadata()

Builds method metadata (name, url template, response type, comments) from path/method and applies transform/patch.

Example:

const meta = parseMethodMetadata(pathMethod)
// meta.name, meta.url, meta.responseType, meta.description

parseMethodParameters(schemas?)

Parses path/method parameters into function options (body, query, path, header, etc.) and provides config for codegen.

Example:

const config = parseMethodParameters({ method: 'get', path: '/user/{id}', parameters }, schemas)
// config.parameters, config.options, config.interfaces

parseOpenapiSpecification(source)

Normalizes input spec to Swagger 2–like shape: passes through Swagger 2 or converts OpenAPI 3.x via swagger2ToSwagger3.

Example:

const spec = parseOpenapiSpecification(openApi3Doc)
// spec has host, basePath, definitions for downstream parser

parseParameterFiled(parameter)

Converts a single OpenAPI parameter into a StatementField (name, type, required, description).

Example:

const field = parseParameterFiled({ name: 'id', in: 'path', type: 'string', required: true })
// { name: 'id', type: 'string', required: true }

parseSchemaType(propertie)

Resolves an OpenAPI schema (or property) to a TypeScript type string; handles $ref, allOf, object, array, primitives.

Example:

parseSchemaType({ type: 'string' }) // 'string'
parseSchemaType({ $ref: '#/definitions/User' }) // 'User'
parseSchemaType({ type: 'array', items: { type: 'number' } }) // 'number[]'

replaceMainext(output?, ext)

Swaps file extension between .ts and .js in output path (e.g. for dual TS/JS presets).

Example:

replaceMainext('src/api/index.ts', 'js') // 'src/api/index.js'

signAnyInter(fields)

Appends an index signature [key: string]: any to the fields array (for open object types).

Example:

signAnyInter(headerFields) // headerFields now has [key: string]: any

spliceEnumDescription(name, enums)

Builds JSDoc @param line for an enum query parameter (allowed values and example query string).

Example:

spliceEnumDescription('status', ['a', 'b']) // "@param status 'a,b' | 'status=a&status=b'"

spliceEnumType(enums)

Builds a TypeScript union array type from enum strings (e.g. 'a' | 'b' for array).

Example:

spliceEnumType(['draft', 'published']) // "('draft' | 'published')[]"

toUndefField(inType, schemas)

Resolves the option key for a parameter location (e.g. 'path' -> 'paths') from schemas or default map.

Example:

toUndefField('query') // 'query'
toUndefField('body', { body: 'data' }) // 'data'

transformBodyStringify(name)

Options for body JSON stringify transform: option list and parameter list.

Replaces a body option with a JSON.stringify(...) literal when the parameter is not FormData/any.

Example:

transformBodyStringify('body', { options: ['body', 'query'], parameters: [{ name: 'body', type: 'CreateDto' }] })
// options may become [['body', 'JSON.stringify(body || {})'], 'query']

transformDefinitions(definitions)

Converts OpenAPI definitions (schemas) to StatementInterface entries and pushes to context interfaces; applies config transform/patch.

Example:

transformDefinitions(spec.definitions)
// inject().interfaces now includes User, Order, etc.

transformFetchBody(url, options, spaceResponseType)

Returns the request/response body snippet for fetch-based clients (json/text/none/void) based on response type.

Example:

transformFetchBody('url', ['method: "GET"'], 'User') // ['const response = await fetch(url, {...})', 'return response.json() as Promise<User>']

transformHeaderOptions(name)

Options for header transform: option list and parameter list.

Injects Content-Type headers (application/json or multipart/form-data) into options and removes standalone 'headers' option when present.

Example:

transformHeaderOptions('headers', { parameters: [...], options: ['headers', 'body'] })
// options get 'headers' replaced with literal { 'Content-Type': 'application/json', ...headers }

transformParameters(parameters, options)

Options for parameter/response type transform (syntax, namespace, generic, infer).

Transforms parameter types and response type for target syntax (TypeScript vs ECMAScript JSDoc); mutates parameters and description.

Example:

const { spaceResponseType } = transformParameters(parameters, { configRead, interfaces, description: [], responseType: 'User', syntax: 'typescript' })

useRefMap(ref)

Extracts the last segment from a $ref path (e.g. '#/definitions/User' -> 'User').

Example:

useRefMap('#/definitions/UserDto') // 'UserDto'

varFiled(name)

Escapes a property name for codegen: wraps in quotes if it contains non-identifier characters.

Example:

varFiled('userId') // 'userId'
varFiled('data-id') // "'data-id'"

varName(string_)

Converts a string or path segments into a valid PascalCase identifier (transliterates, strips non-alphanumeric).

Example:

varName('get /user/info') // 'UserInfo'
varName(['get', 'user', 'id']) // 'UserId'

License

MIT


🤖 auto updated with automd