MCPcopy Index your code
hub / github.com/protobufjs/protobuf.js

github.com/protobufjs/protobuf.js @protobufjs-v7.6.5 sqlite

repository ↗ · DeepWiki ↗ · release protobufjs-v7.6.5 ↗
756 symbols 1,297 edges 212 files 166 documented · 22%
README

protobuf.js protobuf.js

Protocol Buffers are a language-neutral, platform-neutral, extensible way of serializing structured data for use in communications protocols, data storage, and more, originally designed at Google (see).

protobuf.js is a pure JavaScript implementation with TypeScript support for Node.js and the browser. It's easy to use, does not sacrifice on performance, has good conformance and works out of the box with .proto files!

Contents

How to include protobuf.js in your project.

A brief introduction to using the toolset.

A few examples to get you started.

A list of available documentation resources.

A few internals and a benchmark on performance.

Notes on compatibility regarding browsers and optional libraries.

How to build the library and its components yourself.

Installation

Node.js

npm install protobufjs --save
// Static code + Reflection + .proto parser
var protobuf = require("protobufjs");

// Static code + Reflection
var protobuf = require("protobufjs/light");

// Static code only
var protobuf = require("protobufjs/minimal");

The optional command line utility to generate static code and reflection bundles lives in the protobufjs-cli package and can be installed separately:

npm install protobufjs-cli --save-dev

Browsers

Pick the variant matching your needs and replace the version tag with the exact release your project depends upon. For example, to use the minified full variant:

<script src="https://github.com/protobufjs/protobuf.js/raw/protobufjs-v7.6.5/cdn.jsdelivr.net/npm/protobufjs@7.X.X/dist/protobuf.min.js"></script>
Distribution Location
Full https://cdn.jsdelivr.net/npm/protobufjs/dist/
Light https://cdn.jsdelivr.net/npm/protobufjs/dist/light/
Minimal https://cdn.jsdelivr.net/npm/protobufjs/dist/minimal/

All variants support CommonJS and AMD loaders and export globally as window.protobuf.

Usage

Because JavaScript is a dynamically typed language, protobuf.js utilizes the concept of a valid message in order to provide the best possible performance (and, as a side product, proper typings):

Valid message

A valid message is an object (1) not missing any required fields and (2) exclusively composed of JS types understood by the wire format writer.

There are two possible types of valid messages and the encoder is able to work with both of these for convenience:

  • Message instances (explicit instances of message classes with default values on their prototype) naturally satisfy the requirements of a valid message and
  • Plain JavaScript objects that just so happen to be composed in a way satisfying the requirements of a valid message as well.

In a nutshell, the wire format writer understands the following types:

Field type Expected JS type (create, encode) Conversion (fromObject)
s-/u-/int32

s-/fixed32 | number (32 bit integer) | value | 0 if signed

value >>> 0 if unsigned | s-/u-/int64

s-/fixed64 | Long-like (optimal)

number (53 bit integer) | Long.fromValue(value) with long.js

parseInt(value, 10) otherwise | float

double | number | Number(value) | bool | boolean | Boolean(value) | string | string | String(value) | bytes | Uint8Array (optimal)

Buffer (optimal under node)

Array.<number> (8 bit integers) | base64.decode(value) if a string

Object with non-zero .length is assumed to be buffer-like | enum | number (32 bit integer) | Looks up the numeric id if a string | message | Valid message | Message.fromObject(value) | repeated T | Array<T> | Copy | map | Object<K,V> | Copy

  • Explicit undefined and null are considered as not set if the field is optional.
  • Maps are objects where the key is the string representation of the respective value or an 8 characters long hash string for Long-likes.

Toolset

With that in mind and again for performance reasons, each message class provides a distinct set of methods with each method doing just one thing. This avoids unnecessary assertions / redundant operations where performance is a concern but also forces a user to perform verification (of plain JavaScript objects that might just so happen to be a valid message) explicitly where necessary - for example when dealing with user input.

Note that Message below refers to any message class.

  • Message.verify(message: Object): null|string

