or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

binary-io.mdbytestring-utilities.mddebug-utilities.mdextension-fields.mdindex.mdmap-operations.mdmessage-operations.md
tile.json

tessl/npm-google-protobuf

Protocol Buffers JavaScript runtime library for serializing structured data

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/google-protobuf@4.0.x

To install, run

npx @tessl/cli install tessl/npm-google-protobuf@4.0.0

index.mddocs/

Google Protocol Buffers JavaScript Library

Protocol Buffers (protobuf) is Google's language-neutral, platform-neutral extensible mechanism for serializing structured data. This JavaScript library provides runtime support for working with Protocol Buffer messages in JavaScript applications.

Package Information

  • Package Name: google-protobuf
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install google-protobuf

Core Imports

// CommonJS import (ES6 modules not yet supported)
const { 
  Message, 
  BinaryReader, 
  BinaryWriter, 
  Map,
  debug,
  ExtensionFieldInfo,
  ExtensionFieldBinaryInfo,
  ByteString
} = require('google-protobuf');

Basic Usage

Protocol Buffers in JavaScript involves two components:

  1. Runtime Library - This google-protobuf package for message operations
  2. Generated Code - .js files created by protoc from .proto definitions
// Import generated message classes
const { MyMessage } = require('./messages_pb');

// Create and populate a message
const message = new MyMessage();
message.setName("John Doe");
message.setAge(25);
message.setPhoneNumbers(["800-555-1212", "800-555-0000"]);

// Serialize to binary format
const bytes = message.serializeBinary();

// Deserialize from binary format
const message2 = MyMessage.deserializeBinary(bytes);

// Access field values
console.log(message2.getName()); // "John Doe"
console.log(message2.getAge());  // 25

Architecture

The library is organized into several key components:

Core Message System

  • jspb.Message - Base class for all Protocol Buffer messages
  • Handles field access, serialization, cloning, and comparison operations
  • Supports extension fields and wrapper types

Binary I/O Operations

  • jspb.BinaryReader - Reads Protocol Buffer wire format data
  • jspb.BinaryWriter - Writes Protocol Buffer wire format data
  • Low-level encoder/decoder for primitive types

Map Container

  • jspb.Map - ES6 Map-like container for Protocol Buffer map fields
  • Provides iteration, conversion, and synchronization with underlying arrays

Development Utilities

  • jspb.debug - Debugging utilities for message introspection
  • jspb.ExtensionFieldInfo - Metadata for extension fields

Capabilities

Message Operations { .api }

Core functionality for working with Protocol Buffer messages:

const { Message } = require('google-protobuf');

// Field access
const value = Message.getField(message, fieldNumber);
Message.setField(message, fieldNumber, value);

// Repeated fields
const repeatedValue = Message.getRepeatedField(message, fieldNumber);
Message.addToRepeatedField(message, fieldNumber, value);

// Map fields
const mapField = Message.getMapField(message, fieldNumber, false, ValueConstructor);

// Message cloning and comparison
const cloned = Message.cloneMessage(message);
const areEqual = Message.equals(message1, message2);

// Binary serialization
const bytes = message.serializeBinary();
const deserialized = MyMessage.deserializeBinary(bytes);

Type Definitions:

/**
 * @typedef {boolean|number|string} ScalarFieldType
 * @typedef {Array<ScalarFieldType>|Array<Uint8Array>} RepeatedFieldType  
 * @typedef {ScalarFieldType|RepeatedFieldType|Uint8Array} AnyFieldType
 */

→ Complete Message Operations Documentation

Binary I/O Operations { .api }

Low-level binary reading and writing of Protocol Buffer wire format:

const { BinaryReader, BinaryWriter } = require('google-protobuf');

// Reading binary data
const reader = new BinaryReader(bytes);
while (reader.nextField()) {
  const fieldNumber = reader.getFieldNumber();
  const wireType = reader.getWireType();
  
  switch (fieldNumber) {
    case 1:
      const stringValue = reader.readString();
      break;
    case 2:
      const intValue = reader.readInt32();
      break;
  }
}

// Writing binary data
const writer = new BinaryWriter();
writer.writeString(1, "Hello World");
writer.writeInt32(2, 42);
const resultBytes = writer.getResultBuffer();

Type Definitions:

/**
 * @typedef {Object} BinaryReaderOptions
 * @property {boolean=} discardUnknownFields
 * @property {boolean=} aliasBytesFields
 */

→ Complete Binary I/O Documentation

Map Operations { .api }

Protocol Buffer map field handling with ES6 Map-like interface:

const { Map } = require('google-protobuf');

// Create and populate map
const map = new Map();
map.set("key1", "value1");
map.set("key2", "value2");

// Iteration and access
map.forEach((value, key) => {
  console.log(`${key}: ${value}`);
});

const hasKey = map.has("key1");
const value = map.get("key1");
const size = map.getLength();

// Conversion operations
const array = map.toArray();
const object = map.toObject(true, (value) => value);

Type Definitions:

/**
 * @constructor
 * @param {Array=} arr Initial array data
 * @param {Function=} opt_valueCtor Value constructor function
 */

→ Complete Map Operations Documentation

Debug Utilities { .api }

Development-time debugging and introspection tools:

const { debug } = require('google-protobuf');

// Create human-readable representation
const readable = debug.dump(message);
console.log(readable);
/* Output example:
{
  name: "John Doe",
  age: 25,
  phoneNumbers: ["800-555-1212", "800-555-0000"],
  address: {
    street: "123 Main St",
    city: "Anytown"
  }
}
*/

Type Definitions:

/**
 * @param {!jspb.Message} message Protocol Buffer message instance
 * @return {?Object} Human-readable object or null in production
 */

→ Complete Debug Utilities Documentation

Extension Fields { .api }

Support for Protocol Buffer extension fields:

const { ExtensionFieldInfo, ExtensionFieldBinaryInfo } = require('google-protobuf');

// Define extension field metadata
const extensionInfo = new ExtensionFieldInfo(
  fieldNumber,    // Field number
  fieldName,      // Field name object
  constructor,    // Message constructor (null for primitives)
  toObjectFn,     // toObject function (null for primitives)  
  isRepeated      // 0 or 1 for repeated fields
);

// Use extensions with messages
message.setExtension(extensionInfo, value);
const extensionValue = message.getExtension(extensionInfo);

Type Definitions:

/**
 * @constructor
 * @param {number} fieldNumber
 * @param {Object} fieldName 
 * @param {?Function} ctor
 * @param {?Function} toObjectFn
 * @param {number} isRepeated
 */

→ Complete Extension Fields Documentation

Internal APIs for Generated Code { .api }

Low-level APIs used by generated code for serialization and deserialization:

const { internal } = require('google-protobuf');

// Map serialization (used by generated code)
internal.public_for_gencode.serializeMapToBinary(
  map, fieldNumber, writer, keyWriterFn, valueWriterFn, valueWriterCallback
);

// Map deserialization (used by generated code)  
internal.public_for_gencode.deserializeMapFromBinary(
  map, reader, keyReaderFn, defaultKey, valueReaderFn, defaultValue
);

Type Definitions:

/**
 * @param {?jspb.Map} map Map instance to serialize
 * @param {number} fieldNumber Protocol buffer field number
 * @param {!BinaryWriter} writer Writer instance
 * @param {function(this:BinaryWriter,number,*)} keyWriterFn Key serialization function
 * @param {function(this:BinaryWriter,number,*,?=)} valueWriterFn Value serialization function
 * @param {function(*,!BinaryWriter)=} valueWriterCallback Optional callback for message values
 */

Important Note: These APIs are intended for use by generated code only and should not be used directly in application code.

ByteString Utilities { .api }

Immutable binary data handling for bytes fields:

const { ByteString } = require('google-protobuf');

// Create from different sources
const fromBase64 = ByteString.fromBase64("SGVsbG8gV29ybGQ=");
const fromBytes = ByteString.fromUint8Array([72, 101, 108, 108, 111]);
const empty = ByteString.empty();

// Convert between formats
const base64String = byteString.toBase64();
const byteArray = byteString.toUint8Array();
const length = byteString.getLength();

// Comparison and equality
const areEqual = bs1.equals(bs2);
const hashCode = byteString.hashCode();

Type Definitions:

/**
 * @param {string} value Base64 encoded string
 * @return {!ByteString}
 */

/**
 * @param {!Uint8Array|!Array<number>} value Byte array data
 * @return {!ByteString}
 */

→ Complete ByteString Utilities Documentation

Integration Notes

Generated Code Integration

This library works with code generated by the Protocol Buffer compiler (protoc):

# Generate CommonJS modules
protoc --js_out=import_style=commonjs,binary:. messages.proto

# Use generated code
const { MyMessage } = require('./messages_pb');
const message = new MyMessage();

Performance Considerations

  • Binary serialization is optimized for speed and size
  • Use BinaryReader/BinaryWriter options to control memory usage
  • Map fields synchronize lazily with underlying arrays
  • Debug utilities only work in unobfuscated code

Browser Compatibility

  • Uses CommonJS module format (ES6 modules not yet supported)
  • Requires module bundler (webpack, Browserify, etc.) for browser use
  • Supports both development and production builds
  • Compatible with Closure Compiler optimization