@asyncapi/protobuf-schema-parser

中文文档
4.0.0发布于 2026/11/02Apache-2.0TypeScriptESM + CJS构建来源已验证近 30 天下载 129.4万

An AsyncAPI schema parser for Protocol Buffers data types.

原始使用文档
文档目录15 节
  1. Overview
  2. Installation
  3. Usage
  4. Supported input
  5. How it works
  6. Scalar type formats
  7. Comments and annotations
  8. Per field annotation
  9. Per message annotation
  10. Head annotation
  11. Head annotation "Option"
  12. Supported validation frameworks
  13. Development
  14. Contributing
  15. License

ProtoBuff Data Types Schema Parser

npm version License Node

A schema parser for Protocol Buffers data types. It plugs into @asyncapi/parser and lets you embed .proto message definitions directly in the payload (or schema) of an AsyncAPI document. During parsing, the Protobuf definition is converted into an AsyncAPI (JSON Schema based) schema so the rest of the AsyncAPI tooling can work with it like any other message payload.

Overview

AsyncAPI messages can carry payloads described in different schema languages. @asyncapi/parser delegates any payload whose schemaFormat it does not understand natively to a registered schema parser. This package is the schema parser for Protocol Buffers: you register it once, and every message payload tagged with a Protobuf schemaFormat is parsed and expanded in place into an equivalent AsyncAPI schema.

  • Works with Protobuf 2 and Protobuf 3 schemas.
  • Registers for the schema formats application/vnd.google.protobuf;version=2 and application/vnd.google.protobuf;version=3.
  • Maps Protobuf messages, scalars, enums, repeated fields, oneof and nested types to JSON Schema.
  • Understands leading comments as descriptions and a set of @-annotations for validation, defaults and examples.
  • Optionally maps protoc-gen-validate and protovalidate rules to JSON Schema validators.
  • Browser-compatible and ships both CommonJS and ES module builds.

There is no strict distinction between Protobuf 2 and 3. Declaring schemaFormat as application/vnd.google.protobuf;version=2 while providing a proto3 schema (or vice versa) does not by itself cause an error.

Version >= 2.0.0 of this package requires @asyncapi/parser >= 2.0.0; the 3.x line targets @asyncapi/parser >= 3.6.0.

Installation

npm install @asyncapi/protobuf-schema-parser
# or
yarn add @asyncapi/protobuf-schema-parser

@asyncapi/parser is required to use this package. Requires Node.js >= 18.

Usage

Create a Parser, register the Protobuf schema parser on it, then parse an AsyncAPI document that uses a Protobuf schemaFormat. The Protobuf source goes into the message payload as a string.

import { Parser } from '@asyncapi/parser';
import { ProtoBuffSchemaParser } from '@asyncapi/protobuf-schema-parser';

const parser = new Parser();
parser.registerSchemaParser(ProtoBuffSchemaParser());

const asyncapiWithProto = `
asyncapi: 2.0.0
info:
  title: Example with ProtoBuff
  version: 0.1.0
channels:
  example:
    publish:
      message:
        schemaFormat: 'application/vnd.google.protobuf;version=3'
        payload: |
          message Point {
            required int32 x = 1;
            required int32 y = 2;
            optional string label = 3;
          }

          message Line {
            required Point start = 1;
            required Point end = 2;
            optional string label = 3;
          }
`;

const { document, diagnostics } = await parser.parse(asyncapiWithProto);

The same works with CommonJS:

const { Parser } = require('@asyncapi/parser');
const { ProtoBuffSchemaParser } = require('@asyncapi/protobuf-schema-parser');

const parser = new Parser();
parser.registerSchemaParser(ProtoBuffSchemaParser());

Notes:

  • ProtoBuffSchemaParser is exported both as a named export and as the default export. Call it to obtain the parser instance, then pass that instance to registerSchemaParser.
  • Place your Protobuf schema as a string in the message payload (AsyncAPI 2.x) or in the schema object's schema keyword (AsyncAPI 3.x) to get it parsed. See the fixtures under test/documents for both variants.
  • After parsing, the message payload in document is the converted AsyncAPI schema.

Supported input

  • Protobuf 2 and Protobuf 3 message definitions.
  • The two registered schema formats:
    • application/vnd.google.protobuf;version=2
    • application/vnd.google.protobuf;version=3

References are not supported:

  • No support for $ref inside the Protobuf payload.
  • No support for import, with the exception of the bundled well-known definitions:
    • google/protobuf/* (provided by protobufjs)
    • google/type/* (bundled with this package)
    • the validation definitions validate/validate.proto and buf/validate/validate.proto

Any other import throws an error during parsing.

How it works

Each AsyncAPI document may contain several message payloads. For every payload whose schemaFormat matches one of the registered MIME types, the parser hands the raw Protobuf string to the converter, which uses protobufjs to parse it and then walks the message tree, emitting a JSON Schema based AsyncAPI schema.

Because a JSON Schema has a single root, the converter first determines the root message: the message that is not referenced as a field type by any other message. If several candidates remain, annotate the intended root with @RootNode; otherwise parsing fails with Found more than one root proto messages. If no root can be found, parsing fails with Not found a root proto messages.

The main mapping rules:

Protobuf constructAsyncAPI / JSON Schema output
message{ "title": <name>, "type": "object", "properties": { ... } }, plus a required list
Scalar field (e.g. int32, string)type + format from the scalar type map, plus x-primitive (and minimum/maximum for numeric types)
Message-typed fieldThe referenced message compiled inline, plus x-type set to the Protobuf type name
enum{ "type": "string", "enum": [<names>], "x-enum-mapping": { <name>: <number> } }
repeated field{ "type": "array", "items": <field schema> }
oneof with 2+ membersA property named after the oneof holding { "oneOf": [ ... ] }; each variant carries x-oneof-item with the field name
Field / message commentdescription (with @-annotations stripped out). A field comment replaces the comment of the message it references, which moves to x-type-description

A field is in the required list if it is annotated with @Required, is a proto2 required field, or carries the required rule of a validation framework. A proto3 field is never required by itself, optional or not: proto3 has no required label, and a field without explicit presence is omitted from the wire and from ProtoJSON when it holds its default value. A required label in a proto3 file is not valid proto3; the parser ignores it and logs a warning naming the field.

Recursive messages are supported: when the same message type is encountered twice on the current branch, the converter stops descending to avoid an infinite loop.

Non-standard (x-) keywords are used to preserve Protobuf information that has no direct JSON Schema equivalent: x-primitive (original scalar type), x-type (referenced message/enum name), x-type-description (comment of the referenced message when a field comment replaced it), x-enum-mapping (enum name to numeric value), and x-oneof-item (the oneof field a variant came from).

Scalar type formats

Each Protobuf scalar type is mapped to a JSON Schema type plus a format that preserves the original Protobuf wire type. For example int64 becomes {"type": "integer", "format": "int64"} and bytes becomes {"type": "string", "format": "bytes"}. The Protobuf type is additionally kept in the non-standard x-primitive keyword. By default numeric types also carry minimum/maximum limits (see the primitiveTypesWithLimits option).

Comments and annotations

Each field of a message may have a comment which is reflected as the JSON Schema description. Furthermore, the comment can contain the following annotations:

message Point {
    /*
     * The coordinate on the x axis.
     * @Default 99
     * @Min 0
     * @Max 100
     */
    required int32 x = 1;

    /*
     * The coordinate on the y axis.
     * @Default 12
     * @Min 0
     * @Max 100
     */
    required int32 y = 2;
    optional string label = 3;
}

Per field annotation

annotationdescription
@ExampleJSON Schema examples keyword. Can appear multiple times. If used with a complex type, a single-line JSON object has to be used.
@Min or @MinimumJSON Schema numeric validator
@Max or @MaximumJSON Schema numeric validator
@PatternJSON Schema string validator
@ExclusiveMinimumJSON Schema numeric validator
@ExclusiveMaximumJSON Schema numeric validator
@MultipleOfJSON Schema numeric validator
@MinLengthJSON Schema string validator
@MaxLengthJSON Schema string validator
@MinItemsJSON Schema array validator
@MaxItemsJSON Schema array validator
@DefaultJSON Schema default value
@RequiredAdds the field to the JSON Schema required list. In proto3, this and the required rule of a validation framework are the only ways to mark a field as required.

Per message annotation

annotationdescription
@RootNodeIf there are multiple types without a parent, you can give a hint about the root node with this annotation.

Head annotation

annotationdescription
@OptionIn the head of your file you can place options for the parser.

Head annotation "Option"

The @Option has to be followed by a space-separated option key and a space-separated value.

// @Option primitiveTypesWithLimits false

message Point {

}

Possible options are:

optiondescriptiondefault
primitiveTypesWithLimitsIf you do not want default minimum/maximum limits for primitive types, set this option to false.true

Supported validation frameworks

If you would like to add additional validation to your proto files, you can use one of the following validation frameworks. Their rules are translated into JSON Schema validation keywords during parsing.

The required rule of either framework adds the field to the JSON Schema required list: (buf.validate.field).required = true, or (validate.rules).<type>.required = true for the types message, duration, timestamp and any.

Development

This project is written in TypeScript and builds both an ES module (esm/) and a CommonJS (cjs/) output. Tests use Jest against snapshot-style fixtures in test/documents.

npm install          # install dependencies

npm run build        # build both esm/ and cjs/ (build:esm, build:cjs)
npm test             # run the Jest test suite with coverage
npm run lint         # run ESLint (use lint:fix to auto-fix)

Source layout:

PathPurpose
src/index.tsParser factory; implements the @asyncapi/parser schema-parser contract (parse, validate, getMimeTypes).
src/protoj2jsonSchema.tsCore converter that turns a Protobuf schema into an AsyncAPI schema.
src/primitive-types.tsScalar Protobuf type to JSON Schema type/format map.
src/google-types.tsBundled google/type/* well-known definitions.
src/pathUtils.tsImport path resolution helpers.
src/protoc-gen-validate.tsMaps (validate.rules) options to JSON Schema validators.
src/protovalidate.tsMaps (buf.validate.field) options to JSON Schema validators.
test/documents/*.yamlAsyncAPI input fixtures; *.result.json are the expected parsed outputs.

Contributing

Read CONTRIBUTING to learn about the contribution process and the AsyncAPI Code of Conduct. Issues and pull requests are welcome.

License

Apache-2.0

版本与发布记录

@asyncapi/protobuf-schema-parser 共发布 44 个版本,首次发布于 2023/04/11;过去 12 个月发布了 9 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
4.0.0latest2026/11/025 天前
3.9.02026/08/212 个月前
3.8.32026/08/063 个月前
3.8.22026/07/273 个月前
3.8.12026/07/273 个月前
3.7.02026/06/244 个月前

其他发布通道:next-major → 3.0.0-next-major.1。

关于 @asyncapi/protobuf-schema-parser 的常见问题

@asyncapi/protobuf-schema-parser 是什么?

An AsyncAPI schema parser for Protocol Buffers data types.

如何安装 @asyncapi/protobuf-schema-parser?

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

@asyncapi/protobuf-schema-parser 支持 TypeScript 吗?

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

@asyncapi/protobuf-schema-parser 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@asyncapi/protobuf-schema-parser 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@asyncapi/protobuf-schema-parser 可以商用吗?

@asyncapi/protobuf-schema-parser 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@asyncapi/protobuf-schema-parser 的下载量有多少?

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

@asyncapi/protobuf-schema-parser 还在维护吗?

最新版本 4.0.0 发布于 2026/11/02(5 天前);至今共发布 44 个版本,其中过去 12 个月发布了 9 个;首次发布于 2023/04/11。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。