verifies that a plain JavaScript object satisfies the requirements of a valid message and thus can be encoded without issues. Instead of throwing, it returns the error message as a string, if any.

js var payload = "invalid (not an object)"; var err = AwesomeMessage.verify(payload); if (err) throw Error(err);

  • Message.encode(message: Message|Object [, writer: Writer]): Writer

encodes a message instance or valid plain JavaScript object. This method does not implicitly verify the message and it's up to the user to make sure that the payload is a valid message.

js var buffer = AwesomeMessage.encode(message).finish();

  • Message.encodeDelimited(message: Message|Object [, writer: Writer]): Writer

works like Message.encode but additionally prepends the length of the message as a varint.

  • Message.decode(reader: Reader|Uint8Array): Message

decodes a buffer to a message instance. If required fields are missing, it throws a util.ProtocolError with an instance property set to the so far decoded message. If the wire format is invalid, it throws an Error.

js try { var decodedMessage = AwesomeMessage.decode(buffer); } catch (e) { if (e instanceof protobuf.util.ProtocolError) { // e.instance holds the so far decoded message with missing required fields } else { // wire format is invalid } }

  • Message.decodeDelimited(reader: Reader|Uint8Array): Message

works like Message.decode but additionally reads the length of the message prepended as a varint.

  • Message.create(properties: Object): Message

creates a new message instance from a set of properties that satisfy the requirements of a valid message. Where applicable, it is recommended to prefer Message.create over Message.fromObject because it doesn't perform possibly redundant conversion.

js var message = AwesomeMessage.create({ awesomeField: "AwesomeString" });

  • Message.fromObject(object: Object): Message

converts any non-valid plain JavaScript object to a message instance using the conversion steps outlined within the table above.

js var message = AwesomeMessage.fromObject({ awesomeField: 42 }); // converts awesomeField to a string

  • Message.toObject(message: Message [, options: ConversionOptions]): Object

converts a message instance to an arbitrary plain JavaScript object for interoperability with other libraries or storage. The resulting plain JavaScript object might still satisfy the requirements of a valid message depending on the actual conversion options specified, but most of the time it does not.

js var object = AwesomeMessage.toObject(message, { enums: String, // enums as string names longs: String, // longs as strings (or BigInt for bigint values) bytes: String, // bytes as base64 encoded strings defaults: true, // includes default values arrays: true, // populates empty arrays (repeated fields) even if defaults=false objects: true, // populates empty objects (map fields) even if defaults=false oneofs: true // includes virtual oneof fields set to the present field's name });

For reference, the following diagram aims to display relationships between the different methods and the concept of a valid message:

Toolset Diagram

In other words: verify indicates that calling create or encode directly on the plain object will [result in a valid message respectively] succeed. fromObject, on the other hand, does conversion from a broader range of plain objects to create valid messages. (ref)

Examples

Using .proto files

It is possible to load existing .proto files using the full library, which parses and compiles the definitions to ready to use (reflection-based) message classes:

// awesome.proto
package awesomepackage;
syntax = "proto3";

message AwesomeMessage {
    string awesome_field = 1; // becomes awesomeField
}
protobuf.load("awesome.proto", function(err, root) {
    if (err)
        throw err;

    // Obtain a message type
    var AwesomeMessage = root.lookupType("awesomepackage.AwesomeMessage");

    // Exemplary payload
    var payload = { awesomeField: "AwesomeString" };

    // Verify the payload if necessary (i.e. when possibly incomplete or invalid)
    var errMsg = AwesomeMessage.verify(payload);
    if (errMsg)
        throw Error(errMsg);

    // Create a new message
    var message = AwesomeMessage.create(payload); // or use .fromObject if conversion is necessary

    // Encode a message to an Uint8Array (browser) or Buffer (node)
    var buffer = AwesomeMessage.encode(message).finish();
    // ... do something with buffer

    // Decode an Uint8Array (browser) or Buffer (node) to a message
    var message = AwesomeMessage.decode(buffer);
    // ... do something with message

    // If the application uses length-delimited buffers, there is also encodeDelimited and decodeDelimited.

    // Maybe convert the message back to a plain object
    var object = AwesomeMessage.toObject(message, {
        longs: String,
        enums: String,
        bytes: String,
        // see ConversionOptions
    });
});

Additionally, promise syntax can be used by omitting the callback, if preferred:

protobuf.load("awesome.proto")
    .then(function(root) {
       ...
    });

Using JSON descriptors

The library utilizes JSON descriptors that are equivalent to a .proto definition. For example, the following is identical to the .proto definition seen above:

// awesome.json
{
  "nested": {
    "awesomepackage": {
      "nested": {
        "AwesomeMessage": {
          "fields": {
            "awesomeField": {
              "type": "string",
              "id": 1
            }
          }
        }
      }
    }
  }
}

JSON descriptors closely resemble the internal reflection structure:

Type (T) Extends Type-specific properties
ReflectionObject options
Namespace ReflectionObject nested
Root Namespace nested
Type Namespace fields
Enum ReflectionObject values
Field ReflectionObject rule, type, id
MapField Field keyType
OneOf ReflectionObject oneof (array of field names)
Service Namespace methods
Method ReflectionObject type, requestType, responseType, requestStream, responseStream
  • Bold properties are required. Italic types are abstract.
  • T.fromJSON(name, json) creates the respective reflection object from a JSON descriptor
  • T#toJSON() creates a JSON descriptor from the respective reflection object (its name is used as the key within the parent)

Exclusively using JSON descriptors instead of .proto files enables the use of just the light library (the parser isn't required in this case).

A JSON descriptor

Extension points exported contracts — how you extend this code

INested (Interface)
(no doc) [3 implementers]
tests/data/test.d.ts
IAny (Interface)
Properties of a google.protobuf.Any message.
index.d.ts
IFetchOptions (Interface)
* Options as used by util.fetch. * @typedef IFetchOptions * @type {Object} * @property {boolean} [binary=fals
lib/fetch/index.d.ts
Descriptor (Interface)
(no doc)
tests/comp_import_extend.ts
IFileDescriptorSet (Interface)
(no doc)
ext/descriptor/index.d.ts
IComplex (Interface)
(no doc) [2 implementers]
tests/data/test.d.ts
IDuration (Interface)
Properties of a google.protobuf.Duration message.
index.d.ts
IFileDescriptorProto (Interface)
(no doc)
ext/descriptor/index.d.ts

Core symbols most depended-on inside this repo

push
called by 97
cli/targets/static.js
escapeName
called by 49
cli/targets/static.js
write
called by 48
cli/lib/tsd-jsdoc/publish.js
skip
called by 48
src/tokenize.js
illegal
called by 45
src/parse.js
exportName
called by 42
cli/targets/static.js
writeln
called by 40
cli/lib/tsd-jsdoc/publish.js
next
called by 35
src/tokenize.js

Shape

Function 376
Class 213
Interface 136
Enum 28
Method 3

Languages

TypeScript100%

Modules by API surface

tests/data/test.d.ts222 symbols
index.d.ts73 symbols
tests/data/test.js66 symbols
src/parse.js29 symbols
cli/lib/tsd-jsdoc/publish.js25 symbols
cli/targets/proto.js19 symbols
lib/float/index.js17 symbols
ext/descriptor/index.d.ts17 symbols
cli/targets/static.js16 symbols
tests/data/mapbox/vector_tile.d.ts13 symbols
src/tokenize.js13 symbols
ext/descriptor/index.js12 symbols

Dependencies from manifests, versioned

@protobufjs/aspromise1.1.2 · 1×
@protobufjs/base641.1.2 · 1×
@protobufjs/codegen2.0.5 · 1×
@protobufjs/eventemitter1.1.1 · 1×
@protobufjs/fetch1.1.1 · 1×
@protobufjs/float1.0.2 · 1×
@protobufjs/path1.1.2 · 1×
@protobufjs/pool1.1.0 · 1×
@protobufjs/utf81.1.1 · 1×
@types/node>=13.7.0 · 1×
benchmark2.1.4 · 1×
browserify17.0.0 · 1×

For agents

$ claude mcp add protobuf.js \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact