@genapi/parser

中文文档
4.1.4发布于 2026/07/29MITTypeScriptES Module构建来源已验证近 30 天下载 3546
原始使用文档
文档目录34 节
  1. Installation
  2. API
  3. Transform
  4. transformBaseURL(source)
  5. transformOperation(options)
  6. transformQueryParams(name)
  7. transformUrlSyntax(url)
  8. Traverse
  9. traversePaths(paths, callback)
  10. createParser(pathHandler)
  11. fillParameters(options, parameters)
  12. isParameter(p: { $ref? })
  13. isRequiredParameter(fields)
  14. literalFieldsToString(fields)
  15. parseHeaderCommits(source)
  16. parseMethodMetadata()
  17. parseMethodParameters(schemas?)
  18. parseOpenapiSpecification(source)
  19. parseParameterFiled(parameter)
  20. parseSchemaType(propertie)
  21. replaceMainext(output?, ext)
  22. signAnyInter(fields)
  23. spliceEnumDescription(name, enums)
  24. spliceEnumType(enums)
  25. toUndefField(inType, schemas)
  26. transformBodyStringify(name)
  27. transformDefinitions(definitions)
  28. transformFetchBody(url, options, spaceResponseType)
  29. transformHeaderOptions(name)
  30. transformParameters(parameters, options)
  31. useRefMap(ref)
  32. varFiled(name)
  33. varName(string_)
  34. License

@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

版本与发布记录

@genapi/parser 共发布 19 个版本,首次发布于 2025/03/28;过去 12 个月发布了 6 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
4.1.4latest2026/07/293 个月前
4.1.32026/07/233 个月前
4.1.22026/07/233 个月前
4.1.12026/05/215 个月前
4.1.02026/02/099 个月前
4.0.02026/02/099 个月前

关于 @genapi/parser 的常见问题

如何安装 @genapi/parser?

在项目目录运行 npm install @genapi/parser,或使用 pnpm add / yarn add / bun add。

@genapi/parser 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@genapi/parser 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@genapi/parser 可以商用吗?

@genapi/parser 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@genapi/parser 的下载量有多少?

根据 npm 官方下载统计,@genapi/parser 在 2026/10/16 – 2026/11/14 这 30 天内被下载 3,546 次,日均约 118 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@genapi/parser 还在维护吗?

最新版本 4.1.4 发布于 2026/07/29(3 个月前);至今共发布 19 个版本,其中过去 12 个月发布了 6 个;首次发布于 2025/03/28。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。