Erster Commit

This commit is contained in:
2026-08-22 08:40:29 +02:00
commit 875477d425
1961 changed files with 930336 additions and 0 deletions
+43
View File
@@ -0,0 +1,43 @@
# @bufbuild/protobuf
This package provides the runtime library for the code generator plugin
[protoc-gen-es](https://www.npmjs.com/package/@bufbuild/protoc-gen-es).
## Protocol Buffers for ECMAScript
A complete implementation of [Protocol Buffers](https://developers.google.com/protocol-buffers) in TypeScript,
suitable for web browsers and Node.js.
**Protobuf-ES** is intended to be a solid, modern alternative to existing Protobuf implementations for the JavaScript ecosystem. It is the first project in this space to provide a comprehensive plugin framework and decouple the base types from RPC functionality.
Some additional features that set it apart from the others:
- ECMAScript module support
- First-class TypeScript support
- Generation of idiomatic JavaScript and TypeScript code.
- Generation of [much smaller bundles](https://github.com/bufbuild/protobuf-es/blob/main/packages/bundle-size)
- Implementation of all proto3 features, including the [canonical JSON format](https://developers.google.com/protocol-buffers/docs/proto3#json).
- Implementation of all proto2 features, except for extensions and the text format.
- Usage of standard JavaScript APIs instead of the [Closure Library](http://googlecode.blogspot.com/2009/11/introducing-closure-tools.html)
- Compatibility is covered by the protocol buffers [conformance tests](https://github.com/bufbuild/protobuf-es/blob/main/packages/protobuf-conformance).
- Descriptor and reflection support
## Installation
```bash
npm install @bufbuild/protobuf
```
## Documentation
To learn how to work with `@bufbuild/protobuf` check out the docs for the [Runtime API](https://github.com/bufbuild/protobuf-es/blob/main/docs/runtime_api.md)
and the [generated code](https://github.com/bufbuild/protobuf-es/blob/main/docs/generated_code.md).
Official documentation for the Protobuf-ES project can be found at [github.com/bufbuild/protobuf-es](https://github.com/bufbuild/protobuf-es).
For more information on Buf, check out the official [Buf documentation](https://docs.buf.build/introduction).
## Examples
A complete code example can be found in the **Protobuf-ES** repo [here](https://github.com/bufbuild/protobuf-es/tree/main/packages/protobuf-example).
+422
View File
@@ -0,0 +1,422 @@
/**
* Protobuf binary format wire types.
*
* A wire type provides just enough information to find the length of the
* following value.
*
* See https://developers.google.com/protocol-buffers/docs/encoding#structure
*/
export declare enum WireType {
/**
* Used for int32, int64, uint32, uint64, sint32, sint64, bool, enum
*/
Varint = 0,
/**
* Used for fixed64, sfixed64, double.
* Always 8 bytes with little-endian byte order.
*/
Bit64 = 1,
/**
* Used for string, bytes, embedded messages, packed repeated fields
*
* Only repeated numeric types (types which use the varint, 32-bit,
* or 64-bit wire types) can be packed. In proto3, such fields are
* packed by default.
*/
LengthDelimited = 2,
/**
* Start of a tag-delimited aggregate, such as a proto2 group, or a message
* in editions with message_encoding = DELIMITED.
*/
StartGroup = 3,
/**
* End of a tag-delimited aggregate.
*/
EndGroup = 4,
/**
* Used for fixed32, sfixed32, float.
* Always 4 bytes with little-endian byte order.
*/
Bit32 = 5
}
type TextEncoderLike = {
encode(input?: string): Uint8Array;
};
type TextDecoderLike = {
decode(input?: Uint8Array): string;
};
export interface IBinaryReader {
/**
* Current position.
*/
readonly pos: number;
/**
* Number of bytes available in this reader.
*/
readonly len: number;
/**
* Reads a tag - field number and wire type.
*/
tag(): [number, WireType];
/**
* Skip one element on the wire and return the skipped data.
*/
skip(wireType: WireType, fieldNo?: number): Uint8Array;
/**
* Read a `uint32` field, an unsigned 32 bit varint.
*/
uint32(): number;
/**
* Read a `int32` field, a signed 32 bit varint.
*/
int32(): number;
/**
* Read a `sint32` field, a signed, zigzag-encoded 32-bit varint.
*/
sint32(): number;
/**
* Read a `int64` field, a signed 64-bit varint.
*/
int64(): bigint | string;
/**
* Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint.
*/
sint64(): bigint | string;
/**
* Read a `fixed64` field, a signed, fixed-length 64-bit integer.
*/
sfixed64(): bigint | string;
/**
* Read a `uint64` field, an unsigned 64-bit varint.
*/
uint64(): bigint | string;
/**
* Read a `fixed64` field, an unsigned, fixed-length 64 bit integer.
*/
fixed64(): bigint | string;
/**
* Read a `bool` field, a variant.
*/
bool(): boolean;
/**
* Read a `fixed32` field, an unsigned, fixed-length 32-bit integer.
*/
fixed32(): number;
/**
* Read a `sfixed32` field, a signed, fixed-length 32-bit integer.
*/
sfixed32(): number;
/**
* Read a `float` field, 32-bit floating point number.
*/
float(): number;
/**
* Read a `double` field, a 64-bit floating point number.
*/
double(): number;
/**
* Read a `bytes` field, length-delimited arbitrary data.
*/
bytes(): Uint8Array;
/**
* Read a `string` field, length-delimited data converted to UTF-8 text.
*/
string(): string;
}
export interface IBinaryWriter {
/**
* Return all bytes written and reset this writer.
*/
finish(): Uint8Array;
/**
* Start a new fork for length-delimited data like a message
* or a packed repeated field.
*
* Must be joined later with `join()`.
*/
fork(): IBinaryWriter;
/**
* Join the last fork. Write its length and bytes, then
* return to the previous state.
*/
join(): IBinaryWriter;
/**
* Writes a tag (field number and wire type).
*
* Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`
*
* Generated code should compute the tag ahead of time and call `uint32()`.
*/
tag(fieldNo: number, type: WireType): IBinaryWriter;
/**
* Write a chunk of raw bytes.
*/
raw(chunk: Uint8Array): IBinaryWriter;
/**
* Write a `uint32` value, an unsigned 32 bit varint.
*/
uint32(value: number): IBinaryWriter;
/**
* Write a `int32` value, a signed 32 bit varint.
*/
int32(value: number): IBinaryWriter;
/**
* Write a `sint32` value, a signed, zigzag-encoded 32-bit varint.
*/
sint32(value: number): IBinaryWriter;
/**
* Write a `int64` value, a signed 64-bit varint.
*/
int64(value: string | number | bigint): IBinaryWriter;
/**
* Write a `uint64` value, an unsigned 64-bit varint.
*/
uint64(value: string | number | bigint): IBinaryWriter;
/**
* Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint.
*/
sint64(value: string | number | bigint): IBinaryWriter;
/**
* Write a `fixed64` value, an unsigned, fixed-length 64 bit integer.
*/
fixed64(value: string | number | bigint): IBinaryWriter;
/**
* Write a `fixed64` value, a signed, fixed-length 64-bit integer.
*/
sfixed64(value: string | number | bigint): IBinaryWriter;
/**
* Write a `bool` value, a variant.
*/
bool(value: boolean): IBinaryWriter;
/**
* Write a `fixed32` value, an unsigned, fixed-length 32-bit integer.
*/
fixed32(value: number): IBinaryWriter;
/**
* Write a `sfixed32` value, a signed, fixed-length 32-bit integer.
*/
sfixed32(value: number): IBinaryWriter;
/**
* Write a `float` value, 32-bit floating point number.
*/
float(value: number): IBinaryWriter;
/**
* Write a `double` value, a 64-bit floating point number.
*/
double(value: number): IBinaryWriter;
/**
* Write a `bytes` value, length-delimited arbitrary data.
*/
bytes(value: Uint8Array): IBinaryWriter;
/**
* Write a `string` value, length-delimited data converted to UTF-8 text.
*/
string(value: string): IBinaryWriter;
}
export declare class BinaryWriter implements IBinaryWriter {
/**
* We cannot allocate a buffer for the entire output
* because we don't know it's size.
*
* So we collect smaller chunks of known size and
* concat them later.
*
* Use `raw()` to push data to this array. It will flush
* `buf` first.
*/
private chunks;
/**
* A growing buffer for byte values. If you don't know
* the size of the data you are writing, push to this
* array.
*/
protected buf: number[];
/**
* Previous fork states.
*/
private stack;
/**
* Text encoder instance to convert UTF-8 to bytes.
*/
private readonly textEncoder;
constructor(textEncoder?: TextEncoderLike);
/**
* Return all bytes written and reset this writer.
*/
finish(): Uint8Array;
/**
* Start a new fork for length-delimited data like a message
* or a packed repeated field.
*
* Must be joined later with `join()`.
*/
fork(): IBinaryWriter;
/**
* Join the last fork. Write its length and bytes, then
* return to the previous state.
*/
join(): IBinaryWriter;
/**
* Writes a tag (field number and wire type).
*
* Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`.
*
* Generated code should compute the tag ahead of time and call `uint32()`.
*/
tag(fieldNo: number, type: WireType): IBinaryWriter;
/**
* Write a chunk of raw bytes.
*/
raw(chunk: Uint8Array): IBinaryWriter;
/**
* Write a `uint32` value, an unsigned 32 bit varint.
*/
uint32(value: number): IBinaryWriter;
/**
* Write a `int32` value, a signed 32 bit varint.
*/
int32(value: number): IBinaryWriter;
/**
* Write a `bool` value, a variant.
*/
bool(value: boolean): IBinaryWriter;
/**
* Write a `bytes` value, length-delimited arbitrary data.
*/
bytes(value: Uint8Array): IBinaryWriter;
/**
* Write a `string` value, length-delimited data converted to UTF-8 text.
*/
string(value: string): IBinaryWriter;
/**
* Write a `float` value, 32-bit floating point number.
*/
float(value: number): IBinaryWriter;
/**
* Write a `double` value, a 64-bit floating point number.
*/
double(value: number): IBinaryWriter;
/**
* Write a `fixed32` value, an unsigned, fixed-length 32-bit integer.
*/
fixed32(value: number): IBinaryWriter;
/**
* Write a `sfixed32` value, a signed, fixed-length 32-bit integer.
*/
sfixed32(value: number): IBinaryWriter;
/**
* Write a `sint32` value, a signed, zigzag-encoded 32-bit varint.
*/
sint32(value: number): IBinaryWriter;
/**
* Write a `fixed64` value, a signed, fixed-length 64-bit integer.
*/
sfixed64(value: string | number | bigint): IBinaryWriter;
/**
* Write a `fixed64` value, an unsigned, fixed-length 64 bit integer.
*/
fixed64(value: string | number | bigint): IBinaryWriter;
/**
* Write a `int64` value, a signed 64-bit varint.
*/
int64(value: string | number | bigint): IBinaryWriter;
/**
* Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint.
*/
sint64(value: string | number | bigint): IBinaryWriter;
/**
* Write a `uint64` value, an unsigned 64-bit varint.
*/
uint64(value: string | number | bigint): IBinaryWriter;
}
export declare class BinaryReader implements IBinaryReader {
/**
* Current position.
*/
pos: number;
/**
* Number of bytes available in this reader.
*/
readonly len: number;
private readonly buf;
private readonly view;
private readonly textDecoder;
constructor(buf: Uint8Array, textDecoder?: TextDecoderLike);
/**
* Reads a tag - field number and wire type.
*/
tag(): [number, WireType];
/**
* Skip one element and return the skipped data.
*
* When skipping StartGroup, provide the tags field number to check for
* matching field number in the EndGroup tag.
*/
skip(wireType: WireType, fieldNo?: number): Uint8Array;
protected varint64: () => [number, number];
/**
* Throws error if position in byte array is out of range.
*/
protected assertBounds(): void;
/**
* Read a `uint32` field, an unsigned 32 bit varint.
*/
uint32: () => number;
/**
* Read a `int32` field, a signed 32 bit varint.
*/
int32(): number;
/**
* Read a `sint32` field, a signed, zigzag-encoded 32-bit varint.
*/
sint32(): number;
/**
* Read a `int64` field, a signed 64-bit varint.
*/
int64(): bigint | string;
/**
* Read a `uint64` field, an unsigned 64-bit varint.
*/
uint64(): bigint | string;
/**
* Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint.
*/
sint64(): bigint | string;
/**
* Read a `bool` field, a variant.
*/
bool(): boolean;
/**
* Read a `fixed32` field, an unsigned, fixed-length 32-bit integer.
*/
fixed32(): number;
/**
* Read a `sfixed32` field, a signed, fixed-length 32-bit integer.
*/
sfixed32(): number;
/**
* Read a `fixed64` field, an unsigned, fixed-length 64 bit integer.
*/
fixed64(): bigint | string;
/**
* Read a `fixed64` field, a signed, fixed-length 64-bit integer.
*/
sfixed64(): bigint | string;
/**
* Read a `float` field, 32-bit floating point number.
*/
float(): number;
/**
* Read a `double` field, a 64-bit floating point number.
*/
double(): number;
/**
* Read a `bytes` field, length-delimited arbitrary data.
*/
bytes(): Uint8Array;
/**
* Read a `string` field, length-delimited data converted to UTF-8 text.
*/
string(): string;
}
export {};
+444
View File
@@ -0,0 +1,444 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.BinaryReader = exports.BinaryWriter = exports.WireType = void 0;
const varint_js_1 = require("./google/varint.js");
const assert_js_1 = require("./private/assert.js");
const proto_int64_js_1 = require("./proto-int64.js");
/* eslint-disable prefer-const,no-case-declarations,@typescript-eslint/restrict-plus-operands */
/**
* Protobuf binary format wire types.
*
* A wire type provides just enough information to find the length of the
* following value.
*
* See https://developers.google.com/protocol-buffers/docs/encoding#structure
*/
var WireType;
(function (WireType) {
/**
* Used for int32, int64, uint32, uint64, sint32, sint64, bool, enum
*/
WireType[WireType["Varint"] = 0] = "Varint";
/**
* Used for fixed64, sfixed64, double.
* Always 8 bytes with little-endian byte order.
*/
WireType[WireType["Bit64"] = 1] = "Bit64";
/**
* Used for string, bytes, embedded messages, packed repeated fields
*
* Only repeated numeric types (types which use the varint, 32-bit,
* or 64-bit wire types) can be packed. In proto3, such fields are
* packed by default.
*/
WireType[WireType["LengthDelimited"] = 2] = "LengthDelimited";
/**
* Start of a tag-delimited aggregate, such as a proto2 group, or a message
* in editions with message_encoding = DELIMITED.
*/
WireType[WireType["StartGroup"] = 3] = "StartGroup";
/**
* End of a tag-delimited aggregate.
*/
WireType[WireType["EndGroup"] = 4] = "EndGroup";
/**
* Used for fixed32, sfixed32, float.
* Always 4 bytes with little-endian byte order.
*/
WireType[WireType["Bit32"] = 5] = "Bit32";
})(WireType || (exports.WireType = WireType = {}));
class BinaryWriter {
constructor(textEncoder) {
/**
* Previous fork states.
*/
this.stack = [];
this.textEncoder = textEncoder !== null && textEncoder !== void 0 ? textEncoder : new TextEncoder();
this.chunks = [];
this.buf = [];
}
/**
* Return all bytes written and reset this writer.
*/
finish() {
this.chunks.push(new Uint8Array(this.buf)); // flush the buffer
let len = 0;
for (let i = 0; i < this.chunks.length; i++)
len += this.chunks[i].length;
let bytes = new Uint8Array(len);
let offset = 0;
for (let i = 0; i < this.chunks.length; i++) {
bytes.set(this.chunks[i], offset);
offset += this.chunks[i].length;
}
this.chunks = [];
return bytes;
}
/**
* Start a new fork for length-delimited data like a message
* or a packed repeated field.
*
* Must be joined later with `join()`.
*/
fork() {
this.stack.push({ chunks: this.chunks, buf: this.buf });
this.chunks = [];
this.buf = [];
return this;
}
/**
* Join the last fork. Write its length and bytes, then
* return to the previous state.
*/
join() {
// get chunk of fork
let chunk = this.finish();
// restore previous state
let prev = this.stack.pop();
if (!prev)
throw new Error("invalid state, fork stack empty");
this.chunks = prev.chunks;
this.buf = prev.buf;
// write length of chunk as varint
this.uint32(chunk.byteLength);
return this.raw(chunk);
}
/**
* Writes a tag (field number and wire type).
*
* Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`.
*
* Generated code should compute the tag ahead of time and call `uint32()`.
*/
tag(fieldNo, type) {
return this.uint32(((fieldNo << 3) | type) >>> 0);
}
/**
* Write a chunk of raw bytes.
*/
raw(chunk) {
if (this.buf.length) {
this.chunks.push(new Uint8Array(this.buf));
this.buf = [];
}
this.chunks.push(chunk);
return this;
}
/**
* Write a `uint32` value, an unsigned 32 bit varint.
*/
uint32(value) {
(0, assert_js_1.assertUInt32)(value);
// write value as varint 32, inlined for speed
while (value > 0x7f) {
this.buf.push((value & 0x7f) | 0x80);
value = value >>> 7;
}
this.buf.push(value);
return this;
}
/**
* Write a `int32` value, a signed 32 bit varint.
*/
int32(value) {
(0, assert_js_1.assertInt32)(value);
(0, varint_js_1.varint32write)(value, this.buf);
return this;
}
/**
* Write a `bool` value, a variant.
*/
bool(value) {
this.buf.push(value ? 1 : 0);
return this;
}
/**
* Write a `bytes` value, length-delimited arbitrary data.
*/
bytes(value) {
this.uint32(value.byteLength); // write length of chunk as varint
return this.raw(value);
}
/**
* Write a `string` value, length-delimited data converted to UTF-8 text.
*/
string(value) {
let chunk = this.textEncoder.encode(value);
this.uint32(chunk.byteLength); // write length of chunk as varint
return this.raw(chunk);
}
/**
* Write a `float` value, 32-bit floating point number.
*/
float(value) {
(0, assert_js_1.assertFloat32)(value);
let chunk = new Uint8Array(4);
new DataView(chunk.buffer).setFloat32(0, value, true);
return this.raw(chunk);
}
/**
* Write a `double` value, a 64-bit floating point number.
*/
double(value) {
let chunk = new Uint8Array(8);
new DataView(chunk.buffer).setFloat64(0, value, true);
return this.raw(chunk);
}
/**
* Write a `fixed32` value, an unsigned, fixed-length 32-bit integer.
*/
fixed32(value) {
(0, assert_js_1.assertUInt32)(value);
let chunk = new Uint8Array(4);
new DataView(chunk.buffer).setUint32(0, value, true);
return this.raw(chunk);
}
/**
* Write a `sfixed32` value, a signed, fixed-length 32-bit integer.
*/
sfixed32(value) {
(0, assert_js_1.assertInt32)(value);
let chunk = new Uint8Array(4);
new DataView(chunk.buffer).setInt32(0, value, true);
return this.raw(chunk);
}
/**
* Write a `sint32` value, a signed, zigzag-encoded 32-bit varint.
*/
sint32(value) {
(0, assert_js_1.assertInt32)(value);
// zigzag encode
value = ((value << 1) ^ (value >> 31)) >>> 0;
(0, varint_js_1.varint32write)(value, this.buf);
return this;
}
/**
* Write a `fixed64` value, a signed, fixed-length 64-bit integer.
*/
sfixed64(value) {
let chunk = new Uint8Array(8), view = new DataView(chunk.buffer), tc = proto_int64_js_1.protoInt64.enc(value);
view.setInt32(0, tc.lo, true);
view.setInt32(4, tc.hi, true);
return this.raw(chunk);
}
/**
* Write a `fixed64` value, an unsigned, fixed-length 64 bit integer.
*/
fixed64(value) {
let chunk = new Uint8Array(8), view = new DataView(chunk.buffer), tc = proto_int64_js_1.protoInt64.uEnc(value);
view.setInt32(0, tc.lo, true);
view.setInt32(4, tc.hi, true);
return this.raw(chunk);
}
/**
* Write a `int64` value, a signed 64-bit varint.
*/
int64(value) {
let tc = proto_int64_js_1.protoInt64.enc(value);
(0, varint_js_1.varint64write)(tc.lo, tc.hi, this.buf);
return this;
}
/**
* Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint.
*/
sint64(value) {
let tc = proto_int64_js_1.protoInt64.enc(value),
// zigzag encode
sign = tc.hi >> 31, lo = (tc.lo << 1) ^ sign, hi = ((tc.hi << 1) | (tc.lo >>> 31)) ^ sign;
(0, varint_js_1.varint64write)(lo, hi, this.buf);
return this;
}
/**
* Write a `uint64` value, an unsigned 64-bit varint.
*/
uint64(value) {
let tc = proto_int64_js_1.protoInt64.uEnc(value);
(0, varint_js_1.varint64write)(tc.lo, tc.hi, this.buf);
return this;
}
}
exports.BinaryWriter = BinaryWriter;
class BinaryReader {
constructor(buf, textDecoder) {
this.varint64 = varint_js_1.varint64read; // dirty cast for `this`
/**
* Read a `uint32` field, an unsigned 32 bit varint.
*/
this.uint32 = varint_js_1.varint32read; // dirty cast for `this` and access to protected `buf`
this.buf = buf;
this.len = buf.length;
this.pos = 0;
this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
this.textDecoder = textDecoder !== null && textDecoder !== void 0 ? textDecoder : new TextDecoder();
}
/**
* Reads a tag - field number and wire type.
*/
tag() {
let tag = this.uint32(), fieldNo = tag >>> 3, wireType = tag & 7;
if (fieldNo <= 0 || wireType < 0 || wireType > 5)
throw new Error("illegal tag: field no " + fieldNo + " wire type " + wireType);
return [fieldNo, wireType];
}
/**
* Skip one element and return the skipped data.
*
* When skipping StartGroup, provide the tags field number to check for
* matching field number in the EndGroup tag.
*/
skip(wireType, fieldNo) {
let start = this.pos;
switch (wireType) {
case WireType.Varint:
while (this.buf[this.pos++] & 0x80) {
// ignore
}
break;
// eslint-disable-next-line
// @ts-ignore TS7029: Fallthrough case in switch
case WireType.Bit64:
this.pos += 4;
// eslint-disable-next-line
// @ts-ignore TS7029: Fallthrough case in switch
case WireType.Bit32:
this.pos += 4;
break;
case WireType.LengthDelimited:
let len = this.uint32();
this.pos += len;
break;
case WireType.StartGroup:
for (;;) {
const [fn, wt] = this.tag();
if (wt === WireType.EndGroup) {
if (fieldNo !== undefined && fn !== fieldNo) {
throw new Error("invalid end group tag");
}
break;
}
this.skip(wt, fn);
}
break;
default:
throw new Error("cant skip wire type " + wireType);
}
this.assertBounds();
return this.buf.subarray(start, this.pos);
}
/**
* Throws error if position in byte array is out of range.
*/
assertBounds() {
if (this.pos > this.len)
throw new RangeError("premature EOF");
}
/**
* Read a `int32` field, a signed 32 bit varint.
*/
int32() {
return this.uint32() | 0;
}
/**
* Read a `sint32` field, a signed, zigzag-encoded 32-bit varint.
*/
sint32() {
let zze = this.uint32();
// decode zigzag
return (zze >>> 1) ^ -(zze & 1);
}
/**
* Read a `int64` field, a signed 64-bit varint.
*/
int64() {
return proto_int64_js_1.protoInt64.dec(...this.varint64());
}
/**
* Read a `uint64` field, an unsigned 64-bit varint.
*/
uint64() {
return proto_int64_js_1.protoInt64.uDec(...this.varint64());
}
/**
* Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint.
*/
sint64() {
let [lo, hi] = this.varint64();
// decode zig zag
let s = -(lo & 1);
lo = ((lo >>> 1) | ((hi & 1) << 31)) ^ s;
hi = (hi >>> 1) ^ s;
return proto_int64_js_1.protoInt64.dec(lo, hi);
}
/**
* Read a `bool` field, a variant.
*/
bool() {
let [lo, hi] = this.varint64();
return lo !== 0 || hi !== 0;
}
/**
* Read a `fixed32` field, an unsigned, fixed-length 32-bit integer.
*/
fixed32() {
return this.view.getUint32((this.pos += 4) - 4, true);
}
/**
* Read a `sfixed32` field, a signed, fixed-length 32-bit integer.
*/
sfixed32() {
return this.view.getInt32((this.pos += 4) - 4, true);
}
/**
* Read a `fixed64` field, an unsigned, fixed-length 64 bit integer.
*/
fixed64() {
return proto_int64_js_1.protoInt64.uDec(this.sfixed32(), this.sfixed32());
}
/**
* Read a `fixed64` field, a signed, fixed-length 64-bit integer.
*/
sfixed64() {
return proto_int64_js_1.protoInt64.dec(this.sfixed32(), this.sfixed32());
}
/**
* Read a `float` field, 32-bit floating point number.
*/
float() {
return this.view.getFloat32((this.pos += 4) - 4, true);
}
/**
* Read a `double` field, a 64-bit floating point number.
*/
double() {
return this.view.getFloat64((this.pos += 8) - 8, true);
}
/**
* Read a `bytes` field, length-delimited arbitrary data.
*/
bytes() {
let len = this.uint32(), start = this.pos;
this.pos += len;
this.assertBounds();
return this.buf.subarray(start, start + len);
}
/**
* Read a `string` field, length-delimited data converted to UTF-8 text.
*/
string() {
return this.textDecoder.decode(this.bytes());
}
}
exports.BinaryReader = BinaryReader;
+113
View File
@@ -0,0 +1,113 @@
import type { Message } from "./message.js";
import type { IBinaryReader, IBinaryWriter, WireType } from "./binary-encoding.js";
import type { FieldInfo } from "./field.js";
/**
* BinaryFormat is the contract for serializing messages to and from binary
* data. Implementations may be specific to a proto syntax, and can be
* reflection based, or delegate to speed optimized generated code.
*/
export interface BinaryFormat {
/**
* Provide options for parsing binary data.
*/
makeReadOptions(options?: Partial<BinaryReadOptions>): Readonly<BinaryReadOptions>;
/**
* Provide options for serializing binary data.
*/
makeWriteOptions(options?: Partial<BinaryWriteOptions>): Readonly<BinaryWriteOptions>;
/**
* Parse a message from binary data, merging fields.
*
* Supports two message encodings:
* - length-prefixed: delimitedMessageEncoding is false or omitted, and
* lengthOrEndTagFieldNo is the expected length of the message in the reader.
* - delimited: delimitedMessageEncoding is true, and lengthOrEndTagFieldNo is
* the field number in a tag with wire type end-group signalling the end of
* the message in the reader.
*
* delimitedMessageEncoding is optional for backwards compatibility.
*/
readMessage(message: Message, reader: IBinaryReader, lengthOrEndTagFieldNo: number, options: BinaryReadOptions, delimitedMessageEncoding?: boolean): void;
/**
* Parse a field from binary data, and store it in the given target.
*
* The target must be an initialized message object, with oneof groups,
* repeated fields and maps already present.
*/
readField(target: Record<string, any>, // eslint-disable-line @typescript-eslint/no-explicit-any -- `any` is the best choice for dynamic access
reader: IBinaryReader, field: FieldInfo, wireType: WireType, options: BinaryReadOptions): void;
/**
* Serialize a message to binary data.
*/
writeMessage(message: Message, writer: IBinaryWriter, options: BinaryWriteOptions): void;
/**
* Serialize a field value to binary data.
*
* The value must be an array for repeated fields, a record object for map
* fields. Only selected oneof fields should be passed to this method.
*/
writeField(field: FieldInfo, value: any, // eslint-disable-line @typescript-eslint/no-explicit-any -- `any` is the best choice for dynamic access
writer: IBinaryWriter, options: BinaryWriteOptions): void;
/**
* Retrieve the unknown fields for the given message.
*
* Unknown fields are well-formed protocol buffer serialized data for
* fields that the parserdoes not recognize.
*
* For more details see https://developers.google.com/protocol-buffers/docs/proto3#unknowns
*/
listUnknownFields(message: Message): ReadonlyArray<{
no: number;
wireType: WireType;
data: Uint8Array;
}>;
/**
* Discard unknown fields for the given message.
*/
discardUnknownFields(message: Message): void;
/**
* Retrieve the unknown fields for the given message and write them to
* the given writer. This method is called when a message is serialized,
* so the fields that are unknown to the parser persist through a round
* trip.
*/
writeUnknownFields(message: Message, writer: IBinaryWriter): void;
/**
* Store an unknown field for the given message. The parser will use this
* method if it does not recognize a field, unless the option
* `readUnknownFields` has been disabled.
*/
onUnknownField(message: Message, no: number, wireType: WireType, data: Uint8Array): void;
}
/**
* Options for parsing binary data.
*/
export interface BinaryReadOptions {
/**
* Retain unknown fields during parsing? The default behavior is to retain
* unknown fields and include them in the serialized output.
*
* For more details see https://developers.google.com/protocol-buffers/docs/proto3#unknowns
*/
readUnknownFields: boolean;
/**
* Allows to use a custom implementation to decode binary data.
*/
readerFactory: (bytes: Uint8Array) => IBinaryReader;
}
/**
* Options for serializing to binary data.
*/
export interface BinaryWriteOptions {
/**
* Include unknown fields in the serialized output? The default behavior
* is to retain unknown fields and include them in the serialized output.
*
* For more details see https://developers.google.com/protocol-buffers/docs/proto3#unknowns
*/
writeUnknownFields: boolean;
/**
* Allows to use a custom implementation to encode binary data.
*/
writerFactory: () => IBinaryWriter;
}
+15
View File
@@ -0,0 +1,15 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
+33
View File
@@ -0,0 +1,33 @@
import { reifyWkt } from "./private/reify-wkt.js";
import type { DescEnum, DescEnumValue, DescField, DescExtension, DescMessage, DescMethod, DescOneof, DescService } from "./descriptor-set.js";
import type { ScalarValue } from "./scalar.js";
import { LongType, ScalarType } from "./scalar.js";
interface CodegenInfo {
/**
* Name of the runtime library NPM package.
*/
readonly packageName: string;
readonly localName: (desc: DescEnum | DescEnumValue | DescMessage | DescExtension | DescOneof | DescField | DescService | DescMethod) => string;
readonly symbols: Record<RuntimeSymbolName, RuntimeSymbolInfo>;
readonly getUnwrappedFieldType: (field: DescField | DescExtension) => ScalarType | undefined;
readonly wktSourceFiles: readonly string[];
/**
* @deprecated please use scalarZeroValue instead
*/
readonly scalarDefaultValue: (type: ScalarType, longType: LongType) => any;
readonly scalarZeroValue: <T extends ScalarType, L extends LongType>(type: T, longType: L) => ScalarValue<T, L>;
/**
* @deprecated please use reifyWkt from @bufbuild/protoplugin/ecmascript instead
*/
readonly reifyWkt: typeof reifyWkt;
readonly safeIdentifier: (name: string) => string;
readonly safeObjectProperty: (name: string) => string;
}
type RuntimeSymbolName = "proto2" | "proto3" | "Message" | "PartialMessage" | "PlainMessage" | "FieldList" | "MessageType" | "Extension" | "BinaryReadOptions" | "BinaryWriteOptions" | "JsonReadOptions" | "JsonWriteOptions" | "JsonValue" | "JsonObject" | "protoDouble" | "protoInt64" | "ScalarType" | "LongType" | "MethodKind" | "MethodIdempotency" | "IMessageTypeRegistry";
type RuntimeSymbolInfo = {
typeOnly: boolean;
publicImportPath: string;
privateImportPath: string;
};
export declare const codegenInfo: CodegenInfo;
export {};
+69
View File
@@ -0,0 +1,69 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.codegenInfo = void 0;
const names_js_1 = require("./private/names.js");
const field_wrapper_js_1 = require("./private/field-wrapper.js");
const scalars_js_1 = require("./private/scalars.js");
const reify_wkt_js_1 = require("./private/reify-wkt.js");
const packageName = "@bufbuild/protobuf";
exports.codegenInfo = {
packageName: "@bufbuild/protobuf",
localName: names_js_1.localName,
reifyWkt: reify_wkt_js_1.reifyWkt,
getUnwrappedFieldType: field_wrapper_js_1.getUnwrappedFieldType,
scalarDefaultValue: scalars_js_1.scalarZeroValue,
scalarZeroValue: scalars_js_1.scalarZeroValue,
safeIdentifier: names_js_1.safeIdentifier,
safeObjectProperty: names_js_1.safeObjectProperty,
// prettier-ignore
symbols: {
proto2: { typeOnly: false, privateImportPath: "./proto2.js", publicImportPath: packageName },
proto3: { typeOnly: false, privateImportPath: "./proto3.js", publicImportPath: packageName },
Message: { typeOnly: false, privateImportPath: "./message.js", publicImportPath: packageName },
PartialMessage: { typeOnly: true, privateImportPath: "./message.js", publicImportPath: packageName },
PlainMessage: { typeOnly: true, privateImportPath: "./message.js", publicImportPath: packageName },
FieldList: { typeOnly: true, privateImportPath: "./field-list.js", publicImportPath: packageName },
MessageType: { typeOnly: true, privateImportPath: "./message-type.js", publicImportPath: packageName },
Extension: { typeOnly: true, privateImportPath: "./extension.js", publicImportPath: packageName },
BinaryReadOptions: { typeOnly: true, privateImportPath: "./binary-format.js", publicImportPath: packageName },
BinaryWriteOptions: { typeOnly: true, privateImportPath: "./binary-format.js", publicImportPath: packageName },
JsonReadOptions: { typeOnly: true, privateImportPath: "./json-format.js", publicImportPath: packageName },
JsonWriteOptions: { typeOnly: true, privateImportPath: "./json-format.js", publicImportPath: packageName },
JsonValue: { typeOnly: true, privateImportPath: "./json-format.js", publicImportPath: packageName },
JsonObject: { typeOnly: true, privateImportPath: "./json-format.js", publicImportPath: packageName },
protoDouble: { typeOnly: false, privateImportPath: "./proto-double.js", publicImportPath: packageName },
protoInt64: { typeOnly: false, privateImportPath: "./proto-int64.js", publicImportPath: packageName },
ScalarType: { typeOnly: false, privateImportPath: "./scalar.js", publicImportPath: packageName },
LongType: { typeOnly: false, privateImportPath: "./scalar.js", publicImportPath: packageName },
MethodKind: { typeOnly: false, privateImportPath: "./service-type.js", publicImportPath: packageName },
MethodIdempotency: { typeOnly: false, privateImportPath: "./service-type.js", publicImportPath: packageName },
IMessageTypeRegistry: { typeOnly: true, privateImportPath: "./type-registry.js", publicImportPath: packageName },
},
wktSourceFiles: [
"google/protobuf/compiler/plugin.proto",
"google/protobuf/any.proto",
"google/protobuf/api.proto",
"google/protobuf/descriptor.proto",
"google/protobuf/duration.proto",
"google/protobuf/empty.proto",
"google/protobuf/field_mask.proto",
"google/protobuf/source_context.proto",
"google/protobuf/struct.proto",
"google/protobuf/timestamp.proto",
"google/protobuf/type.proto",
"google/protobuf/wrappers.proto",
],
};
+36
View File
@@ -0,0 +1,36 @@
import { FeatureSetDefaults, FileDescriptorProto, FileDescriptorSet } from "./google/protobuf/descriptor_pb.js";
import type { DescriptorSet } from "./descriptor-set.js";
import type { BinaryReadOptions, BinaryWriteOptions } from "./binary-format.js";
/**
* Create a DescriptorSet, a convenient interface for working with a set of
* google.protobuf.FileDescriptorProto.
*
* Note that files must be given in topological order, so each file appears
* before any file that imports it. Protocol buffer compilers always produce
* files in topological order.
*/
export declare function createDescriptorSet(input: FileDescriptorProto[] | FileDescriptorSet | Uint8Array, options?: CreateDescriptorSetOptions): DescriptorSet;
/**
* Options to createDescriptorSet()
*/
interface CreateDescriptorSetOptions {
/**
* Editions support language-specific features with extensions to
* google.protobuf.FeatureSet. They can define defaults, and specify on
* which targets the features can be set.
*
* To create a DescriptorSet that provides your language-specific features,
* you have to provide a google.protobuf.FeatureSetDefaults message in this
* option. It can also specify the minimum and maximum supported edition.
*
* The defaults can be generated with `protoc` - see the flag
* `--experimental_edition_defaults_out`.
*/
featureSetDefaults?: FeatureSetDefaults;
/**
* Internally, data is serialized when features are resolved. The
* serialization options given here will be used for feature resolution.
*/
serializationOptions?: Partial<BinaryReadOptions & BinaryWriteOptions>;
}
export {};
+910
View File
@@ -0,0 +1,910 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.createDescriptorSet = void 0;
const descriptor_pb_js_1 = require("./google/protobuf/descriptor_pb.js");
const assert_js_1 = require("./private/assert.js");
const service_type_js_1 = require("./service-type.js");
const names_js_1 = require("./private/names.js");
const text_format_js_1 = require("./private/text-format.js");
const feature_set_js_1 = require("./private/feature-set.js");
const scalar_js_1 = require("./scalar.js");
const is_message_js_1 = require("./is-message.js");
/**
* Create a DescriptorSet, a convenient interface for working with a set of
* google.protobuf.FileDescriptorProto.
*
* Note that files must be given in topological order, so each file appears
* before any file that imports it. Protocol buffer compilers always produce
* files in topological order.
*/
function createDescriptorSet(input, options) {
var _a;
const cart = {
files: [],
enums: new Map(),
messages: new Map(),
services: new Map(),
extensions: new Map(),
mapEntries: new Map(),
};
const fileDescriptors = (0, is_message_js_1.isMessage)(input, descriptor_pb_js_1.FileDescriptorSet)
? input.file
: input instanceof Uint8Array
? descriptor_pb_js_1.FileDescriptorSet.fromBinary(input).file
: input;
const resolverByEdition = new Map();
for (const proto of fileDescriptors) {
const edition = (_a = proto.edition) !== null && _a !== void 0 ? _a : parseFileSyntax(proto.syntax, proto.edition).edition;
let resolveFeatures = resolverByEdition.get(edition);
if (resolveFeatures === undefined) {
resolveFeatures = (0, feature_set_js_1.createFeatureResolver)(edition, options === null || options === void 0 ? void 0 : options.featureSetDefaults, options === null || options === void 0 ? void 0 : options.serializationOptions);
resolverByEdition.set(edition, resolveFeatures);
}
addFile(proto, cart, resolveFeatures);
}
return cart;
}
exports.createDescriptorSet = createDescriptorSet;
/**
* Create a descriptor for a file.
*/
function addFile(proto, cart, resolveFeatures) {
var _a, _b;
(0, assert_js_1.assert)(proto.name, `invalid FileDescriptorProto: missing name`);
const file = Object.assign(Object.assign({ kind: "file", proto, deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false }, parseFileSyntax(proto.syntax, proto.edition)), { name: proto.name.replace(/\.proto/, ""), dependencies: findFileDependencies(proto, cart), enums: [], messages: [], extensions: [], services: [], toString() {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions -- we asserted above
return `file ${this.proto.name}`;
},
getSyntaxComments() {
return findComments(this.proto.sourceCodeInfo, [
FieldNumber.FileDescriptorProto_Syntax,
]);
},
getPackageComments() {
return findComments(this.proto.sourceCodeInfo, [
FieldNumber.FileDescriptorProto_Package,
]);
},
getFeatures() {
var _a;
return resolveFeatures((_a = proto.options) === null || _a === void 0 ? void 0 : _a.features);
} });
cart.mapEntries.clear(); // map entries are local to the file, we can safely discard
for (const enumProto of proto.enumType) {
addEnum(enumProto, file, undefined, cart, resolveFeatures);
}
for (const messageProto of proto.messageType) {
addMessage(messageProto, file, undefined, cart, resolveFeatures);
}
for (const serviceProto of proto.service) {
addService(serviceProto, file, cart, resolveFeatures);
}
addExtensions(file, cart, resolveFeatures);
for (const mapEntry of cart.mapEntries.values()) {
addFields(mapEntry, cart, resolveFeatures);
}
for (const message of file.messages) {
addFields(message, cart, resolveFeatures);
addExtensions(message, cart, resolveFeatures);
}
cart.mapEntries.clear(); // map entries are local to the file, we can safely discard
cart.files.push(file);
}
/**
* Create descriptors for extensions, and add them to the message / file,
* and to our cart.
* Recurses into nested types.
*/
function addExtensions(desc, cart, resolveFeatures) {
switch (desc.kind) {
case "file":
for (const proto of desc.proto.extension) {
const ext = newExtension(proto, desc, undefined, cart, resolveFeatures);
desc.extensions.push(ext);
cart.extensions.set(ext.typeName, ext);
}
break;
case "message":
for (const proto of desc.proto.extension) {
const ext = newExtension(proto, desc.file, desc, cart, resolveFeatures);
desc.nestedExtensions.push(ext);
cart.extensions.set(ext.typeName, ext);
}
for (const message of desc.nestedMessages) {
addExtensions(message, cart, resolveFeatures);
}
break;
}
}
/**
* Create descriptors for fields and oneof groups, and add them to the message.
* Recurses into nested types.
*/
function addFields(message, cart, resolveFeatures) {
const allOneofs = message.proto.oneofDecl.map((proto) => newOneof(proto, message, resolveFeatures));
const oneofsSeen = new Set();
for (const proto of message.proto.field) {
const oneof = findOneof(proto, allOneofs);
const field = newField(proto, message.file, message, oneof, cart, resolveFeatures);
message.fields.push(field);
if (oneof === undefined) {
message.members.push(field);
}
else {
oneof.fields.push(field);
if (!oneofsSeen.has(oneof)) {
oneofsSeen.add(oneof);
message.members.push(oneof);
}
}
}
for (const oneof of allOneofs.filter((o) => oneofsSeen.has(o))) {
message.oneofs.push(oneof);
}
for (const child of message.nestedMessages) {
addFields(child, cart, resolveFeatures);
}
}
/**
* Create a descriptor for an enumeration, and add it our cart and to the
* parent type, if any.
*/
function addEnum(proto, file, parent, cart, resolveFeatures) {
var _a, _b, _c;
(0, assert_js_1.assert)(proto.name, `invalid EnumDescriptorProto: missing name`);
const desc = {
kind: "enum",
proto,
deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,
file,
parent,
name: proto.name,
typeName: makeTypeName(proto, parent, file),
values: [],
sharedPrefix: (0, names_js_1.findEnumSharedPrefix)(proto.name, proto.value.map((v) => { var _a; return (_a = v.name) !== null && _a !== void 0 ? _a : ""; })),
toString() {
return `enum ${this.typeName}`;
},
getComments() {
const path = this.parent
? [
...this.parent.getComments().sourcePath,
FieldNumber.DescriptorProto_EnumType,
this.parent.proto.enumType.indexOf(this.proto),
]
: [
FieldNumber.FileDescriptorProto_EnumType,
this.file.proto.enumType.indexOf(this.proto),
];
return findComments(file.proto.sourceCodeInfo, path);
},
getFeatures() {
var _a, _b;
return resolveFeatures((_a = parent === null || parent === void 0 ? void 0 : parent.getFeatures()) !== null && _a !== void 0 ? _a : file.getFeatures(), (_b = proto.options) === null || _b === void 0 ? void 0 : _b.features);
},
};
cart.enums.set(desc.typeName, desc);
proto.value.forEach((proto) => {
var _a, _b;
(0, assert_js_1.assert)(proto.name, `invalid EnumValueDescriptorProto: missing name`);
(0, assert_js_1.assert)(proto.number !== undefined, `invalid EnumValueDescriptorProto: missing number`);
desc.values.push({
kind: "enum_value",
proto,
deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,
parent: desc,
name: proto.name,
number: proto.number,
toString() {
return `enum value ${desc.typeName}.${this.name}`;
},
declarationString() {
var _a;
let str = `${this.name} = ${this.number}`;
if (((_a = this.proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) === true) {
str += " [deprecated = true]";
}
return str;
},
getComments() {
const path = [
...this.parent.getComments().sourcePath,
FieldNumber.EnumDescriptorProto_Value,
this.parent.proto.value.indexOf(this.proto),
];
return findComments(file.proto.sourceCodeInfo, path);
},
getFeatures() {
var _a;
return resolveFeatures(desc.getFeatures(), (_a = proto.options) === null || _a === void 0 ? void 0 : _a.features);
},
});
});
((_c = parent === null || parent === void 0 ? void 0 : parent.nestedEnums) !== null && _c !== void 0 ? _c : file.enums).push(desc);
}
/**
* Create a descriptor for a message, including nested types, and add it to our
* cart. Note that this does not create descriptors fields.
*/
function addMessage(proto, file, parent, cart, resolveFeatures) {
var _a, _b, _c, _d;
(0, assert_js_1.assert)(proto.name, `invalid DescriptorProto: missing name`);
const desc = {
kind: "message",
proto,
deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,
file,
parent,
name: proto.name,
typeName: makeTypeName(proto, parent, file),
fields: [],
oneofs: [],
members: [],
nestedEnums: [],
nestedMessages: [],
nestedExtensions: [],
toString() {
return `message ${this.typeName}`;
},
getComments() {
const path = this.parent
? [
...this.parent.getComments().sourcePath,
FieldNumber.DescriptorProto_NestedType,
this.parent.proto.nestedType.indexOf(this.proto),
]
: [
FieldNumber.FileDescriptorProto_MessageType,
this.file.proto.messageType.indexOf(this.proto),
];
return findComments(file.proto.sourceCodeInfo, path);
},
getFeatures() {
var _a, _b;
return resolveFeatures((_a = parent === null || parent === void 0 ? void 0 : parent.getFeatures()) !== null && _a !== void 0 ? _a : file.getFeatures(), (_b = proto.options) === null || _b === void 0 ? void 0 : _b.features);
},
};
if (((_c = proto.options) === null || _c === void 0 ? void 0 : _c.mapEntry) === true) {
cart.mapEntries.set(desc.typeName, desc);
}
else {
((_d = parent === null || parent === void 0 ? void 0 : parent.nestedMessages) !== null && _d !== void 0 ? _d : file.messages).push(desc);
cart.messages.set(desc.typeName, desc);
}
for (const enumProto of proto.enumType) {
addEnum(enumProto, file, desc, cart, resolveFeatures);
}
for (const messageProto of proto.nestedType) {
addMessage(messageProto, file, desc, cart, resolveFeatures);
}
}
/**
* Create a descriptor for a service, including methods, and add it to our
* cart.
*/
function addService(proto, file, cart, resolveFeatures) {
var _a, _b;
(0, assert_js_1.assert)(proto.name, `invalid ServiceDescriptorProto: missing name`);
const desc = {
kind: "service",
proto,
deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,
file,
name: proto.name,
typeName: makeTypeName(proto, undefined, file),
methods: [],
toString() {
return `service ${this.typeName}`;
},
getComments() {
const path = [
FieldNumber.FileDescriptorProto_Service,
this.file.proto.service.indexOf(this.proto),
];
return findComments(file.proto.sourceCodeInfo, path);
},
getFeatures() {
var _a;
return resolveFeatures(file.getFeatures(), (_a = proto.options) === null || _a === void 0 ? void 0 : _a.features);
},
};
file.services.push(desc);
cart.services.set(desc.typeName, desc);
for (const methodProto of proto.method) {
desc.methods.push(newMethod(methodProto, desc, cart, resolveFeatures));
}
}
/**
* Create a descriptor for a method.
*/
function newMethod(proto, parent, cart, resolveFeatures) {
var _a, _b, _c;
(0, assert_js_1.assert)(proto.name, `invalid MethodDescriptorProto: missing name`);
(0, assert_js_1.assert)(proto.inputType, `invalid MethodDescriptorProto: missing input_type`);
(0, assert_js_1.assert)(proto.outputType, `invalid MethodDescriptorProto: missing output_type`);
let methodKind;
if (proto.clientStreaming === true && proto.serverStreaming === true) {
methodKind = service_type_js_1.MethodKind.BiDiStreaming;
}
else if (proto.clientStreaming === true) {
methodKind = service_type_js_1.MethodKind.ClientStreaming;
}
else if (proto.serverStreaming === true) {
methodKind = service_type_js_1.MethodKind.ServerStreaming;
}
else {
methodKind = service_type_js_1.MethodKind.Unary;
}
let idempotency;
switch ((_a = proto.options) === null || _a === void 0 ? void 0 : _a.idempotencyLevel) {
case descriptor_pb_js_1.MethodOptions_IdempotencyLevel.IDEMPOTENT:
idempotency = service_type_js_1.MethodIdempotency.Idempotent;
break;
case descriptor_pb_js_1.MethodOptions_IdempotencyLevel.NO_SIDE_EFFECTS:
idempotency = service_type_js_1.MethodIdempotency.NoSideEffects;
break;
case descriptor_pb_js_1.MethodOptions_IdempotencyLevel.IDEMPOTENCY_UNKNOWN:
case undefined:
idempotency = undefined;
break;
}
const input = cart.messages.get(trimLeadingDot(proto.inputType));
const output = cart.messages.get(trimLeadingDot(proto.outputType));
(0, assert_js_1.assert)(input, `invalid MethodDescriptorProto: input_type ${proto.inputType} not found`);
(0, assert_js_1.assert)(output, `invalid MethodDescriptorProto: output_type ${proto.inputType} not found`);
const name = proto.name;
return {
kind: "rpc",
proto,
deprecated: (_c = (_b = proto.options) === null || _b === void 0 ? void 0 : _b.deprecated) !== null && _c !== void 0 ? _c : false,
parent,
name,
methodKind,
input,
output,
idempotency,
toString() {
return `rpc ${parent.typeName}.${name}`;
},
getComments() {
const path = [
...this.parent.getComments().sourcePath,
FieldNumber.ServiceDescriptorProto_Method,
this.parent.proto.method.indexOf(this.proto),
];
return findComments(parent.file.proto.sourceCodeInfo, path);
},
getFeatures() {
var _a;
return resolveFeatures(parent.getFeatures(), (_a = proto.options) === null || _a === void 0 ? void 0 : _a.features);
},
};
}
/**
* Create a descriptor for a oneof group.
*/
function newOneof(proto, parent, resolveFeatures) {
(0, assert_js_1.assert)(proto.name, `invalid OneofDescriptorProto: missing name`);
return {
kind: "oneof",
proto,
deprecated: false,
parent,
fields: [],
name: proto.name,
toString() {
return `oneof ${parent.typeName}.${this.name}`;
},
getComments() {
const path = [
...this.parent.getComments().sourcePath,
FieldNumber.DescriptorProto_OneofDecl,
this.parent.proto.oneofDecl.indexOf(this.proto),
];
return findComments(parent.file.proto.sourceCodeInfo, path);
},
getFeatures() {
var _a;
return resolveFeatures(parent.getFeatures(), (_a = proto.options) === null || _a === void 0 ? void 0 : _a.features);
},
};
}
/**
* Create a descriptor for a field.
*/
function newField(proto, file, parent, oneof, cart, resolveFeatures) {
var _a, _b, _c;
(0, assert_js_1.assert)(proto.name, `invalid FieldDescriptorProto: missing name`);
(0, assert_js_1.assert)(proto.number, `invalid FieldDescriptorProto: missing number`);
(0, assert_js_1.assert)(proto.type, `invalid FieldDescriptorProto: missing type`);
const common = {
proto,
deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,
name: proto.name,
number: proto.number,
parent,
oneof,
optional: isOptionalField(proto, file.syntax),
packedByDefault: isPackedFieldByDefault(proto, resolveFeatures),
packed: isPackedField(file, parent, proto, resolveFeatures),
jsonName: proto.jsonName === (0, names_js_1.fieldJsonName)(proto.name) ? undefined : proto.jsonName,
scalar: undefined,
longType: undefined,
message: undefined,
enum: undefined,
mapKey: undefined,
mapValue: undefined,
declarationString,
// toString, getComments, getFeatures are overridden in newExtension
toString() {
return `field ${this.parent.typeName}.${this.name}`;
},
getComments() {
const path = [
...this.parent.getComments().sourcePath,
FieldNumber.DescriptorProto_Field,
this.parent.proto.field.indexOf(this.proto),
];
return findComments(file.proto.sourceCodeInfo, path);
},
getFeatures() {
var _a;
return resolveFeatures(parent.getFeatures(), (_a = proto.options) === null || _a === void 0 ? void 0 : _a.features);
},
};
const repeated = proto.label === descriptor_pb_js_1.FieldDescriptorProto_Label.REPEATED;
switch (proto.type) {
case descriptor_pb_js_1.FieldDescriptorProto_Type.MESSAGE:
case descriptor_pb_js_1.FieldDescriptorProto_Type.GROUP: {
(0, assert_js_1.assert)(proto.typeName, `invalid FieldDescriptorProto: missing type_name`);
const mapEntry = cart.mapEntries.get(trimLeadingDot(proto.typeName));
if (mapEntry !== undefined) {
(0, assert_js_1.assert)(repeated, `invalid FieldDescriptorProto: expected map entry to be repeated`);
return Object.assign(Object.assign(Object.assign({}, common), { kind: "field", fieldKind: "map", repeated: false }), getMapFieldTypes(mapEntry));
}
const message = cart.messages.get(trimLeadingDot(proto.typeName));
(0, assert_js_1.assert)(message !== undefined, `invalid FieldDescriptorProto: type_name ${proto.typeName} not found`);
return Object.assign(Object.assign({}, common), { kind: "field", fieldKind: "message", repeated,
message });
}
case descriptor_pb_js_1.FieldDescriptorProto_Type.ENUM: {
(0, assert_js_1.assert)(proto.typeName, `invalid FieldDescriptorProto: missing type_name`);
const e = cart.enums.get(trimLeadingDot(proto.typeName));
(0, assert_js_1.assert)(e !== undefined, `invalid FieldDescriptorProto: type_name ${proto.typeName} not found`);
return Object.assign(Object.assign({}, common), { kind: "field", fieldKind: "enum", getDefaultValue,
repeated, enum: e });
}
default: {
const scalar = fieldTypeToScalarType[proto.type];
(0, assert_js_1.assert)(scalar, `invalid FieldDescriptorProto: unknown type ${proto.type}`);
return Object.assign(Object.assign({}, common), { kind: "field", fieldKind: "scalar", getDefaultValue,
repeated,
scalar, longType: ((_c = proto.options) === null || _c === void 0 ? void 0 : _c.jstype) == descriptor_pb_js_1.FieldOptions_JSType.JS_STRING
? scalar_js_1.LongType.STRING
: scalar_js_1.LongType.BIGINT });
}
}
}
/**
* Create a descriptor for an extension field.
*/
function newExtension(proto, file, parent, cart, resolveFeatures) {
(0, assert_js_1.assert)(proto.extendee, `invalid FieldDescriptorProto: missing extendee`);
const field = newField(proto, file, null, // to safe us many lines of duplicated code, we trick the type system
undefined, cart, resolveFeatures);
const extendee = cart.messages.get(trimLeadingDot(proto.extendee));
(0, assert_js_1.assert)(extendee, `invalid FieldDescriptorProto: extendee ${proto.extendee} not found`);
return Object.assign(Object.assign({}, field), { kind: "extension", typeName: makeTypeName(proto, parent, file), parent,
file,
extendee,
// Must override toString, getComments, getFeatures from newField, because we
// call newField with parent undefined.
toString() {
return `extension ${this.typeName}`;
},
getComments() {
const path = this.parent
? [
...this.parent.getComments().sourcePath,
FieldNumber.DescriptorProto_Extension,
this.parent.proto.extension.indexOf(proto),
]
: [
FieldNumber.FileDescriptorProto_Extension,
this.file.proto.extension.indexOf(proto),
];
return findComments(file.proto.sourceCodeInfo, path);
},
getFeatures() {
var _a;
return resolveFeatures((parent !== null && parent !== void 0 ? parent : file).getFeatures(), (_a = proto.options) === null || _a === void 0 ? void 0 : _a.features);
} });
}
/**
* Parse the "syntax" and "edition" fields, stripping test editions.
*/
function parseFileSyntax(syntax, edition) {
let e;
let s;
switch (syntax) {
case undefined:
case "proto2":
s = "proto2";
e = descriptor_pb_js_1.Edition.EDITION_PROTO2;
break;
case "proto3":
s = "proto3";
e = descriptor_pb_js_1.Edition.EDITION_PROTO3;
break;
case "editions":
s = "editions";
switch (edition) {
case undefined:
case descriptor_pb_js_1.Edition.EDITION_1_TEST_ONLY:
case descriptor_pb_js_1.Edition.EDITION_2_TEST_ONLY:
case descriptor_pb_js_1.Edition.EDITION_99997_TEST_ONLY:
case descriptor_pb_js_1.Edition.EDITION_99998_TEST_ONLY:
case descriptor_pb_js_1.Edition.EDITION_99999_TEST_ONLY:
case descriptor_pb_js_1.Edition.EDITION_UNKNOWN:
e = descriptor_pb_js_1.Edition.EDITION_UNKNOWN;
break;
default:
e = edition;
break;
}
break;
default:
throw new Error(`invalid FileDescriptorProto: unsupported syntax: ${syntax}`);
}
if (syntax === "editions" && edition === descriptor_pb_js_1.Edition.EDITION_UNKNOWN) {
throw new Error(`invalid FileDescriptorProto: syntax ${syntax} cannot have edition ${String(edition)}`);
}
return {
syntax: s,
edition: e,
};
}
/**
* Resolve dependencies of FileDescriptorProto to DescFile.
*/
function findFileDependencies(proto, cart) {
return proto.dependency.map((wantName) => {
const dep = cart.files.find((f) => f.proto.name === wantName);
(0, assert_js_1.assert)(dep);
return dep;
});
}
/**
* Create a fully qualified name for a protobuf type or extension field.
*
* The fully qualified name for messages, enumerations, and services is
* constructed by concatenating the package name (if present), parent
* message names (for nested types), and the type name. We omit the leading
* dot added by protobuf compilers. Examples:
* - mypackage.MyMessage
* - mypackage.MyMessage.NestedMessage
*
* The fully qualified name for extension fields is constructed by
* concatenating the package name (if present), parent message names (for
* extensions declared within a message), and the field name. Examples:
* - mypackage.extfield
* - mypackage.MyMessage.extfield
*/
function makeTypeName(proto, parent, file) {
(0, assert_js_1.assert)(proto.name, `invalid ${proto.getType().typeName}: missing name`);
let typeName;
if (parent) {
typeName = `${parent.typeName}.${proto.name}`;
}
else if (file.proto.package !== undefined) {
typeName = `${file.proto.package}.${proto.name}`;
}
else {
typeName = `${proto.name}`;
}
return typeName;
}
/**
* Remove the leading dot from a fully qualified type name.
*/
function trimLeadingDot(typeName) {
return typeName.startsWith(".") ? typeName.substring(1) : typeName;
}
function getMapFieldTypes(mapEntry) {
var _a, _b;
(0, assert_js_1.assert)((_a = mapEntry.proto.options) === null || _a === void 0 ? void 0 : _a.mapEntry, `invalid DescriptorProto: expected ${mapEntry.toString()} to be a map entry`);
(0, assert_js_1.assert)(mapEntry.fields.length === 2, `invalid DescriptorProto: map entry ${mapEntry.toString()} has ${mapEntry.fields.length} fields`);
const keyField = mapEntry.fields.find((f) => f.proto.number === 1);
(0, assert_js_1.assert)(keyField, `invalid DescriptorProto: map entry ${mapEntry.toString()} is missing key field`);
const mapKey = keyField.scalar;
(0, assert_js_1.assert)(mapKey !== undefined &&
mapKey !== scalar_js_1.ScalarType.BYTES &&
mapKey !== scalar_js_1.ScalarType.FLOAT &&
mapKey !== scalar_js_1.ScalarType.DOUBLE, `invalid DescriptorProto: map entry ${mapEntry.toString()} has unexpected key type ${(_b = keyField.proto.type) !== null && _b !== void 0 ? _b : -1}`);
const valueField = mapEntry.fields.find((f) => f.proto.number === 2);
(0, assert_js_1.assert)(valueField, `invalid DescriptorProto: map entry ${mapEntry.toString()} is missing value field`);
switch (valueField.fieldKind) {
case "scalar":
return {
mapKey,
mapValue: Object.assign(Object.assign({}, valueField), { kind: "scalar" }),
};
case "message":
return {
mapKey,
mapValue: Object.assign(Object.assign({}, valueField), { kind: "message" }),
};
case "enum":
return {
mapKey,
mapValue: Object.assign(Object.assign({}, valueField), { kind: "enum" }),
};
default:
throw new Error("invalid DescriptorProto: unsupported map entry value field");
}
}
/**
* Did the user put the field in a oneof group?
* This handles proto3 optionals.
*/
function findOneof(proto, allOneofs) {
var _a;
const oneofIndex = proto.oneofIndex;
if (oneofIndex === undefined) {
return undefined;
}
let oneof;
if (proto.proto3Optional !== true) {
oneof = allOneofs[oneofIndex];
(0, assert_js_1.assert)(oneof, `invalid FieldDescriptorProto: oneof #${oneofIndex} for field #${(_a = proto.number) !== null && _a !== void 0 ? _a : -1} not found`);
}
return oneof;
}
/**
* Did the user use the `optional` keyword?
* This handles proto3 optionals.
*/
function isOptionalField(proto, syntax) {
switch (syntax) {
case "proto2":
return (proto.oneofIndex === undefined &&
proto.label === descriptor_pb_js_1.FieldDescriptorProto_Label.OPTIONAL);
case "proto3":
return proto.proto3Optional === true;
case "editions":
return false;
}
}
/**
* Is this field packed by default? Only valid for repeated enum fields, and
* for repeated scalar fields except BYTES and STRING.
*
* In proto3 syntax, fields are packed by default. In proto2 syntax, fields
* are unpacked by default. With editions, the default is whatever the edition
* specifies as a default. In edition 2023, fields are packed by default.
*/
function isPackedFieldByDefault(proto, resolveFeatures) {
const { repeatedFieldEncoding } = resolveFeatures();
if (repeatedFieldEncoding != descriptor_pb_js_1.FeatureSet_RepeatedFieldEncoding.PACKED) {
return false;
}
// From the proto3 language guide:
// > In proto3, repeated fields of scalar numeric types are packed by default.
// This information is incomplete - according to the conformance tests, BOOL
// and ENUM are packed by default as well. This means only STRING and BYTES
// are not packed by default, which makes sense because they are length-delimited.
switch (proto.type) {
case descriptor_pb_js_1.FieldDescriptorProto_Type.STRING:
case descriptor_pb_js_1.FieldDescriptorProto_Type.BYTES:
case descriptor_pb_js_1.FieldDescriptorProto_Type.GROUP:
case descriptor_pb_js_1.FieldDescriptorProto_Type.MESSAGE:
return false;
default:
return true;
}
}
/**
* Pack this repeated field?
*
* Respects field type, proto2/proto3 defaults and the `packed` option, or
* edition defaults and the edition features.repeated_field_encoding options.
*/
function isPackedField(file, parent, proto, resolveFeatures) {
var _a, _b, _c, _d, _e, _f;
switch (proto.type) {
case descriptor_pb_js_1.FieldDescriptorProto_Type.STRING:
case descriptor_pb_js_1.FieldDescriptorProto_Type.BYTES:
case descriptor_pb_js_1.FieldDescriptorProto_Type.GROUP:
case descriptor_pb_js_1.FieldDescriptorProto_Type.MESSAGE:
// length-delimited types cannot be packed
return false;
default:
switch (file.edition) {
case descriptor_pb_js_1.Edition.EDITION_PROTO2:
return (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.packed) !== null && _b !== void 0 ? _b : false;
case descriptor_pb_js_1.Edition.EDITION_PROTO3:
return (_d = (_c = proto.options) === null || _c === void 0 ? void 0 : _c.packed) !== null && _d !== void 0 ? _d : true;
default: {
const { repeatedFieldEncoding } = resolveFeatures((_e = parent === null || parent === void 0 ? void 0 : parent.getFeatures()) !== null && _e !== void 0 ? _e : file.getFeatures(), (_f = proto.options) === null || _f === void 0 ? void 0 : _f.features);
return (repeatedFieldEncoding == descriptor_pb_js_1.FeatureSet_RepeatedFieldEncoding.PACKED);
}
}
}
}
/**
* Map from a compiler-generated field type to our ScalarType, which is a
* subset of field types declared by protobuf enum google.protobuf.FieldDescriptorProto.
*/
const fieldTypeToScalarType = {
[descriptor_pb_js_1.FieldDescriptorProto_Type.DOUBLE]: scalar_js_1.ScalarType.DOUBLE,
[descriptor_pb_js_1.FieldDescriptorProto_Type.FLOAT]: scalar_js_1.ScalarType.FLOAT,
[descriptor_pb_js_1.FieldDescriptorProto_Type.INT64]: scalar_js_1.ScalarType.INT64,
[descriptor_pb_js_1.FieldDescriptorProto_Type.UINT64]: scalar_js_1.ScalarType.UINT64,
[descriptor_pb_js_1.FieldDescriptorProto_Type.INT32]: scalar_js_1.ScalarType.INT32,
[descriptor_pb_js_1.FieldDescriptorProto_Type.FIXED64]: scalar_js_1.ScalarType.FIXED64,
[descriptor_pb_js_1.FieldDescriptorProto_Type.FIXED32]: scalar_js_1.ScalarType.FIXED32,
[descriptor_pb_js_1.FieldDescriptorProto_Type.BOOL]: scalar_js_1.ScalarType.BOOL,
[descriptor_pb_js_1.FieldDescriptorProto_Type.STRING]: scalar_js_1.ScalarType.STRING,
[descriptor_pb_js_1.FieldDescriptorProto_Type.GROUP]: undefined,
[descriptor_pb_js_1.FieldDescriptorProto_Type.MESSAGE]: undefined,
[descriptor_pb_js_1.FieldDescriptorProto_Type.BYTES]: scalar_js_1.ScalarType.BYTES,
[descriptor_pb_js_1.FieldDescriptorProto_Type.UINT32]: scalar_js_1.ScalarType.UINT32,
[descriptor_pb_js_1.FieldDescriptorProto_Type.ENUM]: undefined,
[descriptor_pb_js_1.FieldDescriptorProto_Type.SFIXED32]: scalar_js_1.ScalarType.SFIXED32,
[descriptor_pb_js_1.FieldDescriptorProto_Type.SFIXED64]: scalar_js_1.ScalarType.SFIXED64,
[descriptor_pb_js_1.FieldDescriptorProto_Type.SINT32]: scalar_js_1.ScalarType.SINT32,
[descriptor_pb_js_1.FieldDescriptorProto_Type.SINT64]: scalar_js_1.ScalarType.SINT64,
};
/**
* Find comments.
*/
function findComments(sourceCodeInfo, sourcePath) {
if (!sourceCodeInfo) {
return {
leadingDetached: [],
sourcePath,
};
}
for (const location of sourceCodeInfo.location) {
if (location.path.length !== sourcePath.length) {
continue;
}
if (location.path.some((value, index) => sourcePath[index] !== value)) {
continue;
}
return {
leadingDetached: location.leadingDetachedComments,
leading: location.leadingComments,
trailing: location.trailingComments,
sourcePath,
};
}
return {
leadingDetached: [],
sourcePath,
};
}
/**
* The following field numbers are used to find comments in
* google.protobuf.SourceCodeInfo.
*/
var FieldNumber;
(function (FieldNumber) {
FieldNumber[FieldNumber["FileDescriptorProto_Package"] = 2] = "FileDescriptorProto_Package";
FieldNumber[FieldNumber["FileDescriptorProto_MessageType"] = 4] = "FileDescriptorProto_MessageType";
FieldNumber[FieldNumber["FileDescriptorProto_EnumType"] = 5] = "FileDescriptorProto_EnumType";
FieldNumber[FieldNumber["FileDescriptorProto_Service"] = 6] = "FileDescriptorProto_Service";
FieldNumber[FieldNumber["FileDescriptorProto_Extension"] = 7] = "FileDescriptorProto_Extension";
FieldNumber[FieldNumber["FileDescriptorProto_Syntax"] = 12] = "FileDescriptorProto_Syntax";
FieldNumber[FieldNumber["DescriptorProto_Field"] = 2] = "DescriptorProto_Field";
FieldNumber[FieldNumber["DescriptorProto_NestedType"] = 3] = "DescriptorProto_NestedType";
FieldNumber[FieldNumber["DescriptorProto_EnumType"] = 4] = "DescriptorProto_EnumType";
FieldNumber[FieldNumber["DescriptorProto_Extension"] = 6] = "DescriptorProto_Extension";
FieldNumber[FieldNumber["DescriptorProto_OneofDecl"] = 8] = "DescriptorProto_OneofDecl";
FieldNumber[FieldNumber["EnumDescriptorProto_Value"] = 2] = "EnumDescriptorProto_Value";
FieldNumber[FieldNumber["ServiceDescriptorProto_Method"] = 2] = "ServiceDescriptorProto_Method";
})(FieldNumber || (FieldNumber = {}));
/**
* Return a string that matches the definition of a field in the protobuf
* source. Does not take custom options into account.
*/
function declarationString() {
var _a, _b, _c;
const parts = [];
if (this.repeated) {
parts.push("repeated");
}
if (this.optional) {
parts.push("optional");
}
const file = this.kind === "extension" ? this.file : this.parent.file;
if (file.syntax == "proto2" &&
this.proto.label === descriptor_pb_js_1.FieldDescriptorProto_Label.REQUIRED) {
parts.push("required");
}
let type;
switch (this.fieldKind) {
case "scalar":
type = scalar_js_1.ScalarType[this.scalar].toLowerCase();
break;
case "enum":
type = this.enum.typeName;
break;
case "message":
type = this.message.typeName;
break;
case "map": {
const k = scalar_js_1.ScalarType[this.mapKey].toLowerCase();
let v;
switch (this.mapValue.kind) {
case "scalar":
v = scalar_js_1.ScalarType[this.mapValue.scalar].toLowerCase();
break;
case "enum":
v = this.mapValue.enum.typeName;
break;
case "message":
v = this.mapValue.message.typeName;
break;
}
type = `map<${k}, ${v}>`;
break;
}
}
parts.push(`${type} ${this.name} = ${this.number}`);
const options = [];
if (((_a = this.proto.options) === null || _a === void 0 ? void 0 : _a.packed) !== undefined) {
options.push(`packed = ${this.proto.options.packed.toString()}`);
}
let defaultValue = this.proto.defaultValue;
if (defaultValue !== undefined) {
if (this.proto.type == descriptor_pb_js_1.FieldDescriptorProto_Type.BYTES ||
this.proto.type == descriptor_pb_js_1.FieldDescriptorProto_Type.STRING) {
defaultValue = '"' + defaultValue.replace('"', '\\"') + '"';
}
options.push(`default = ${defaultValue}`);
}
if (this.jsonName !== undefined) {
options.push(`json_name = "${this.jsonName}"`);
}
if (((_b = this.proto.options) === null || _b === void 0 ? void 0 : _b.jstype) !== undefined) {
options.push(`jstype = ${descriptor_pb_js_1.FieldOptions_JSType[this.proto.options.jstype]}`);
}
if (((_c = this.proto.options) === null || _c === void 0 ? void 0 : _c.deprecated) === true) {
options.push(`deprecated = true`);
}
if (options.length > 0) {
parts.push("[" + options.join(", ") + "]");
}
return parts.join(" ");
}
/**
* Parses a text-encoded default value (proto2) of a scalar or enum field.
*/
function getDefaultValue() {
const d = this.proto.defaultValue;
if (d === undefined) {
return undefined;
}
switch (this.fieldKind) {
case "enum":
return (0, text_format_js_1.parseTextFormatEnumValue)(this.enum, d);
case "scalar":
return (0, text_format_js_1.parseTextFormatScalarValue)(this.scalar, d);
default:
return undefined;
}
}
@@ -0,0 +1,15 @@
import type { IEnumTypeRegistry, IExtensionRegistry, IMessageTypeRegistry, IServiceTypeRegistry } from "./type-registry.js";
import { FileDescriptorSet } from "./google/protobuf/descriptor_pb.js";
import type { DescriptorSet } from "./descriptor-set.js";
/**
* Create a registry from a set of descriptors. The types returned by this
* registry behave exactly like types from generated code.
*
* This function accepts google.protobuf.FileDescriptorSet in serialized or
* deserialized form. Alternatively, it also accepts a DescriptorSet (see
* createDescriptorSet()).
*
* By default, all well-known types with a specialized JSON representation
* are replaced with their generated counterpart in this package.
*/
export declare function createRegistryFromDescriptors(input: DescriptorSet | FileDescriptorSet | Uint8Array, replaceWkt?: boolean): IMessageTypeRegistry & IEnumTypeRegistry & IExtensionRegistry & IServiceTypeRegistry;
+264
View File
@@ -0,0 +1,264 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.createRegistryFromDescriptors = void 0;
const assert_js_1 = require("./private/assert.js");
const proto3_js_1 = require("./proto3.js");
const proto2_js_1 = require("./proto2.js");
const names_js_1 = require("./private/names.js");
const timestamp_pb_js_1 = require("./google/protobuf/timestamp_pb.js");
const duration_pb_js_1 = require("./google/protobuf/duration_pb.js");
const any_pb_js_1 = require("./google/protobuf/any_pb.js");
const empty_pb_js_1 = require("./google/protobuf/empty_pb.js");
const field_mask_pb_js_1 = require("./google/protobuf/field_mask_pb.js");
const struct_pb_js_1 = require("./google/protobuf/struct_pb.js");
const enum_js_1 = require("./private/enum.js");
const wrappers_pb_js_1 = require("./google/protobuf/wrappers_pb.js");
const descriptor_pb_js_1 = require("./google/protobuf/descriptor_pb.js");
const create_descriptor_set_js_1 = require("./create-descriptor-set.js");
const is_message_js_1 = require("./is-message.js");
// well-known message types with specialized JSON representation
const wkMessages = [
any_pb_js_1.Any,
duration_pb_js_1.Duration,
empty_pb_js_1.Empty,
field_mask_pb_js_1.FieldMask,
struct_pb_js_1.Struct,
struct_pb_js_1.Value,
struct_pb_js_1.ListValue,
timestamp_pb_js_1.Timestamp,
duration_pb_js_1.Duration,
wrappers_pb_js_1.DoubleValue,
wrappers_pb_js_1.FloatValue,
wrappers_pb_js_1.Int64Value,
wrappers_pb_js_1.Int32Value,
wrappers_pb_js_1.UInt32Value,
wrappers_pb_js_1.UInt64Value,
wrappers_pb_js_1.BoolValue,
wrappers_pb_js_1.StringValue,
wrappers_pb_js_1.BytesValue,
];
// well-known enum types with specialized JSON representation
const wkEnums = [(0, enum_js_1.getEnumType)(struct_pb_js_1.NullValue)];
/**
* Create a registry from a set of descriptors. The types returned by this
* registry behave exactly like types from generated code.
*
* This function accepts google.protobuf.FileDescriptorSet in serialized or
* deserialized form. Alternatively, it also accepts a DescriptorSet (see
* createDescriptorSet()).
*
* By default, all well-known types with a specialized JSON representation
* are replaced with their generated counterpart in this package.
*/
function createRegistryFromDescriptors(input, replaceWkt = true) {
const set = input instanceof Uint8Array || (0, is_message_js_1.isMessage)(input, descriptor_pb_js_1.FileDescriptorSet)
? (0, create_descriptor_set_js_1.createDescriptorSet)(input)
: input;
const enums = new Map();
const messages = new Map();
const extensions = new Map();
const extensionsByExtendee = new Map();
const services = {};
if (replaceWkt) {
for (const mt of wkMessages) {
messages.set(mt.typeName, mt);
}
for (const et of wkEnums) {
enums.set(et.typeName, et);
}
}
return {
/**
* May raise an error on invalid descriptors.
*/
findEnum(typeName) {
const existing = enums.get(typeName);
if (existing) {
return existing;
}
const desc = set.enums.get(typeName);
if (!desc) {
return undefined;
}
const runtime = desc.file.syntax == "proto3" ? proto3_js_1.proto3 : proto2_js_1.proto2;
const type = runtime.makeEnumType(typeName, desc.values.map((u) => ({
no: u.number,
name: u.name,
localName: (0, names_js_1.localName)(u),
})), {});
enums.set(typeName, type);
return type;
},
/**
* May raise an error on invalid descriptors.
*/
findMessage(typeName) {
const existing = messages.get(typeName);
if (existing) {
return existing;
}
const desc = set.messages.get(typeName);
if (!desc) {
return undefined;
}
const runtime = desc.file.syntax == "proto3" ? proto3_js_1.proto3 : proto2_js_1.proto2;
const fields = [];
const type = runtime.makeMessageType(typeName, () => fields, {
localName: (0, names_js_1.localName)(desc),
});
messages.set(typeName, type);
for (const field of desc.fields) {
fields.push(makeFieldInfo(field, this));
}
return type;
},
/**
* May raise an error on invalid descriptors.
*/
findService(typeName) {
const existing = services[typeName];
if (existing) {
return existing;
}
const desc = set.services.get(typeName);
if (!desc) {
return undefined;
}
const methods = {};
for (const method of desc.methods) {
const I = resolve(method.input, this, method);
const O = resolve(method.output, this, method);
methods[(0, names_js_1.localName)(method)] = {
name: method.name,
I,
O,
kind: method.methodKind,
idempotency: method.idempotency,
// We do not surface options at this time
// options: {},
};
}
return (services[typeName] = {
typeName: desc.typeName,
methods,
});
},
/**
* May raise an error on invalid descriptors.
*/
findExtensionFor(typeName, no) {
var _a;
if (!set.messages.has(typeName)) {
return undefined;
}
let extensionsByNo = extensionsByExtendee.get(typeName);
if (!extensionsByNo) {
// maintain a lookup for extension desc by number
extensionsByNo = new Map();
extensionsByExtendee.set(typeName, extensionsByNo);
for (const desc of set.extensions.values()) {
if (desc.extendee.typeName == typeName) {
extensionsByNo.set(desc.number, desc);
}
}
}
const desc = (_a = extensionsByExtendee.get(typeName)) === null || _a === void 0 ? void 0 : _a.get(no);
return desc ? this.findExtension(desc.typeName) : undefined;
},
/**
* May raise an error on invalid descriptors.
*/
findExtension(typeName) {
const existing = extensions.get(typeName);
if (existing) {
return existing;
}
const desc = set.extensions.get(typeName);
if (!desc) {
return undefined;
}
const extendee = resolve(desc.extendee, this, desc);
const runtime = desc.file.syntax == "proto3" ? proto3_js_1.proto3 : proto2_js_1.proto2;
const ext = runtime.makeExtension(typeName, extendee, makeFieldInfo(desc, this));
extensions.set(typeName, ext);
return ext;
},
};
}
exports.createRegistryFromDescriptors = createRegistryFromDescriptors;
function makeFieldInfo(desc, registry) {
var _a;
const f = {
kind: desc.fieldKind,
no: desc.number,
name: desc.name,
jsonName: desc.jsonName,
delimited: desc.proto.type == descriptor_pb_js_1.FieldDescriptorProto_Type.GROUP,
repeated: desc.repeated,
packed: desc.packed,
oneof: (_a = desc.oneof) === null || _a === void 0 ? void 0 : _a.name,
opt: desc.optional,
req: desc.proto.label === descriptor_pb_js_1.FieldDescriptorProto_Label.REQUIRED,
};
switch (desc.fieldKind) {
case "map": {
(0, assert_js_1.assert)(desc.kind == "field"); // maps are not allowed for extensions
let T;
switch (desc.mapValue.kind) {
case "scalar":
T = desc.mapValue.scalar;
break;
case "enum": {
T = resolve(desc.mapValue.enum, registry, desc);
break;
}
case "message": {
T = resolve(desc.mapValue.message, registry, desc);
break;
}
}
f.K = desc.mapKey;
f.V = {
kind: desc.mapValue.kind,
T,
};
break;
}
case "message": {
f.T = resolve(desc.message, registry, desc);
break;
}
case "enum": {
f.T = resolve(desc.enum, registry, desc);
f.default = desc.getDefaultValue();
break;
}
case "scalar": {
f.L = desc.longType;
f.T = desc.scalar;
f.default = desc.getDefaultValue();
break;
}
}
return f;
}
function resolve(desc, registry, context) {
const type = desc.kind == "message"
? registry.findMessage(desc.typeName)
: registry.findEnum(desc.typeName);
(0, assert_js_1.assert)(type, `${desc.toString()}" for ${context.toString()} not found`);
return type;
}
+13
View File
@@ -0,0 +1,13 @@
import type { MessageType } from "./message-type.js";
import type { EnumType } from "./enum.js";
import type { ServiceType } from "./service-type.js";
import type { IEnumTypeRegistry, IExtensionRegistry, IMessageTypeRegistry, IMutableRegistry, IServiceTypeRegistry } from "./type-registry.js";
import type { Extension } from "./extension.js";
/**
* Create a new registry from the given types.
*/
export declare function createRegistry(...types: Array<MessageType | EnumType | ServiceType | Extension>): IMessageTypeRegistry & IEnumTypeRegistry & IExtensionRegistry & IServiceTypeRegistry;
/**
* Create a mutable registry from the given types.
*/
export declare function createMutableRegistry(...types: Array<MessageType | EnumType | ServiceType | Extension>): IMutableRegistry;
+103
View File
@@ -0,0 +1,103 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.createMutableRegistry = exports.createRegistry = void 0;
/**
* Create a new registry from the given types.
*/
function createRegistry(...types) {
const mutable = createMutableRegistry(...types);
delete mutable.add;
return mutable;
}
exports.createRegistry = createRegistry;
/**
* Create a mutable registry from the given types.
*/
function createMutableRegistry(...types) {
const messages = {};
const enums = {};
const services = {};
const extensionsByName = new Map();
const extensionsByExtendee = new Map();
const registry = {
findMessage(typeName) {
return messages[typeName];
},
findEnum(typeName) {
return enums[typeName];
},
findService(typeName) {
return services[typeName];
},
findExtensionFor(typeName, no) {
var _a, _b;
return (_b = (_a = extensionsByExtendee.get(typeName)) === null || _a === void 0 ? void 0 : _a.get(no)) !== null && _b !== void 0 ? _b : undefined;
},
findExtension(typeName) {
var _a;
return (_a = extensionsByName.get(typeName)) !== null && _a !== void 0 ? _a : undefined;
},
add(type) {
var _a;
if ("fields" in type) {
if (!this.findMessage(type.typeName)) {
messages[type.typeName] = type;
type.fields.list().forEach(addField);
}
}
else if ("methods" in type) {
if (!this.findService(type.typeName)) {
services[type.typeName] = type;
for (const method of Object.values(type.methods)) {
this.add(method.I);
this.add(method.O);
}
}
}
else if ("extendee" in type) {
if (!extensionsByName.has(type.typeName)) {
extensionsByName.set(type.typeName, type);
const extendeeName = type.extendee.typeName;
if (!extensionsByExtendee.has(extendeeName)) {
extensionsByExtendee.set(extendeeName, new Map());
}
(_a = extensionsByExtendee.get(extendeeName)) === null || _a === void 0 ? void 0 : _a.set(type.field.no, type);
this.add(type.extendee);
addField(type.field);
}
}
else {
enums[type.typeName] = type;
}
},
};
function addField(field) {
if (field.kind == "message") {
registry.add(field.T);
}
else if (field.kind == "map" && field.V.kind == "message") {
registry.add(field.V.T);
}
else if (field.kind == "enum") {
registry.add(field.T);
}
}
for (const type of types) {
registry.add(type);
}
return registry;
}
exports.createMutableRegistry = createMutableRegistry;
+672
View File
@@ -0,0 +1,672 @@
import type { DescriptorProto, Edition, EnumDescriptorProto, EnumValueDescriptorProto, FieldDescriptorProto, FileDescriptorProto, MethodDescriptorProto, OneofDescriptorProto, ServiceDescriptorProto } from "./google/protobuf/descriptor_pb.js";
import { LongType, ScalarType } from "./scalar.js";
import type { MethodIdempotency, MethodKind } from "./service-type.js";
import type { MergedFeatureSet } from "./private/feature-set.js";
/**
* DescriptorSet provides a convenient interface for working with a set
* of google.protobuf.FileDescriptorProto.
*
* When protobuf sources are compiled, each file is parsed into a
* google.protobuf.FileDescriptorProto. Those messages describe all parts
* of the source file that are required to generate code for them.
*
* DescriptorSet resolves references between the descriptors, hides
* implementation details like synthetic map entry messages, and provides
* simple access to comments.
*/
export interface DescriptorSet {
/**
* All files, in the order they were added to the set.
*/
readonly files: DescFile[];
/**
* All enumerations, indexed by their fully qualified type name.
* (We omit the leading dot.)
*/
readonly enums: ReadonlyMap<string, DescEnum>;
/**
* All messages, indexed by their fully qualified type name.
* (We omit the leading dot.)
*/
readonly messages: ReadonlyMap<string, DescMessage>;
/**
* All services, indexed by their fully qualified type name.
* (We omit the leading dot.)
*/
readonly services: ReadonlyMap<string, DescService>;
/**
* All extensions, indexed by their fully qualified type name.
*/
readonly extensions: ReadonlyMap<string, DescExtension>;
}
/**
* A union of all descriptors, discriminated by a `kind` property.
*/
export type AnyDesc = DescFile | DescEnum | DescEnumValue | DescMessage | DescField | DescExtension | DescOneof | DescService | DescMethod;
/**
* Describes a protobuf source file.
*/
export interface DescFile {
readonly kind: "file";
/**
* The syntax specified in the protobuf source.
*/
readonly syntax: "proto3" | "proto2" | "editions";
/**
* The edition of the protobuf file. Will be EDITION_PROTO2 for syntax="proto2",
* EDITION_PROTO3 for syntax="proto3";
*/
readonly edition: Exclude<Edition, Edition.EDITION_1_TEST_ONLY | Edition.EDITION_2_TEST_ONLY | Edition.EDITION_99997_TEST_ONLY | Edition.EDITION_99998_TEST_ONLY | Edition.EDITION_99999_TEST_ONLY>;
/**
* The name of the file, excluding the .proto suffix.
* For a protobuf file `foo/bar.proto`, this is `foo/bar`.
*/
readonly name: string;
/**
* Files imported by this file.
*/
readonly dependencies: DescFile[];
/**
* Top-level enumerations declared in this file.
* Note that more enumerations might be declared within message declarations.
*/
readonly enums: DescEnum[];
/**
* Top-level messages declared in this file.
* Note that more messages might be declared within message declarations.
*/
readonly messages: DescMessage[];
/**
* Top-level extensions declared in this file.
* Note that more extensions might be declared within message declarations.
*/
readonly extensions: DescExtension[];
/**
* Services declared in this file.
*/
readonly services: DescService[];
/**
* Marked as deprecated in the protobuf source.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: FileDescriptorProto;
/**
* Get comments on the syntax element in the protobuf source.
*/
getSyntaxComments(): DescComments;
/**
* Get comments on the package element in the protobuf source.
*/
getPackageComments(): DescComments;
/**
* Get the edition features for this protobuf element.
*/
getFeatures(): MergedFeatureSet;
toString(): string;
}
/**
* Describes an enumeration in a protobuf source file.
*/
export interface DescEnum {
readonly kind: "enum";
/**
* The fully qualified name of the enumeration. (We omit the leading dot.)
*/
readonly typeName: string;
/**
* The name of the enumeration, as declared in the protobuf source.
*/
readonly name: string;
/**
* The file this enumeration was declared in.
*/
readonly file: DescFile;
/**
* The parent message, if this enumeration was declared inside a message declaration.
*/
readonly parent: DescMessage | undefined;
/**
* Values declared for this enumeration.
*/
readonly values: DescEnumValue[];
/**
* A prefix shared by all enum values.
* For example, `MY_ENUM_` for `enum MyEnum {MY_ENUM_A=0; MY_ENUM_B=1;}`
*/
readonly sharedPrefix?: string;
/**
* Marked as deprecated in the protobuf source.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: EnumDescriptorProto;
/**
* Get comments on the element in the protobuf source.
*/
getComments(): DescComments;
/**
* Get the edition features for this protobuf element.
*/
getFeatures(): MergedFeatureSet;
toString(): string;
}
/**
* Describes an individual value of an enumeration in a protobuf source file.
*/
export interface DescEnumValue {
kind: "enum_value";
/**
* The name of the enumeration value, as specified in the protobuf source.
*/
readonly name: string;
/**
* The enumeration this value belongs to.
*/
readonly parent: DescEnum;
/**
* The numeric enumeration value, as specified in the protobuf source.
*/
readonly number: number;
/**
* Marked as deprecated in the protobuf source.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: EnumValueDescriptorProto;
/**
* Return a string that (closely) matches the definition of the enumeration
* value in the protobuf source.
*/
declarationString(): string;
/**
* Get comments on the element in the protobuf source.
*/
getComments(): DescComments;
/**
* Get the edition features for this protobuf element.
*/
getFeatures(): MergedFeatureSet;
toString(): string;
}
/**
* Describes a message declaration in a protobuf source file.
*/
export interface DescMessage {
readonly kind: "message";
/**
* The fully qualified name of the message. (We omit the leading dot.)
*/
readonly typeName: string;
/**
* The name of the message, as specified in the protobuf source.
*/
readonly name: string;
/**
* The file this message was declared in.
*/
readonly file: DescFile;
/**
* The parent message, if this message was declared inside a message declaration.
*/
readonly parent: DescMessage | undefined;
/**
* Fields declared for this message, including fields declared in a oneof
* group.
*/
readonly fields: DescField[];
/**
* Oneof groups declared for this message.
* This does not include synthetic oneofs for proto3 optionals.
*/
readonly oneofs: DescOneof[];
/**
* Fields and oneof groups for this message, ordered by their appearance in the
* protobuf source.
*/
readonly members: (DescField | DescOneof)[];
/**
* Enumerations declared within the message, if any.
*/
readonly nestedEnums: DescEnum[];
/**
* Messages declared within the message, if any.
* This does not include synthetic messages like map entries.
*/
readonly nestedMessages: DescMessage[];
/**
* Extensions declared within the message, if any.
*/
readonly nestedExtensions: DescExtension[];
/**
* Marked as deprecated in the protobuf source.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: DescriptorProto;
/**
* Get comments on the element in the protobuf source.
*/
getComments(): DescComments;
/**
* Get the edition features for this protobuf element.
*/
getFeatures(): MergedFeatureSet;
toString(): string;
}
/**
* Describes a field declaration in a protobuf source file.
*/
export type DescField = DescFieldCommon & (DescFieldScalar | DescFieldMessage | DescFieldEnum | DescFieldMap) & {
readonly kind: "field";
/**
* The message this field is declared on.
*/
readonly parent: DescMessage;
};
/**
* Describes an extension in a protobuf source file.
*/
export type DescExtension = DescFieldCommon & (DescFieldScalar | DescFieldMessage | DescFieldEnum | DescFieldMap) & {
readonly kind: "extension";
/**
* The fully qualified name of the extension.
*/
readonly typeName: string;
/**
* The file this extension was declared in.
*/
readonly file: DescFile;
/**
* The parent message, if this extension was declared inside a message declaration.
*/
readonly parent: DescMessage | undefined;
/**
* The message that this extension extends.
*/
readonly extendee: DescMessage;
};
interface DescFieldCommon {
/**
* The field name, as specified in the protobuf source
*/
readonly name: string;
/**
* The field number, as specified in the protobuf source.
*/
readonly number: number;
/**
* The `oneof` group this field belongs to, if any.
*/
readonly oneof: DescOneof | undefined;
/**
* Whether this field was declared with `optional` in the protobuf source.
*/
readonly optional: boolean;
/**
* Pack this repeated field?
*/
readonly packed: boolean;
/**
* Is this field packed by default? Only valid for repeated enum fields, and
* for repeated scalar fields except BYTES and STRING.
*
* In proto3 syntax, fields are packed by default. In proto2 syntax, fields
* are unpacked by default.
*
* With editions, the default is whatever the edition specifies as a default.
* In edition 2023, fields are packed by default.
*/
readonly packedByDefault: boolean;
/**
* A user-defined name for the JSON format, set with the field option
* [json_name="foo"].
*/
readonly jsonName: string | undefined;
/**
* Marked as deprecated in the protobuf source.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: FieldDescriptorProto;
/**
* Get comments on the element in the protobuf source.
*/
getComments(): DescComments;
/**
* Return a string that (closely) matches the definition of the field in the
* protobuf source.
*/
declarationString(): string;
/**
* Get the edition features for this protobuf element.
*/
getFeatures(): MergedFeatureSet;
toString(): string;
}
interface DescFieldScalar {
readonly fieldKind: "scalar";
/**
* Is the field repeated?
*/
readonly repeated: boolean;
/**
* Scalar type, if it is a scalar field.
*/
readonly scalar: ScalarType;
/**
* JavaScript type for 64 bit integral types (int64, uint64,
* sint64, fixed64, sfixed64).
*/
readonly longType: LongType;
/**
* The message type, if it is a message field.
*/
readonly message: undefined;
/**
* The enum type, if it is an enum field.
*/
readonly enum: undefined;
/**
* The map key type, if this is a map field.
*/
readonly mapKey: undefined;
/**
* The map value type, if this is a map field.
*/
readonly mapValue: undefined;
/**
* Return the default value specified in the protobuf source.
* Only valid for proto2 syntax.
*/
getDefaultValue(): number | boolean | string | bigint | Uint8Array | undefined;
}
interface DescFieldMessage {
readonly fieldKind: "message";
/**
* Is the field repeated?
*/
readonly repeated: boolean;
/**
* Scalar type, if it is a scalar field.
*/
readonly scalar: undefined;
/**
* JavaScript type for 64 bit integral types (int64, uint64,
* sint64, fixed64, sfixed64).
*/
readonly longType: undefined;
/**
* The message type, if it is a message field.
*/
readonly message: DescMessage;
/**
* The enum type, if it is an enum field.
*/
readonly enum: undefined;
/**
* The map key type, if this is a map field.
*/
readonly mapKey: undefined;
/**
* The map value type, if this is a map field.
*/
readonly mapValue: undefined;
}
interface DescFieldEnum {
readonly fieldKind: "enum";
/**
* Is the field repeated?
*/
readonly repeated: boolean;
/**
* Scalar type, if it is a scalar field.
*/
readonly scalar: undefined;
/**
* JavaScript type for 64 bit integral types (int64, uint64,
* sint64, fixed64, sfixed64).
*/
readonly longType: undefined;
/**
* The message type, if it is a message field.
*/
readonly message: undefined;
/**
* The enum type, if it is an enum field.
*/
readonly enum: DescEnum;
/**
* The map key type, if this is a map field.
*/
readonly mapKey: undefined;
/**
* The map value type, if this is a map field.
*/
readonly mapValue: undefined;
/**
* Return the default value specified in the protobuf source.
* Only valid for proto2 syntax.
*/
getDefaultValue(): number | boolean | string | bigint | Uint8Array | undefined;
}
interface DescFieldMap {
readonly fieldKind: "map";
/**
* Is the field repeated?
*/
readonly repeated: false;
/**
* Scalar type, if it is a scalar field.
*/
readonly scalar: undefined;
/**
* JavaScript type for 64 bit integral types (int64, uint64,
* sint64, fixed64, sfixed64).
*/
readonly longType: undefined;
/**
* The message type, if it is a message field.
*/
readonly message: undefined;
/**
* The enum type, if it is an enum field.
*/
readonly enum: undefined;
/**
* The map key type, if this is a map field.
*/
readonly mapKey: Exclude<ScalarType, ScalarType.FLOAT | ScalarType.DOUBLE | ScalarType.BYTES>;
/**
* The map value type, if this is a map field.
*/
readonly mapValue: DescFieldMapValueEnum | DescFieldMapValueMessage | DescFieldMapValueScalar;
}
interface DescFieldMapValueEnum {
readonly kind: "enum";
/**
* The enum type, if this is a map field with enum values.
*/
readonly enum: DescEnum;
/**
* The message this message field uses.
*/
readonly message: undefined;
/**
* Scalar type, if this is a map field with scalar values.
*/
readonly scalar: undefined;
}
interface DescFieldMapValueMessage {
readonly kind: "message";
/**
* The enum type, if this is a map field with enum values.
*/
readonly enum: undefined;
/**
* The message type, if this is a map field with message values.
*/
readonly message: DescMessage;
/**
* Scalar type, if this is a map field with scalar values.
*/
readonly scalar: undefined;
}
interface DescFieldMapValueScalar {
readonly kind: "scalar";
/**
* The enum type, if this is a map field with enum values.
*/
readonly enum: undefined;
/**
* The message type, if this is a map field with message values.
*/
readonly message: undefined;
/**
* Scalar type, if this is a map field with scalar values.
*/
readonly scalar: ScalarType;
}
/**
* Describes a oneof group in a protobuf source file.
*/
export interface DescOneof {
readonly kind: "oneof";
/**
* The name of the oneof group, as specified in the protobuf source.
*/
readonly name: string;
/**
* The message this oneof group was declared in.
*/
readonly parent: DescMessage;
/**
* The fields declared in this oneof group.
*/
readonly fields: DescField[];
/**
* Marked as deprecated in the protobuf source.
* Note that oneof groups cannot be marked as deprecated, this property
* only exists for consistency and will always be false.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: OneofDescriptorProto;
/**
* Get comments on the element in the protobuf source.
*/
getComments(): DescComments;
/**
* Get the edition features for this protobuf element.
*/
getFeatures(): MergedFeatureSet;
toString(): string;
}
/**
* Describes a service declaration in a protobuf source file.
*/
export interface DescService {
readonly kind: "service";
/**
* The fully qualified name of the service. (We omit the leading dot.)
*/
readonly typeName: string;
/**
* The name of the service, as specified in the protobuf source.
*/
readonly name: string;
/**
* The file this service was declared in.
*/
readonly file: DescFile;
/**
* The RPCs this service declares.
*/
readonly methods: DescMethod[];
/**
* Marked as deprecated in the protobuf source.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: ServiceDescriptorProto;
/**
* Get comments on the element in the protobuf source.
*/
getComments(): DescComments;
/**
* Get the edition features for this protobuf element.
*/
getFeatures(): MergedFeatureSet;
toString(): string;
}
/**
* Describes an RPC declaration in a protobuf source file.
*/
export interface DescMethod {
readonly kind: "rpc";
/**
* The name of the RPC, as specified in the protobuf source.
*/
readonly name: string;
/**
* The parent service.
*/
readonly parent: DescService;
/**
* One of the four available method types.
*/
readonly methodKind: MethodKind;
/**
* The message type for requests.
*/
readonly input: DescMessage;
/**
* The message type for responses.
*/
readonly output: DescMessage;
/**
* The idempotency level declared in the protobuf source, if any.
*/
readonly idempotency?: MethodIdempotency;
/**
* Marked as deprecated in the protobuf source.
*/
readonly deprecated: boolean;
/**
* The compiler-generated descriptor.
*/
readonly proto: MethodDescriptorProto;
/**
* Get comments on the element in the protobuf source.
*/
getComments(): DescComments;
/**
* Get the edition features for this protobuf element.
*/
getFeatures(): MergedFeatureSet;
toString(): string;
}
/**
* Comments on an element in a protobuf source file.
*/
export interface DescComments {
readonly leadingDetached: readonly string[];
readonly leading?: string;
readonly trailing?: string;
readonly sourcePath: readonly number[];
}
export {};
+15
View File
@@ -0,0 +1,15 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
+35
View File
@@ -0,0 +1,35 @@
/**
* Reflection information for a protobuf enumeration.
*/
export interface EnumType {
/**
* The fully qualified name of the enumeration.
*/
readonly typeName: string;
readonly values: readonly EnumValueInfo[];
/**
* Find an enum value by its (protobuf) name.
*/
findName(name: string): EnumValueInfo | undefined;
/**
* Find an enum value by its number.
*/
findNumber(no: number): EnumValueInfo | undefined;
}
/**
* Reflection information for a protobuf enumeration value.
*/
export interface EnumValueInfo {
/**
* The numeric enumeration value, as specified in the protobuf source.
*/
readonly no: number;
/**
* The name of the enumeration value, as specified in the protobuf source.
*/
readonly name: string;
/**
* The name of the enumeration value in generated code.
*/
readonly localName: string;
}
+15
View File
@@ -0,0 +1,15 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
+35
View File
@@ -0,0 +1,35 @@
import type { Message } from "./message.js";
import type { BinaryReadOptions, BinaryWriteOptions } from "./binary-format.js";
import type { Extension } from "./extension.js";
/**
* Retrieve an extension value from a message.
*
* The function never returns undefined. Use hasExtension() to check whether an
* extension is set. If the extension is not set, this function returns the
* default value (if one was specified in the protobuf source), or the zero value
* (for example `0` for numeric types, `[]` for repeated extension fields, and
* an empty message instance for message fields).
*
* Extensions are stored as unknown fields on a message. To mutate an extension
* value, make sure to store the new value with setExtension() after mutating.
*
* If the extension does not extend the given message, an error is raised.
*/
export declare function getExtension<E extends Message<E>, V>(message: E, extension: Extension<E, V>, options?: Partial<BinaryReadOptions>): V;
/**
* Set an extension value on a message. If the message already has a value for
* this extension, the value is replaced.
*
* If the extension does not extend the given message, an error is raised.
*/
export declare function setExtension<E extends Message<E>, V>(message: E, extension: Extension<E, V>, value: V, options?: Partial<BinaryReadOptions & BinaryWriteOptions>): void;
/**
* Remove an extension value from a message.
*
* If the extension does not extend the given message, an error is raised.
*/
export declare function clearExtension<E extends Message<E>, V>(message: E, extension: Extension<E, V>): void;
/**
* Check whether an extension is set on a message.
*/
export declare function hasExtension<E extends Message<E>, V>(message: E, extension: Extension<E, V>): boolean;
+114
View File
@@ -0,0 +1,114 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.hasExtension = exports.clearExtension = exports.setExtension = exports.getExtension = void 0;
const assert_js_1 = require("./private/assert.js");
const extensions_js_1 = require("./private/extensions.js");
/**
* Retrieve an extension value from a message.
*
* The function never returns undefined. Use hasExtension() to check whether an
* extension is set. If the extension is not set, this function returns the
* default value (if one was specified in the protobuf source), or the zero value
* (for example `0` for numeric types, `[]` for repeated extension fields, and
* an empty message instance for message fields).
*
* Extensions are stored as unknown fields on a message. To mutate an extension
* value, make sure to store the new value with setExtension() after mutating.
*
* If the extension does not extend the given message, an error is raised.
*/
function getExtension(message, extension, options) {
assertExtendee(extension, message);
const opt = extension.runtime.bin.makeReadOptions(options);
const ufs = (0, extensions_js_1.filterUnknownFields)(message.getType().runtime.bin.listUnknownFields(message), extension.field);
const [container, get] = (0, extensions_js_1.createExtensionContainer)(extension);
for (const uf of ufs) {
extension.runtime.bin.readField(container, opt.readerFactory(uf.data), extension.field, uf.wireType, opt);
}
return get();
}
exports.getExtension = getExtension;
/**
* Set an extension value on a message. If the message already has a value for
* this extension, the value is replaced.
*
* If the extension does not extend the given message, an error is raised.
*/
function setExtension(message, extension, value, options) {
assertExtendee(extension, message);
const readOpt = extension.runtime.bin.makeReadOptions(options);
const writeOpt = extension.runtime.bin.makeWriteOptions(options);
if (hasExtension(message, extension)) {
const ufs = message
.getType()
.runtime.bin.listUnknownFields(message)
.filter((uf) => uf.no != extension.field.no);
message.getType().runtime.bin.discardUnknownFields(message);
for (const uf of ufs) {
message
.getType()
.runtime.bin.onUnknownField(message, uf.no, uf.wireType, uf.data);
}
}
const writer = writeOpt.writerFactory();
let f = extension.field;
// Implicit presence does not apply to extensions, see https://github.com/protocolbuffers/protobuf/issues/8234
// We patch the field info to use explicit presence:
if (!f.opt && !f.repeated && (f.kind == "enum" || f.kind == "scalar")) {
f = Object.assign(Object.assign({}, extension.field), { opt: true });
}
extension.runtime.bin.writeField(f, value, writer, writeOpt);
const reader = readOpt.readerFactory(writer.finish());
while (reader.pos < reader.len) {
const [no, wireType] = reader.tag();
const data = reader.skip(wireType, no);
message.getType().runtime.bin.onUnknownField(message, no, wireType, data);
}
}
exports.setExtension = setExtension;
/**
* Remove an extension value from a message.
*
* If the extension does not extend the given message, an error is raised.
*/
function clearExtension(message, extension) {
assertExtendee(extension, message);
if (hasExtension(message, extension)) {
const bin = message.getType().runtime.bin;
const ufs = bin
.listUnknownFields(message)
.filter((uf) => uf.no != extension.field.no);
bin.discardUnknownFields(message);
for (const uf of ufs) {
bin.onUnknownField(message, uf.no, uf.wireType, uf.data);
}
}
}
exports.clearExtension = clearExtension;
/**
* Check whether an extension is set on a message.
*/
function hasExtension(message, extension) {
const messageType = message.getType();
return (extension.extendee.typeName === messageType.typeName &&
!!messageType.runtime.bin
.listUnknownFields(message)
.find((uf) => uf.no == extension.field.no));
}
exports.hasExtension = hasExtension;
function assertExtendee(extension, message) {
(0, assert_js_1.assert)(extension.extendee.typeName == message.getType().typeName, `extension ${extension.typeName} can only be applied to message ${extension.extendee.typeName}`);
}
+24
View File
@@ -0,0 +1,24 @@
import type { FieldInfo } from "./field.js";
import type { AnyMessage, Message } from "./message.js";
import type { MessageType } from "./message-type.js";
import type { ProtoRuntime } from "./private/proto-runtime.js";
export interface Extension<E extends Message<E> = AnyMessage, V = unknown> {
/**
* The fully qualified name of the extension.
*/
readonly typeName: string;
/**
* The message extended by this extension.
*/
readonly extendee: MessageType<E>;
/**
* Field information for this extension. Note that required fields, maps,
* oneof are not allowed in extensions. Behavior of "localName" property is
* undefined and must not be relied upon.
*/
readonly field: FieldInfo;
/**
* Provides serialization and other functionality.
*/
readonly runtime: ProtoRuntime;
}
+15
View File
@@ -0,0 +1,15 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
+27
View File
@@ -0,0 +1,27 @@
import type { FieldInfo, OneofInfo } from "./field.js";
/**
* Provides convenient access to field information of a message type.
*/
export interface FieldList {
/**
* Find field information by field name or json_name.
*/
findJsonName(jsonName: string): FieldInfo | undefined;
/**
* Find field information by proto field number.
*/
find(fieldNo: number): FieldInfo | undefined;
/**
* Return field information in the order they appear in the source.
*/
list(): readonly FieldInfo[];
/**
* Return field information ordered by field number ascending.
*/
byNumber(): readonly FieldInfo[];
/**
* In order of appearance in the source, list fields and
* oneof groups.
*/
byMember(): readonly (FieldInfo | OneofInfo)[];
}
+15
View File
@@ -0,0 +1,15 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
+314
View File
@@ -0,0 +1,314 @@
import type { EnumType } from "./enum.js";
import type { MessageType } from "./message-type.js";
import type { LongType, ScalarType } from "./scalar.js";
/**
* FieldInfo describes a field of a protobuf message for runtime reflection. We
* distinguish between the following kinds of fields:
*
* - "scalar": string, bool, float, int32, etc. The scalar type is "T".
* - "enum": The field was declared with an enum type. The enum type is "T".
* - "message": The field was declared with a message type. The message type is "T".
* - "map": The field was declared with map<K,V>. The key type is "K", the value type is "V".
*
* Every field always has the following properties:
*
* - "no": The field number of the protobuf field.
* - "name": The original name of the protobuf field.
* - "localName": The name of the field as used in generated code.
* - "jsonName": The name for JSON serialization / deserialization.
* - "opt": Whether the field is optional.
* - "req": Whether the field is required (a legacy proto2 feature).
* - "repeated": Whether the field is repeated.
* - "packed": Whether the repeated field is packed.
*
* Additionally, fields may have the following properties:
*
* - "oneof": If the field is member of a oneof group.
* - "default": Only proto2: An explicit default value.
* - "delimited": Only proto2: Use the tag-delimited group encoding.
*/
export type FieldInfo = fiRules<fiScalar> | fiRules<fiEnum> | fiRules<fiMessage> | fiRules<fiMap>;
/**
* Version of `FieldInfo` that allows the following properties
* to be omitted:
*
* - "localName", "jsonName": can be omitted if equal to lowerCamelCase(name)
* - "opt": Can be omitted if false.
* - "repeated": Can be omitted if false.
* - "packed": Can be omitted if equal to the standard packing of the field.
*/
export type PartialFieldInfo = fiPartialRules<fiScalar> | fiPartialRules<fiEnum> | fiPartialRules<fiMessage> | fiPartialRules<fiMap>;
/**
* Provides convenient access to field information of a oneof.
*/
export interface OneofInfo {
readonly kind: "oneof";
readonly name: string;
readonly localName: string;
readonly repeated: false;
readonly packed: false;
readonly opt: false;
readonly req: false;
readonly default: undefined;
readonly delimited?: undefined;
readonly fields: readonly FieldInfo[];
/**
* Return field information by local name.
*/
findField(localName: string): FieldInfo | undefined;
}
interface fiShared {
/**
* The field number of the .proto field.
*/
readonly no: number;
/**
* The original name of the .proto field.
*/
readonly name: string;
/**
* The name of the field as used in generated code.
*/
readonly localName: string;
/**
* The name for JSON serialization / deserialization.
*/
readonly jsonName: string;
/**
* The `oneof` group, if this field belongs to one.
*/
readonly oneof?: OneofInfo | undefined;
}
interface fiScalar extends fiShared {
readonly kind: "scalar";
/**
* Scalar type of the field.
*/
readonly T: ScalarType;
/**
* JavaScript representation of 64 bit integral types (int64, uint64,
* sint64, fixed64, sfixed64).
*
* By default, this is LongType.BIGINT. Generated code will use the BigInt
* primitive.
*
* With LongType.STRING, generated code will use the String primitive instead.
* This can be specified per field with the option `[jstype = JS_STRING]`:
*
* ```protobuf
* uint64 field_a = 1; // BigInt
* uint64 field_b = 2 [jstype = JS_NORMAL]; // BigInt
* uint64 field_b = 2 [jstype = JS_NUMBER]; // BigInt
* uint64 field_b = 2 [jstype = JS_STRING]; // String
* ```
*
* This property is ignored for other scalar types.
*/
readonly L: LongType;
/**
* Is the field repeated?
*/
readonly repeated: boolean;
/**
* Is this repeated field packed?
* BYTES and STRING can never be packed, since they are length-delimited.
* Other types can be packed with the field option "packed".
* For proto3, fields are packed by default.
*/
readonly packed: boolean;
/**
* Is the field optional?
*/
readonly opt: boolean;
/**
* Is the field required? A legacy proto2 feature.
*/
readonly req: boolean;
/**
* Only proto2: An explicit default value.
*/
readonly default: number | boolean | string | bigint | Uint8Array | undefined;
/**
* Serialize this message with the delimited format, also known as group
* encoding, as opposed to the standard length prefix.
*
* Only valid for message fields.
*/
readonly delimited?: undefined;
}
interface fiMessage extends fiShared {
readonly kind: "message";
/**
* Message handler for the field.
*/
readonly T: MessageType;
/**
* Is the field repeated?
*/
readonly repeated: boolean;
/**
* Is this repeated field packed? Never true for messages.
*/
readonly packed: false;
/**
* Is the field required? A legacy proto2 feature.
*/
readonly req: boolean;
/**
* An explicit default value (only proto2). Never set for messages.
*/
readonly default: undefined;
/**
* Serialize this message with the delimited format, also known as group
* encoding, as opposed to the standard length prefix.
*
* Only valid for message fields.
*/
readonly delimited?: boolean;
}
interface fiEnum extends fiShared {
readonly kind: "enum";
/**
* Enum type information for the field.
*/
readonly T: EnumType;
/**
* Is the field repeated?
*/
readonly repeated: boolean;
/**
* Is this repeated field packed?
* Repeated enums can be packed with the field option "packed".
* For proto3, they are packed by default.
*/
readonly packed: boolean;
/**
* Is the field optional?
*/
readonly opt: boolean;
/**
* Is the field required? A legacy proto2 feature.
*/
readonly req: boolean;
/**
* Only proto2: An explicit default value.
*/
readonly default: number | undefined;
/**
* Serialize this message with the delimited format, also known as group
* encoding, as opposed to the standard length prefix.
*
* Only valid for message fields.
*/
readonly delimited?: undefined;
}
interface fiMap extends fiShared {
readonly kind: "map";
/**
* Map key type.
*
* The key_type can be any integral or string type
* (so, any scalar type except for floating point
* types and bytes)
*/
readonly K: Exclude<ScalarType, ScalarType.FLOAT | ScalarType.DOUBLE | ScalarType.BYTES>;
/**
* Map value type. Can be scalar, enum, or message.
*/
readonly V: {
readonly kind: "scalar";
readonly T: ScalarType;
} | {
readonly kind: "enum";
readonly T: EnumType;
} | {
readonly kind: "message";
readonly T: MessageType;
};
/**
* Is the field repeated? Never true for maps.
*/
readonly repeated: false;
/**
* Is this repeated field packed? Never true for maps.
*/
readonly packed: false;
/**
* An explicit default value (only proto2). Never set for maps.
*/
readonly default: undefined;
/**
* Serialize this message with the delimited format, also known as group
* encoding, as opposed to the standard length prefix.
*
* Only valid for message fields.
*/
readonly delimited?: undefined;
}
type fiRules<T> = Omit<T, "oneof" | "repeat" | "repeated" | "packed" | "opt" | "req"> & ({
readonly repeated: false;
readonly packed: false;
readonly opt: false;
readonly req: boolean;
readonly oneof: undefined;
} | {
readonly repeated: false;
readonly packed: false;
readonly opt: true;
readonly req: false;
readonly oneof: undefined;
} | {
readonly repeated: boolean;
readonly packed: boolean;
readonly opt: false;
readonly req: boolean;
readonly oneof: undefined;
} | {
readonly repeated: false;
readonly packed: false;
readonly opt: false;
readonly req: false;
readonly oneof: OneofInfo;
});
type fiPartialRules<T extends fiScalar | fiMap | fiEnum | fiMessage> = Omit<T, "jsonName" | "localName" | "oneof" | "repeat" | "repeated" | "packed" | "opt" | "req" | "default" | "L" | "delimited"> & ({
readonly jsonName?: string;
readonly repeated?: false;
readonly packed?: false;
readonly opt?: false;
readonly req?: boolean;
readonly oneof?: undefined;
default?: T["default"];
L?: LongType;
delimited?: boolean;
} | {
readonly jsonName?: string;
readonly repeated?: false;
readonly packed?: false;
readonly opt: true;
readonly req?: false;
readonly oneof?: undefined;
default?: T["default"];
L?: LongType;
delimited?: boolean;
} | {
readonly jsonName?: string;
readonly repeated?: boolean;
readonly packed?: boolean;
readonly opt?: false;
readonly req?: boolean;
readonly oneof?: undefined;
default?: T["default"];
L?: LongType;
delimited?: boolean;
} | {
readonly jsonName?: string;
readonly repeated?: false;
readonly packed?: false;
readonly opt?: false;
readonly req?: false;
readonly oneof: string;
default?: T["default"];
L?: LongType;
delimited?: boolean;
});
export {};
+15
View File
@@ -0,0 +1,15 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
+157
View File
@@ -0,0 +1,157 @@
import type { PartialMessage, PlainMessage } from "../../message.js";
import { Message } from "../../message.js";
import { proto3 } from "../../proto3.js";
import type { JsonReadOptions, JsonValue, JsonWriteOptions } from "../../json-format.js";
import type { IMessageTypeRegistry } from "../../type-registry.js";
import type { MessageType } from "../../message-type.js";
import type { FieldList } from "../../field-list.js";
import type { BinaryReadOptions } from "../../binary-format.js";
/**
* `Any` contains an arbitrary serialized protocol buffer message along with a
* URL that describes the type of the serialized message.
*
* Protobuf library provides support to pack/unpack Any values in the form
* of utility functions or additional generated methods of the Any type.
*
* Example 1: Pack and unpack a message in C++.
*
* Foo foo = ...;
* Any any;
* any.PackFrom(foo);
* ...
* if (any.UnpackTo(&foo)) {
* ...
* }
*
* Example 2: Pack and unpack a message in Java.
*
* Foo foo = ...;
* Any any = Any.pack(foo);
* ...
* if (any.is(Foo.class)) {
* foo = any.unpack(Foo.class);
* }
* // or ...
* if (any.isSameTypeAs(Foo.getDefaultInstance())) {
* foo = any.unpack(Foo.getDefaultInstance());
* }
*
* Example 3: Pack and unpack a message in Python.
*
* foo = Foo(...)
* any = Any()
* any.Pack(foo)
* ...
* if any.Is(Foo.DESCRIPTOR):
* any.Unpack(foo)
* ...
*
* Example 4: Pack and unpack a message in Go
*
* foo := &pb.Foo{...}
* any, err := anypb.New(foo)
* if err != nil {
* ...
* }
* ...
* foo := &pb.Foo{}
* if err := any.UnmarshalTo(foo); err != nil {
* ...
* }
*
* The pack methods provided by protobuf library will by default use
* 'type.googleapis.com/full.type.name' as the type URL and the unpack
* methods only use the fully qualified type name after the last '/'
* in the type URL, for example "foo.bar.com/x/y.z" will yield type
* name "y.z".
*
* JSON
* ====
* The JSON representation of an `Any` value uses the regular
* representation of the deserialized, embedded message, with an
* additional field `@type` which contains the type URL. Example:
*
* package google.profile;
* message Person {
* string first_name = 1;
* string last_name = 2;
* }
*
* {
* "@type": "type.googleapis.com/google.profile.Person",
* "firstName": <string>,
* "lastName": <string>
* }
*
* If the embedded message type is well-known and has a custom JSON
* representation, that representation will be embedded adding a field
* `value` which holds the custom JSON in addition to the `@type`
* field. Example (for message [google.protobuf.Duration][]):
*
* {
* "@type": "type.googleapis.com/google.protobuf.Duration",
* "value": "1.212s"
* }
*
*
* @generated from message google.protobuf.Any
*/
export declare class Any extends Message<Any> {
/**
* A URL/resource name that uniquely identifies the type of the serialized
* protocol buffer message. This string must contain at least
* one "/" character. The last segment of the URL's path must represent
* the fully qualified name of the type (as in
* `path/google.protobuf.Duration`). The name should be in a canonical form
* (e.g., leading "." is not accepted).
*
* In practice, teams usually precompile into the binary all types that they
* expect it to use in the context of Any. However, for URLs which use the
* scheme `http`, `https`, or no scheme, one can optionally set up a type
* server that maps type URLs to message definitions as follows:
*
* * If no scheme is provided, `https` is assumed.
* * An HTTP GET on the URL must yield a [google.protobuf.Type][]
* value in binary format, or produce an error.
* * Applications are allowed to cache lookup results based on the
* URL, or have them precompiled into a binary to avoid any
* lookup. Therefore, binary compatibility needs to be preserved
* on changes to types. (Use versioned type names to manage
* breaking changes.)
*
* Note: this functionality is not currently available in the official
* protobuf release, and it is not used for type URLs beginning with
* type.googleapis.com. As of May 2023, there are no widely used type server
* implementations and no plans to implement one.
*
* Schemes other than `http`, `https` (or the empty scheme) might be
* used with implementation specific semantics.
*
*
* @generated from field: string type_url = 1;
*/
typeUrl: string;
/**
* Must be a valid serialized protocol buffer of the above specified type.
*
* @generated from field: bytes value = 2;
*/
value: Uint8Array;
constructor(data?: PartialMessage<Any>);
toJson(options?: Partial<JsonWriteOptions>): JsonValue;
fromJson(json: JsonValue, options?: Partial<JsonReadOptions>): this;
packFrom(message: Message): void;
unpackTo(target: Message): boolean;
unpack(registry: IMessageTypeRegistry): Message | undefined;
is(type: MessageType | string): boolean;
private typeNameToUrl;
private typeUrlToName;
static readonly runtime: typeof proto3;
static readonly typeName = "google.protobuf.Any";
static readonly fields: FieldList;
static pack(message: Message): Any;
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): Any;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): Any;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): Any;
static equals(a: Any | PlainMessage<Any> | undefined, b: Any | PlainMessage<Any> | undefined): boolean;
}
+273
View File
@@ -0,0 +1,273 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.Any = void 0;
const message_js_1 = require("../../message.js");
const proto3_js_1 = require("../../proto3.js");
/**
* `Any` contains an arbitrary serialized protocol buffer message along with a
* URL that describes the type of the serialized message.
*
* Protobuf library provides support to pack/unpack Any values in the form
* of utility functions or additional generated methods of the Any type.
*
* Example 1: Pack and unpack a message in C++.
*
* Foo foo = ...;
* Any any;
* any.PackFrom(foo);
* ...
* if (any.UnpackTo(&foo)) {
* ...
* }
*
* Example 2: Pack and unpack a message in Java.
*
* Foo foo = ...;
* Any any = Any.pack(foo);
* ...
* if (any.is(Foo.class)) {
* foo = any.unpack(Foo.class);
* }
* // or ...
* if (any.isSameTypeAs(Foo.getDefaultInstance())) {
* foo = any.unpack(Foo.getDefaultInstance());
* }
*
* Example 3: Pack and unpack a message in Python.
*
* foo = Foo(...)
* any = Any()
* any.Pack(foo)
* ...
* if any.Is(Foo.DESCRIPTOR):
* any.Unpack(foo)
* ...
*
* Example 4: Pack and unpack a message in Go
*
* foo := &pb.Foo{...}
* any, err := anypb.New(foo)
* if err != nil {
* ...
* }
* ...
* foo := &pb.Foo{}
* if err := any.UnmarshalTo(foo); err != nil {
* ...
* }
*
* The pack methods provided by protobuf library will by default use
* 'type.googleapis.com/full.type.name' as the type URL and the unpack
* methods only use the fully qualified type name after the last '/'
* in the type URL, for example "foo.bar.com/x/y.z" will yield type
* name "y.z".
*
* JSON
* ====
* The JSON representation of an `Any` value uses the regular
* representation of the deserialized, embedded message, with an
* additional field `@type` which contains the type URL. Example:
*
* package google.profile;
* message Person {
* string first_name = 1;
* string last_name = 2;
* }
*
* {
* "@type": "type.googleapis.com/google.profile.Person",
* "firstName": <string>,
* "lastName": <string>
* }
*
* If the embedded message type is well-known and has a custom JSON
* representation, that representation will be embedded adding a field
* `value` which holds the custom JSON in addition to the `@type`
* field. Example (for message [google.protobuf.Duration][]):
*
* {
* "@type": "type.googleapis.com/google.protobuf.Duration",
* "value": "1.212s"
* }
*
*
* @generated from message google.protobuf.Any
*/
class Any extends message_js_1.Message {
constructor(data) {
super();
/**
* A URL/resource name that uniquely identifies the type of the serialized
* protocol buffer message. This string must contain at least
* one "/" character. The last segment of the URL's path must represent
* the fully qualified name of the type (as in
* `path/google.protobuf.Duration`). The name should be in a canonical form
* (e.g., leading "." is not accepted).
*
* In practice, teams usually precompile into the binary all types that they
* expect it to use in the context of Any. However, for URLs which use the
* scheme `http`, `https`, or no scheme, one can optionally set up a type
* server that maps type URLs to message definitions as follows:
*
* * If no scheme is provided, `https` is assumed.
* * An HTTP GET on the URL must yield a [google.protobuf.Type][]
* value in binary format, or produce an error.
* * Applications are allowed to cache lookup results based on the
* URL, or have them precompiled into a binary to avoid any
* lookup. Therefore, binary compatibility needs to be preserved
* on changes to types. (Use versioned type names to manage
* breaking changes.)
*
* Note: this functionality is not currently available in the official
* protobuf release, and it is not used for type URLs beginning with
* type.googleapis.com. As of May 2023, there are no widely used type server
* implementations and no plans to implement one.
*
* Schemes other than `http`, `https` (or the empty scheme) might be
* used with implementation specific semantics.
*
*
* @generated from field: string type_url = 1;
*/
this.typeUrl = "";
/**
* Must be a valid serialized protocol buffer of the above specified type.
*
* @generated from field: bytes value = 2;
*/
this.value = new Uint8Array(0);
proto3_js_1.proto3.util.initPartial(data, this);
}
toJson(options) {
var _a;
if (this.typeUrl === "") {
return {};
}
const typeName = this.typeUrlToName(this.typeUrl);
const messageType = (_a = options === null || options === void 0 ? void 0 : options.typeRegistry) === null || _a === void 0 ? void 0 : _a.findMessage(typeName);
if (!messageType) {
throw new Error(`cannot encode message google.protobuf.Any to JSON: "${this.typeUrl}" is not in the type registry`);
}
const message = messageType.fromBinary(this.value);
let json = message.toJson(options);
if (typeName.startsWith("google.protobuf.") || (json === null || Array.isArray(json) || typeof json !== "object")) {
json = { value: json };
}
json["@type"] = this.typeUrl;
return json;
}
fromJson(json, options) {
var _a;
if (json === null || Array.isArray(json) || typeof json != "object") {
throw new Error(`cannot decode message google.protobuf.Any from JSON: expected object but got ${json === null ? "null" : Array.isArray(json) ? "array" : typeof json}`);
}
if (Object.keys(json).length == 0) {
return this;
}
const typeUrl = json["@type"];
if (typeof typeUrl != "string" || typeUrl == "") {
throw new Error(`cannot decode message google.protobuf.Any from JSON: "@type" is empty`);
}
const typeName = this.typeUrlToName(typeUrl), messageType = (_a = options === null || options === void 0 ? void 0 : options.typeRegistry) === null || _a === void 0 ? void 0 : _a.findMessage(typeName);
if (!messageType) {
throw new Error(`cannot decode message google.protobuf.Any from JSON: ${typeUrl} is not in the type registry`);
}
let message;
if (typeName.startsWith("google.protobuf.") && Object.prototype.hasOwnProperty.call(json, "value")) {
message = messageType.fromJson(json["value"], options);
}
else {
const copy = Object.assign({}, json);
delete copy["@type"];
message = messageType.fromJson(copy, options);
}
this.packFrom(message);
return this;
}
packFrom(message) {
this.value = message.toBinary();
this.typeUrl = this.typeNameToUrl(message.getType().typeName);
}
unpackTo(target) {
if (!this.is(target.getType())) {
return false;
}
target.fromBinary(this.value);
return true;
}
unpack(registry) {
if (this.typeUrl === "") {
return undefined;
}
const messageType = registry.findMessage(this.typeUrlToName(this.typeUrl));
if (!messageType) {
return undefined;
}
return messageType.fromBinary(this.value);
}
is(type) {
if (this.typeUrl === '') {
return false;
}
const name = this.typeUrlToName(this.typeUrl);
let typeName = '';
if (typeof type === 'string') {
typeName = type;
}
else {
typeName = type.typeName;
}
return name === typeName;
}
typeNameToUrl(name) {
return `type.googleapis.com/${name}`;
}
typeUrlToName(url) {
if (!url.length) {
throw new Error(`invalid type url: ${url}`);
}
const slash = url.lastIndexOf("/");
const name = slash >= 0 ? url.substring(slash + 1) : url;
if (!name.length) {
throw new Error(`invalid type url: ${url}`);
}
return name;
}
static pack(message) {
const any = new Any();
any.packFrom(message);
return any;
}
static fromBinary(bytes, options) {
return new Any().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new Any().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new Any().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto3_js_1.proto3.util.equals(Any, a, b);
}
}
exports.Any = Any;
Any.runtime = proto3_js_1.proto3;
Any.typeName = "google.protobuf.Any";
Any.fields = proto3_js_1.proto3.util.newFieldList(() => [
{ no: 1, name: "type_url", kind: "scalar", T: 9 /* ScalarType.STRING */ },
{ no: 2, name: "value", kind: "scalar", T: 12 /* ScalarType.BYTES */ },
]);
+256
View File
@@ -0,0 +1,256 @@
import type { PartialMessage, PlainMessage } from "../../message.js";
import { Message } from "../../message.js";
import { Option, Syntax } from "./type_pb.js";
import { SourceContext } from "./source_context_pb.js";
import { proto3 } from "../../proto3.js";
import type { FieldList } from "../../field-list.js";
import type { BinaryReadOptions } from "../../binary-format.js";
import type { JsonReadOptions, JsonValue } from "../../json-format.js";
/**
* Api is a light-weight descriptor for an API Interface.
*
* Interfaces are also described as "protocol buffer services" in some contexts,
* such as by the "service" keyword in a .proto file, but they are different
* from API Services, which represent a concrete implementation of an interface
* as opposed to simply a description of methods and bindings. They are also
* sometimes simply referred to as "APIs" in other contexts, such as the name of
* this message itself. See https://cloud.google.com/apis/design/glossary for
* detailed terminology.
*
* @generated from message google.protobuf.Api
*/
export declare class Api extends Message<Api> {
/**
* The fully qualified name of this interface, including package name
* followed by the interface's simple name.
*
* @generated from field: string name = 1;
*/
name: string;
/**
* The methods of this interface, in unspecified order.
*
* @generated from field: repeated google.protobuf.Method methods = 2;
*/
methods: Method[];
/**
* Any metadata attached to the interface.
*
* @generated from field: repeated google.protobuf.Option options = 3;
*/
options: Option[];
/**
* A version string for this interface. If specified, must have the form
* `major-version.minor-version`, as in `1.10`. If the minor version is
* omitted, it defaults to zero. If the entire version field is empty, the
* major version is derived from the package name, as outlined below. If the
* field is not empty, the version in the package name will be verified to be
* consistent with what is provided here.
*
* The versioning schema uses [semantic
* versioning](http://semver.org) where the major version number
* indicates a breaking change and the minor version an additive,
* non-breaking change. Both version numbers are signals to users
* what to expect from different versions, and should be carefully
* chosen based on the product plan.
*
* The major version is also reflected in the package name of the
* interface, which must end in `v<major-version>`, as in
* `google.feature.v1`. For major versions 0 and 1, the suffix can
* be omitted. Zero major versions must only be used for
* experimental, non-GA interfaces.
*
*
* @generated from field: string version = 4;
*/
version: string;
/**
* Source context for the protocol buffer service represented by this
* message.
*
* @generated from field: google.protobuf.SourceContext source_context = 5;
*/
sourceContext?: SourceContext;
/**
* Included interfaces. See [Mixin][].
*
* @generated from field: repeated google.protobuf.Mixin mixins = 6;
*/
mixins: Mixin[];
/**
* The source syntax of the service.
*
* @generated from field: google.protobuf.Syntax syntax = 7;
*/
syntax: Syntax;
constructor(data?: PartialMessage<Api>);
static readonly runtime: typeof proto3;
static readonly typeName = "google.protobuf.Api";
static readonly fields: FieldList;
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): Api;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): Api;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): Api;
static equals(a: Api | PlainMessage<Api> | undefined, b: Api | PlainMessage<Api> | undefined): boolean;
}
/**
* Method represents a method of an API interface.
*
* @generated from message google.protobuf.Method
*/
export declare class Method extends Message<Method> {
/**
* The simple name of this method.
*
* @generated from field: string name = 1;
*/
name: string;
/**
* A URL of the input message type.
*
* @generated from field: string request_type_url = 2;
*/
requestTypeUrl: string;
/**
* If true, the request is streamed.
*
* @generated from field: bool request_streaming = 3;
*/
requestStreaming: boolean;
/**
* The URL of the output message type.
*
* @generated from field: string response_type_url = 4;
*/
responseTypeUrl: string;
/**
* If true, the response is streamed.
*
* @generated from field: bool response_streaming = 5;
*/
responseStreaming: boolean;
/**
* Any metadata attached to the method.
*
* @generated from field: repeated google.protobuf.Option options = 6;
*/
options: Option[];
/**
* The source syntax of this method.
*
* @generated from field: google.protobuf.Syntax syntax = 7;
*/
syntax: Syntax;
constructor(data?: PartialMessage<Method>);
static readonly runtime: typeof proto3;
static readonly typeName = "google.protobuf.Method";
static readonly fields: FieldList;
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): Method;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): Method;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): Method;
static equals(a: Method | PlainMessage<Method> | undefined, b: Method | PlainMessage<Method> | undefined): boolean;
}
/**
* Declares an API Interface to be included in this interface. The including
* interface must redeclare all the methods from the included interface, but
* documentation and options are inherited as follows:
*
* - If after comment and whitespace stripping, the documentation
* string of the redeclared method is empty, it will be inherited
* from the original method.
*
* - Each annotation belonging to the service config (http,
* visibility) which is not set in the redeclared method will be
* inherited.
*
* - If an http annotation is inherited, the path pattern will be
* modified as follows. Any version prefix will be replaced by the
* version of the including interface plus the [root][] path if
* specified.
*
* Example of a simple mixin:
*
* package google.acl.v1;
* service AccessControl {
* // Get the underlying ACL object.
* rpc GetAcl(GetAclRequest) returns (Acl) {
* option (google.api.http).get = "/v1/{resource=**}:getAcl";
* }
* }
*
* package google.storage.v2;
* service Storage {
* rpc GetAcl(GetAclRequest) returns (Acl);
*
* // Get a data record.
* rpc GetData(GetDataRequest) returns (Data) {
* option (google.api.http).get = "/v2/{resource=**}";
* }
* }
*
* Example of a mixin configuration:
*
* apis:
* - name: google.storage.v2.Storage
* mixins:
* - name: google.acl.v1.AccessControl
*
* The mixin construct implies that all methods in `AccessControl` are
* also declared with same name and request/response types in
* `Storage`. A documentation generator or annotation processor will
* see the effective `Storage.GetAcl` method after inherting
* documentation and annotations as follows:
*
* service Storage {
* // Get the underlying ACL object.
* rpc GetAcl(GetAclRequest) returns (Acl) {
* option (google.api.http).get = "/v2/{resource=**}:getAcl";
* }
* ...
* }
*
* Note how the version in the path pattern changed from `v1` to `v2`.
*
* If the `root` field in the mixin is specified, it should be a
* relative path under which inherited HTTP paths are placed. Example:
*
* apis:
* - name: google.storage.v2.Storage
* mixins:
* - name: google.acl.v1.AccessControl
* root: acls
*
* This implies the following inherited HTTP annotation:
*
* service Storage {
* // Get the underlying ACL object.
* rpc GetAcl(GetAclRequest) returns (Acl) {
* option (google.api.http).get = "/v2/acls/{resource=**}:getAcl";
* }
* ...
* }
*
* @generated from message google.protobuf.Mixin
*/
export declare class Mixin extends Message<Mixin> {
/**
* The fully qualified name of the interface which is included.
*
* @generated from field: string name = 1;
*/
name: string;
/**
* If non-empty specifies a path under which inherited HTTP paths
* are rooted.
*
* @generated from field: string root = 2;
*/
root: string;
constructor(data?: PartialMessage<Mixin>);
static readonly runtime: typeof proto3;
static readonly typeName = "google.protobuf.Mixin";
static readonly fields: FieldList;
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): Mixin;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): Mixin;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): Mixin;
static equals(a: Mixin | PlainMessage<Mixin> | undefined, b: Mixin | PlainMessage<Mixin> | undefined): boolean;
}
+316
View File
@@ -0,0 +1,316 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.Mixin = exports.Method = exports.Api = void 0;
const message_js_1 = require("../../message.js");
const type_pb_js_1 = require("./type_pb.js");
const source_context_pb_js_1 = require("./source_context_pb.js");
const proto3_js_1 = require("../../proto3.js");
/**
* Api is a light-weight descriptor for an API Interface.
*
* Interfaces are also described as "protocol buffer services" in some contexts,
* such as by the "service" keyword in a .proto file, but they are different
* from API Services, which represent a concrete implementation of an interface
* as opposed to simply a description of methods and bindings. They are also
* sometimes simply referred to as "APIs" in other contexts, such as the name of
* this message itself. See https://cloud.google.com/apis/design/glossary for
* detailed terminology.
*
* @generated from message google.protobuf.Api
*/
class Api extends message_js_1.Message {
constructor(data) {
super();
/**
* The fully qualified name of this interface, including package name
* followed by the interface's simple name.
*
* @generated from field: string name = 1;
*/
this.name = "";
/**
* The methods of this interface, in unspecified order.
*
* @generated from field: repeated google.protobuf.Method methods = 2;
*/
this.methods = [];
/**
* Any metadata attached to the interface.
*
* @generated from field: repeated google.protobuf.Option options = 3;
*/
this.options = [];
/**
* A version string for this interface. If specified, must have the form
* `major-version.minor-version`, as in `1.10`. If the minor version is
* omitted, it defaults to zero. If the entire version field is empty, the
* major version is derived from the package name, as outlined below. If the
* field is not empty, the version in the package name will be verified to be
* consistent with what is provided here.
*
* The versioning schema uses [semantic
* versioning](http://semver.org) where the major version number
* indicates a breaking change and the minor version an additive,
* non-breaking change. Both version numbers are signals to users
* what to expect from different versions, and should be carefully
* chosen based on the product plan.
*
* The major version is also reflected in the package name of the
* interface, which must end in `v<major-version>`, as in
* `google.feature.v1`. For major versions 0 and 1, the suffix can
* be omitted. Zero major versions must only be used for
* experimental, non-GA interfaces.
*
*
* @generated from field: string version = 4;
*/
this.version = "";
/**
* Included interfaces. See [Mixin][].
*
* @generated from field: repeated google.protobuf.Mixin mixins = 6;
*/
this.mixins = [];
/**
* The source syntax of the service.
*
* @generated from field: google.protobuf.Syntax syntax = 7;
*/
this.syntax = type_pb_js_1.Syntax.PROTO2;
proto3_js_1.proto3.util.initPartial(data, this);
}
static fromBinary(bytes, options) {
return new Api().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new Api().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new Api().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto3_js_1.proto3.util.equals(Api, a, b);
}
}
exports.Api = Api;
Api.runtime = proto3_js_1.proto3;
Api.typeName = "google.protobuf.Api";
Api.fields = proto3_js_1.proto3.util.newFieldList(() => [
{ no: 1, name: "name", kind: "scalar", T: 9 /* ScalarType.STRING */ },
{ no: 2, name: "methods", kind: "message", T: Method, repeated: true },
{ no: 3, name: "options", kind: "message", T: type_pb_js_1.Option, repeated: true },
{ no: 4, name: "version", kind: "scalar", T: 9 /* ScalarType.STRING */ },
{ no: 5, name: "source_context", kind: "message", T: source_context_pb_js_1.SourceContext },
{ no: 6, name: "mixins", kind: "message", T: Mixin, repeated: true },
{ no: 7, name: "syntax", kind: "enum", T: proto3_js_1.proto3.getEnumType(type_pb_js_1.Syntax) },
]);
/**
* Method represents a method of an API interface.
*
* @generated from message google.protobuf.Method
*/
class Method extends message_js_1.Message {
constructor(data) {
super();
/**
* The simple name of this method.
*
* @generated from field: string name = 1;
*/
this.name = "";
/**
* A URL of the input message type.
*
* @generated from field: string request_type_url = 2;
*/
this.requestTypeUrl = "";
/**
* If true, the request is streamed.
*
* @generated from field: bool request_streaming = 3;
*/
this.requestStreaming = false;
/**
* The URL of the output message type.
*
* @generated from field: string response_type_url = 4;
*/
this.responseTypeUrl = "";
/**
* If true, the response is streamed.
*
* @generated from field: bool response_streaming = 5;
*/
this.responseStreaming = false;
/**
* Any metadata attached to the method.
*
* @generated from field: repeated google.protobuf.Option options = 6;
*/
this.options = [];
/**
* The source syntax of this method.
*
* @generated from field: google.protobuf.Syntax syntax = 7;
*/
this.syntax = type_pb_js_1.Syntax.PROTO2;
proto3_js_1.proto3.util.initPartial(data, this);
}
static fromBinary(bytes, options) {
return new Method().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new Method().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new Method().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto3_js_1.proto3.util.equals(Method, a, b);
}
}
exports.Method = Method;
Method.runtime = proto3_js_1.proto3;
Method.typeName = "google.protobuf.Method";
Method.fields = proto3_js_1.proto3.util.newFieldList(() => [
{ no: 1, name: "name", kind: "scalar", T: 9 /* ScalarType.STRING */ },
{ no: 2, name: "request_type_url", kind: "scalar", T: 9 /* ScalarType.STRING */ },
{ no: 3, name: "request_streaming", kind: "scalar", T: 8 /* ScalarType.BOOL */ },
{ no: 4, name: "response_type_url", kind: "scalar", T: 9 /* ScalarType.STRING */ },
{ no: 5, name: "response_streaming", kind: "scalar", T: 8 /* ScalarType.BOOL */ },
{ no: 6, name: "options", kind: "message", T: type_pb_js_1.Option, repeated: true },
{ no: 7, name: "syntax", kind: "enum", T: proto3_js_1.proto3.getEnumType(type_pb_js_1.Syntax) },
]);
/**
* Declares an API Interface to be included in this interface. The including
* interface must redeclare all the methods from the included interface, but
* documentation and options are inherited as follows:
*
* - If after comment and whitespace stripping, the documentation
* string of the redeclared method is empty, it will be inherited
* from the original method.
*
* - Each annotation belonging to the service config (http,
* visibility) which is not set in the redeclared method will be
* inherited.
*
* - If an http annotation is inherited, the path pattern will be
* modified as follows. Any version prefix will be replaced by the
* version of the including interface plus the [root][] path if
* specified.
*
* Example of a simple mixin:
*
* package google.acl.v1;
* service AccessControl {
* // Get the underlying ACL object.
* rpc GetAcl(GetAclRequest) returns (Acl) {
* option (google.api.http).get = "/v1/{resource=**}:getAcl";
* }
* }
*
* package google.storage.v2;
* service Storage {
* rpc GetAcl(GetAclRequest) returns (Acl);
*
* // Get a data record.
* rpc GetData(GetDataRequest) returns (Data) {
* option (google.api.http).get = "/v2/{resource=**}";
* }
* }
*
* Example of a mixin configuration:
*
* apis:
* - name: google.storage.v2.Storage
* mixins:
* - name: google.acl.v1.AccessControl
*
* The mixin construct implies that all methods in `AccessControl` are
* also declared with same name and request/response types in
* `Storage`. A documentation generator or annotation processor will
* see the effective `Storage.GetAcl` method after inherting
* documentation and annotations as follows:
*
* service Storage {
* // Get the underlying ACL object.
* rpc GetAcl(GetAclRequest) returns (Acl) {
* option (google.api.http).get = "/v2/{resource=**}:getAcl";
* }
* ...
* }
*
* Note how the version in the path pattern changed from `v1` to `v2`.
*
* If the `root` field in the mixin is specified, it should be a
* relative path under which inherited HTTP paths are placed. Example:
*
* apis:
* - name: google.storage.v2.Storage
* mixins:
* - name: google.acl.v1.AccessControl
* root: acls
*
* This implies the following inherited HTTP annotation:
*
* service Storage {
* // Get the underlying ACL object.
* rpc GetAcl(GetAclRequest) returns (Acl) {
* option (google.api.http).get = "/v2/acls/{resource=**}:getAcl";
* }
* ...
* }
*
* @generated from message google.protobuf.Mixin
*/
class Mixin extends message_js_1.Message {
constructor(data) {
super();
/**
* The fully qualified name of the interface which is included.
*
* @generated from field: string name = 1;
*/
this.name = "";
/**
* If non-empty specifies a path under which inherited HTTP paths
* are rooted.
*
* @generated from field: string root = 2;
*/
this.root = "";
proto3_js_1.proto3.util.initPartial(data, this);
}
static fromBinary(bytes, options) {
return new Mixin().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new Mixin().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new Mixin().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto3_js_1.proto3.util.equals(Mixin, a, b);
}
}
exports.Mixin = Mixin;
Mixin.runtime = proto3_js_1.proto3;
Mixin.typeName = "google.protobuf.Mixin";
Mixin.fields = proto3_js_1.proto3.util.newFieldList(() => [
{ no: 1, name: "name", kind: "scalar", T: 9 /* ScalarType.STRING */ },
{ no: 2, name: "root", kind: "scalar", T: 9 /* ScalarType.STRING */ },
]);
@@ -0,0 +1,271 @@
import type { PartialMessage, PlainMessage } from "../../../message.js";
import { Message } from "../../../message.js";
import { proto2 } from "../../../proto2.js";
import type { FieldList } from "../../../field-list.js";
import type { BinaryReadOptions } from "../../../binary-format.js";
import type { JsonReadOptions, JsonValue } from "../../../json-format.js";
import { FileDescriptorProto, GeneratedCodeInfo } from "../descriptor_pb.js";
/**
* The version number of protocol compiler.
*
* @generated from message google.protobuf.compiler.Version
*/
export declare class Version extends Message<Version> {
/**
* @generated from field: optional int32 major = 1;
*/
major?: number;
/**
* @generated from field: optional int32 minor = 2;
*/
minor?: number;
/**
* @generated from field: optional int32 patch = 3;
*/
patch?: number;
/**
* A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should
* be empty for mainline stable releases.
*
* @generated from field: optional string suffix = 4;
*/
suffix?: string;
constructor(data?: PartialMessage<Version>);
static readonly runtime: typeof proto2;
static readonly typeName = "google.protobuf.compiler.Version";
static readonly fields: FieldList;
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): Version;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): Version;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): Version;
static equals(a: Version | PlainMessage<Version> | undefined, b: Version | PlainMessage<Version> | undefined): boolean;
}
/**
* An encoded CodeGeneratorRequest is written to the plugin's stdin.
*
* @generated from message google.protobuf.compiler.CodeGeneratorRequest
*/
export declare class CodeGeneratorRequest extends Message<CodeGeneratorRequest> {
/**
* The .proto files that were explicitly listed on the command-line. The
* code generator should generate code only for these files. Each file's
* descriptor will be included in proto_file, below.
*
* @generated from field: repeated string file_to_generate = 1;
*/
fileToGenerate: string[];
/**
* The generator parameter passed on the command-line.
*
* @generated from field: optional string parameter = 2;
*/
parameter?: string;
/**
* FileDescriptorProtos for all files in files_to_generate and everything
* they import. The files will appear in topological order, so each file
* appears before any file that imports it.
*
* Note: the files listed in files_to_generate will include runtime-retention
* options only, but all other files will include source-retention options.
* The source_file_descriptors field below is available in case you need
* source-retention options for files_to_generate.
*
* protoc guarantees that all proto_files will be written after
* the fields above, even though this is not technically guaranteed by the
* protobuf wire format. This theoretically could allow a plugin to stream
* in the FileDescriptorProtos and handle them one by one rather than read
* the entire set into memory at once. However, as of this writing, this
* is not similarly optimized on protoc's end -- it will store all fields in
* memory at once before sending them to the plugin.
*
* Type names of fields and extensions in the FileDescriptorProto are always
* fully qualified.
*
* @generated from field: repeated google.protobuf.FileDescriptorProto proto_file = 15;
*/
protoFile: FileDescriptorProto[];
/**
* File descriptors with all options, including source-retention options.
* These descriptors are only provided for the files listed in
* files_to_generate.
*
* @generated from field: repeated google.protobuf.FileDescriptorProto source_file_descriptors = 17;
*/
sourceFileDescriptors: FileDescriptorProto[];
/**
* The version number of protocol compiler.
*
* @generated from field: optional google.protobuf.compiler.Version compiler_version = 3;
*/
compilerVersion?: Version;
constructor(data?: PartialMessage<CodeGeneratorRequest>);
static readonly runtime: typeof proto2;
static readonly typeName = "google.protobuf.compiler.CodeGeneratorRequest";
static readonly fields: FieldList;
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): CodeGeneratorRequest;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): CodeGeneratorRequest;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): CodeGeneratorRequest;
static equals(a: CodeGeneratorRequest | PlainMessage<CodeGeneratorRequest> | undefined, b: CodeGeneratorRequest | PlainMessage<CodeGeneratorRequest> | undefined): boolean;
}
/**
* The plugin writes an encoded CodeGeneratorResponse to stdout.
*
* @generated from message google.protobuf.compiler.CodeGeneratorResponse
*/
export declare class CodeGeneratorResponse extends Message<CodeGeneratorResponse> {
/**
* Error message. If non-empty, code generation failed. The plugin process
* should exit with status code zero even if it reports an error in this way.
*
* This should be used to indicate errors in .proto files which prevent the
* code generator from generating correct code. Errors which indicate a
* problem in protoc itself -- such as the input CodeGeneratorRequest being
* unparseable -- should be reported by writing a message to stderr and
* exiting with a non-zero status code.
*
* @generated from field: optional string error = 1;
*/
error?: string;
/**
* A bitmask of supported features that the code generator supports.
* This is a bitwise "or" of values from the Feature enum.
*
* @generated from field: optional uint64 supported_features = 2;
*/
supportedFeatures?: bigint;
/**
* The minimum edition this plugin supports. This will be treated as an
* Edition enum, but we want to allow unknown values. It should be specified
* according the edition enum value, *not* the edition number. Only takes
* effect for plugins that have FEATURE_SUPPORTS_EDITIONS set.
*
* @generated from field: optional int32 minimum_edition = 3;
*/
minimumEdition?: number;
/**
* The maximum edition this plugin supports. This will be treated as an
* Edition enum, but we want to allow unknown values. It should be specified
* according the edition enum value, *not* the edition number. Only takes
* effect for plugins that have FEATURE_SUPPORTS_EDITIONS set.
*
* @generated from field: optional int32 maximum_edition = 4;
*/
maximumEdition?: number;
/**
* @generated from field: repeated google.protobuf.compiler.CodeGeneratorResponse.File file = 15;
*/
file: CodeGeneratorResponse_File[];
constructor(data?: PartialMessage<CodeGeneratorResponse>);
static readonly runtime: typeof proto2;
static readonly typeName = "google.protobuf.compiler.CodeGeneratorResponse";
static readonly fields: FieldList;
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): CodeGeneratorResponse;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): CodeGeneratorResponse;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): CodeGeneratorResponse;
static equals(a: CodeGeneratorResponse | PlainMessage<CodeGeneratorResponse> | undefined, b: CodeGeneratorResponse | PlainMessage<CodeGeneratorResponse> | undefined): boolean;
}
/**
* Sync with code_generator.h.
*
* @generated from enum google.protobuf.compiler.CodeGeneratorResponse.Feature
*/
export declare enum CodeGeneratorResponse_Feature {
/**
* @generated from enum value: FEATURE_NONE = 0;
*/
NONE = 0,
/**
* @generated from enum value: FEATURE_PROTO3_OPTIONAL = 1;
*/
PROTO3_OPTIONAL = 1,
/**
* @generated from enum value: FEATURE_SUPPORTS_EDITIONS = 2;
*/
SUPPORTS_EDITIONS = 2
}
/**
* Represents a single generated file.
*
* @generated from message google.protobuf.compiler.CodeGeneratorResponse.File
*/
export declare class CodeGeneratorResponse_File extends Message<CodeGeneratorResponse_File> {
/**
* The file name, relative to the output directory. The name must not
* contain "." or ".." components and must be relative, not be absolute (so,
* the file cannot lie outside the output directory). "/" must be used as
* the path separator, not "\".
*
* If the name is omitted, the content will be appended to the previous
* file. This allows the generator to break large files into small chunks,
* and allows the generated text to be streamed back to protoc so that large
* files need not reside completely in memory at one time. Note that as of
* this writing protoc does not optimize for this -- it will read the entire
* CodeGeneratorResponse before writing files to disk.
*
* @generated from field: optional string name = 1;
*/
name?: string;
/**
* If non-empty, indicates that the named file should already exist, and the
* content here is to be inserted into that file at a defined insertion
* point. This feature allows a code generator to extend the output
* produced by another code generator. The original generator may provide
* insertion points by placing special annotations in the file that look
* like:
* @@protoc_insertion_point(NAME)
* The annotation can have arbitrary text before and after it on the line,
* which allows it to be placed in a comment. NAME should be replaced with
* an identifier naming the point -- this is what other generators will use
* as the insertion_point. Code inserted at this point will be placed
* immediately above the line containing the insertion point (thus multiple
* insertions to the same point will come out in the order they were added).
* The double-@ is intended to make it unlikely that the generated code
* could contain things that look like insertion points by accident.
*
* For example, the C++ code generator places the following line in the
* .pb.h files that it generates:
* // @@protoc_insertion_point(namespace_scope)
* This line appears within the scope of the file's package namespace, but
* outside of any particular class. Another plugin can then specify the
* insertion_point "namespace_scope" to generate additional classes or
* other declarations that should be placed in this scope.
*
* Note that if the line containing the insertion point begins with
* whitespace, the same whitespace will be added to every line of the
* inserted text. This is useful for languages like Python, where
* indentation matters. In these languages, the insertion point comment
* should be indented the same amount as any inserted code will need to be
* in order to work correctly in that context.
*
* The code generator that generates the initial file and the one which
* inserts into it must both run as part of a single invocation of protoc.
* Code generators are executed in the order in which they appear on the
* command line.
*
* If |insertion_point| is present, |name| must also be present.
*
* @generated from field: optional string insertion_point = 2;
*/
insertionPoint?: string;
/**
* The file contents.
*
* @generated from field: optional string content = 15;
*/
content?: string;
/**
* Information describing the file content being inserted. If an insertion
* point is used, this information will be appropriately offset and inserted
* into the code generation metadata for the generated files.
*
* @generated from field: optional google.protobuf.GeneratedCodeInfo generated_code_info = 16;
*/
generatedCodeInfo?: GeneratedCodeInfo;
constructor(data?: PartialMessage<CodeGeneratorResponse_File>);
static readonly runtime: typeof proto2;
static readonly typeName = "google.protobuf.compiler.CodeGeneratorResponse.File";
static readonly fields: FieldList;
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): CodeGeneratorResponse_File;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): CodeGeneratorResponse_File;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): CodeGeneratorResponse_File;
static equals(a: CodeGeneratorResponse_File | PlainMessage<CodeGeneratorResponse_File> | undefined, b: CodeGeneratorResponse_File | PlainMessage<CodeGeneratorResponse_File> | undefined): boolean;
}
@@ -0,0 +1,219 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.CodeGeneratorResponse_File = exports.CodeGeneratorResponse_Feature = exports.CodeGeneratorResponse = exports.CodeGeneratorRequest = exports.Version = void 0;
const message_js_1 = require("../../../message.js");
const proto2_js_1 = require("../../../proto2.js");
const descriptor_pb_js_1 = require("../descriptor_pb.js");
/**
* The version number of protocol compiler.
*
* @generated from message google.protobuf.compiler.Version
*/
class Version extends message_js_1.Message {
constructor(data) {
super();
proto2_js_1.proto2.util.initPartial(data, this);
}
static fromBinary(bytes, options) {
return new Version().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new Version().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new Version().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto2_js_1.proto2.util.equals(Version, a, b);
}
}
exports.Version = Version;
Version.runtime = proto2_js_1.proto2;
Version.typeName = "google.protobuf.compiler.Version";
Version.fields = proto2_js_1.proto2.util.newFieldList(() => [
{ no: 1, name: "major", kind: "scalar", T: 5 /* ScalarType.INT32 */, opt: true },
{ no: 2, name: "minor", kind: "scalar", T: 5 /* ScalarType.INT32 */, opt: true },
{ no: 3, name: "patch", kind: "scalar", T: 5 /* ScalarType.INT32 */, opt: true },
{ no: 4, name: "suffix", kind: "scalar", T: 9 /* ScalarType.STRING */, opt: true },
]);
/**
* An encoded CodeGeneratorRequest is written to the plugin's stdin.
*
* @generated from message google.protobuf.compiler.CodeGeneratorRequest
*/
class CodeGeneratorRequest extends message_js_1.Message {
constructor(data) {
super();
/**
* The .proto files that were explicitly listed on the command-line. The
* code generator should generate code only for these files. Each file's
* descriptor will be included in proto_file, below.
*
* @generated from field: repeated string file_to_generate = 1;
*/
this.fileToGenerate = [];
/**
* FileDescriptorProtos for all files in files_to_generate and everything
* they import. The files will appear in topological order, so each file
* appears before any file that imports it.
*
* Note: the files listed in files_to_generate will include runtime-retention
* options only, but all other files will include source-retention options.
* The source_file_descriptors field below is available in case you need
* source-retention options for files_to_generate.
*
* protoc guarantees that all proto_files will be written after
* the fields above, even though this is not technically guaranteed by the
* protobuf wire format. This theoretically could allow a plugin to stream
* in the FileDescriptorProtos and handle them one by one rather than read
* the entire set into memory at once. However, as of this writing, this
* is not similarly optimized on protoc's end -- it will store all fields in
* memory at once before sending them to the plugin.
*
* Type names of fields and extensions in the FileDescriptorProto are always
* fully qualified.
*
* @generated from field: repeated google.protobuf.FileDescriptorProto proto_file = 15;
*/
this.protoFile = [];
/**
* File descriptors with all options, including source-retention options.
* These descriptors are only provided for the files listed in
* files_to_generate.
*
* @generated from field: repeated google.protobuf.FileDescriptorProto source_file_descriptors = 17;
*/
this.sourceFileDescriptors = [];
proto2_js_1.proto2.util.initPartial(data, this);
}
static fromBinary(bytes, options) {
return new CodeGeneratorRequest().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new CodeGeneratorRequest().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new CodeGeneratorRequest().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto2_js_1.proto2.util.equals(CodeGeneratorRequest, a, b);
}
}
exports.CodeGeneratorRequest = CodeGeneratorRequest;
CodeGeneratorRequest.runtime = proto2_js_1.proto2;
CodeGeneratorRequest.typeName = "google.protobuf.compiler.CodeGeneratorRequest";
CodeGeneratorRequest.fields = proto2_js_1.proto2.util.newFieldList(() => [
{ no: 1, name: "file_to_generate", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true },
{ no: 2, name: "parameter", kind: "scalar", T: 9 /* ScalarType.STRING */, opt: true },
{ no: 15, name: "proto_file", kind: "message", T: descriptor_pb_js_1.FileDescriptorProto, repeated: true },
{ no: 17, name: "source_file_descriptors", kind: "message", T: descriptor_pb_js_1.FileDescriptorProto, repeated: true },
{ no: 3, name: "compiler_version", kind: "message", T: Version, opt: true },
]);
/**
* The plugin writes an encoded CodeGeneratorResponse to stdout.
*
* @generated from message google.protobuf.compiler.CodeGeneratorResponse
*/
class CodeGeneratorResponse extends message_js_1.Message {
constructor(data) {
super();
/**
* @generated from field: repeated google.protobuf.compiler.CodeGeneratorResponse.File file = 15;
*/
this.file = [];
proto2_js_1.proto2.util.initPartial(data, this);
}
static fromBinary(bytes, options) {
return new CodeGeneratorResponse().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new CodeGeneratorResponse().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new CodeGeneratorResponse().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto2_js_1.proto2.util.equals(CodeGeneratorResponse, a, b);
}
}
exports.CodeGeneratorResponse = CodeGeneratorResponse;
CodeGeneratorResponse.runtime = proto2_js_1.proto2;
CodeGeneratorResponse.typeName = "google.protobuf.compiler.CodeGeneratorResponse";
CodeGeneratorResponse.fields = proto2_js_1.proto2.util.newFieldList(() => [
{ no: 1, name: "error", kind: "scalar", T: 9 /* ScalarType.STRING */, opt: true },
{ no: 2, name: "supported_features", kind: "scalar", T: 4 /* ScalarType.UINT64 */, opt: true },
{ no: 3, name: "minimum_edition", kind: "scalar", T: 5 /* ScalarType.INT32 */, opt: true },
{ no: 4, name: "maximum_edition", kind: "scalar", T: 5 /* ScalarType.INT32 */, opt: true },
{ no: 15, name: "file", kind: "message", T: CodeGeneratorResponse_File, repeated: true },
]);
/**
* Sync with code_generator.h.
*
* @generated from enum google.protobuf.compiler.CodeGeneratorResponse.Feature
*/
var CodeGeneratorResponse_Feature;
(function (CodeGeneratorResponse_Feature) {
/**
* @generated from enum value: FEATURE_NONE = 0;
*/
CodeGeneratorResponse_Feature[CodeGeneratorResponse_Feature["NONE"] = 0] = "NONE";
/**
* @generated from enum value: FEATURE_PROTO3_OPTIONAL = 1;
*/
CodeGeneratorResponse_Feature[CodeGeneratorResponse_Feature["PROTO3_OPTIONAL"] = 1] = "PROTO3_OPTIONAL";
/**
* @generated from enum value: FEATURE_SUPPORTS_EDITIONS = 2;
*/
CodeGeneratorResponse_Feature[CodeGeneratorResponse_Feature["SUPPORTS_EDITIONS"] = 2] = "SUPPORTS_EDITIONS";
})(CodeGeneratorResponse_Feature || (exports.CodeGeneratorResponse_Feature = CodeGeneratorResponse_Feature = {}));
// Retrieve enum metadata with: proto2.getEnumType(CodeGeneratorResponse_Feature)
proto2_js_1.proto2.util.setEnumType(CodeGeneratorResponse_Feature, "google.protobuf.compiler.CodeGeneratorResponse.Feature", [
{ no: 0, name: "FEATURE_NONE" },
{ no: 1, name: "FEATURE_PROTO3_OPTIONAL" },
{ no: 2, name: "FEATURE_SUPPORTS_EDITIONS" },
]);
/**
* Represents a single generated file.
*
* @generated from message google.protobuf.compiler.CodeGeneratorResponse.File
*/
class CodeGeneratorResponse_File extends message_js_1.Message {
constructor(data) {
super();
proto2_js_1.proto2.util.initPartial(data, this);
}
static fromBinary(bytes, options) {
return new CodeGeneratorResponse_File().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new CodeGeneratorResponse_File().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new CodeGeneratorResponse_File().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto2_js_1.proto2.util.equals(CodeGeneratorResponse_File, a, b);
}
}
exports.CodeGeneratorResponse_File = CodeGeneratorResponse_File;
CodeGeneratorResponse_File.runtime = proto2_js_1.proto2;
CodeGeneratorResponse_File.typeName = "google.protobuf.compiler.CodeGeneratorResponse.File";
CodeGeneratorResponse_File.fields = proto2_js_1.proto2.util.newFieldList(() => [
{ no: 1, name: "name", kind: "scalar", T: 9 /* ScalarType.STRING */, opt: true },
{ no: 2, name: "insertion_point", kind: "scalar", T: 9 /* ScalarType.STRING */, opt: true },
{ no: 15, name: "content", kind: "scalar", T: 9 /* ScalarType.STRING */, opt: true },
{ no: 16, name: "generated_code_info", kind: "message", T: descriptor_pb_js_1.GeneratedCodeInfo, opt: true },
]);
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,100 @@
import type { PartialMessage, PlainMessage } from "../../message.js";
import { Message } from "../../message.js";
import { proto3 } from "../../proto3.js";
import type { JsonReadOptions, JsonValue, JsonWriteOptions } from "../../json-format.js";
import type { FieldList } from "../../field-list.js";
import type { BinaryReadOptions } from "../../binary-format.js";
/**
* A Duration represents a signed, fixed-length span of time represented
* as a count of seconds and fractions of seconds at nanosecond
* resolution. It is independent of any calendar and concepts like "day"
* or "month". It is related to Timestamp in that the difference between
* two Timestamp values is a Duration and it can be added or subtracted
* from a Timestamp. Range is approximately +-10,000 years.
*
* # Examples
*
* Example 1: Compute Duration from two Timestamps in pseudo code.
*
* Timestamp start = ...;
* Timestamp end = ...;
* Duration duration = ...;
*
* duration.seconds = end.seconds - start.seconds;
* duration.nanos = end.nanos - start.nanos;
*
* if (duration.seconds < 0 && duration.nanos > 0) {
* duration.seconds += 1;
* duration.nanos -= 1000000000;
* } else if (duration.seconds > 0 && duration.nanos < 0) {
* duration.seconds -= 1;
* duration.nanos += 1000000000;
* }
*
* Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
*
* Timestamp start = ...;
* Duration duration = ...;
* Timestamp end = ...;
*
* end.seconds = start.seconds + duration.seconds;
* end.nanos = start.nanos + duration.nanos;
*
* if (end.nanos < 0) {
* end.seconds -= 1;
* end.nanos += 1000000000;
* } else if (end.nanos >= 1000000000) {
* end.seconds += 1;
* end.nanos -= 1000000000;
* }
*
* Example 3: Compute Duration from datetime.timedelta in Python.
*
* td = datetime.timedelta(days=3, minutes=10)
* duration = Duration()
* duration.FromTimedelta(td)
*
* # JSON Mapping
*
* In JSON format, the Duration type is encoded as a string rather than an
* object, where the string ends in the suffix "s" (indicating seconds) and
* is preceded by the number of seconds, with nanoseconds expressed as
* fractional seconds. For example, 3 seconds with 0 nanoseconds should be
* encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
* be expressed in JSON format as "3.000000001s", and 3 seconds and 1
* microsecond should be expressed in JSON format as "3.000001s".
*
*
* @generated from message google.protobuf.Duration
*/
export declare class Duration extends Message<Duration> {
/**
* Signed seconds of the span of time. Must be from -315,576,000,000
* to +315,576,000,000 inclusive. Note: these bounds are computed from:
* 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
*
* @generated from field: int64 seconds = 1;
*/
seconds: bigint;
/**
* Signed fractions of a second at nanosecond resolution of the span
* of time. Durations less than one second are represented with a 0
* `seconds` field and a positive or negative `nanos` field. For durations
* of one second or more, a non-zero value for the `nanos` field must be
* of the same sign as the `seconds` field. Must be from -999,999,999
* to +999,999,999 inclusive.
*
* @generated from field: int32 nanos = 2;
*/
nanos: number;
constructor(data?: PartialMessage<Duration>);
fromJson(json: JsonValue, options?: Partial<JsonReadOptions>): this;
toJson(options?: Partial<JsonWriteOptions>): JsonValue;
static readonly runtime: typeof proto3;
static readonly typeName = "google.protobuf.Duration";
static readonly fields: FieldList;
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): Duration;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): Duration;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): Duration;
static equals(a: Duration | PlainMessage<Duration> | undefined, b: Duration | PlainMessage<Duration> | undefined): boolean;
}
+169
View File
@@ -0,0 +1,169 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.Duration = void 0;
const message_js_1 = require("../../message.js");
const proto_int64_js_1 = require("../../proto-int64.js");
const proto3_js_1 = require("../../proto3.js");
/**
* A Duration represents a signed, fixed-length span of time represented
* as a count of seconds and fractions of seconds at nanosecond
* resolution. It is independent of any calendar and concepts like "day"
* or "month". It is related to Timestamp in that the difference between
* two Timestamp values is a Duration and it can be added or subtracted
* from a Timestamp. Range is approximately +-10,000 years.
*
* # Examples
*
* Example 1: Compute Duration from two Timestamps in pseudo code.
*
* Timestamp start = ...;
* Timestamp end = ...;
* Duration duration = ...;
*
* duration.seconds = end.seconds - start.seconds;
* duration.nanos = end.nanos - start.nanos;
*
* if (duration.seconds < 0 && duration.nanos > 0) {
* duration.seconds += 1;
* duration.nanos -= 1000000000;
* } else if (duration.seconds > 0 && duration.nanos < 0) {
* duration.seconds -= 1;
* duration.nanos += 1000000000;
* }
*
* Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
*
* Timestamp start = ...;
* Duration duration = ...;
* Timestamp end = ...;
*
* end.seconds = start.seconds + duration.seconds;
* end.nanos = start.nanos + duration.nanos;
*
* if (end.nanos < 0) {
* end.seconds -= 1;
* end.nanos += 1000000000;
* } else if (end.nanos >= 1000000000) {
* end.seconds += 1;
* end.nanos -= 1000000000;
* }
*
* Example 3: Compute Duration from datetime.timedelta in Python.
*
* td = datetime.timedelta(days=3, minutes=10)
* duration = Duration()
* duration.FromTimedelta(td)
*
* # JSON Mapping
*
* In JSON format, the Duration type is encoded as a string rather than an
* object, where the string ends in the suffix "s" (indicating seconds) and
* is preceded by the number of seconds, with nanoseconds expressed as
* fractional seconds. For example, 3 seconds with 0 nanoseconds should be
* encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
* be expressed in JSON format as "3.000000001s", and 3 seconds and 1
* microsecond should be expressed in JSON format as "3.000001s".
*
*
* @generated from message google.protobuf.Duration
*/
class Duration extends message_js_1.Message {
constructor(data) {
super();
/**
* Signed seconds of the span of time. Must be from -315,576,000,000
* to +315,576,000,000 inclusive. Note: these bounds are computed from:
* 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
*
* @generated from field: int64 seconds = 1;
*/
this.seconds = proto_int64_js_1.protoInt64.zero;
/**
* Signed fractions of a second at nanosecond resolution of the span
* of time. Durations less than one second are represented with a 0
* `seconds` field and a positive or negative `nanos` field. For durations
* of one second or more, a non-zero value for the `nanos` field must be
* of the same sign as the `seconds` field. Must be from -999,999,999
* to +999,999,999 inclusive.
*
* @generated from field: int32 nanos = 2;
*/
this.nanos = 0;
proto3_js_1.proto3.util.initPartial(data, this);
}
fromJson(json, options) {
if (typeof json !== "string") {
throw new Error(`cannot decode google.protobuf.Duration from JSON: ${proto3_js_1.proto3.json.debug(json)}`);
}
const match = json.match(/^(-?[0-9]+)(?:\.([0-9]+))?s/);
if (match === null) {
throw new Error(`cannot decode google.protobuf.Duration from JSON: ${proto3_js_1.proto3.json.debug(json)}`);
}
const longSeconds = Number(match[1]);
if (longSeconds > 315576000000 || longSeconds < -315576000000) {
throw new Error(`cannot decode google.protobuf.Duration from JSON: ${proto3_js_1.proto3.json.debug(json)}`);
}
this.seconds = proto_int64_js_1.protoInt64.parse(longSeconds);
if (typeof match[2] == "string") {
const nanosStr = match[2] + "0".repeat(9 - match[2].length);
this.nanos = parseInt(nanosStr);
if (longSeconds < 0 || Object.is(longSeconds, -0)) {
this.nanos = -this.nanos;
}
}
return this;
}
toJson(options) {
if (Number(this.seconds) > 315576000000 || Number(this.seconds) < -315576000000) {
throw new Error(`cannot encode google.protobuf.Duration to JSON: value out of range`);
}
let text = this.seconds.toString();
if (this.nanos !== 0) {
let nanosStr = Math.abs(this.nanos).toString();
nanosStr = "0".repeat(9 - nanosStr.length) + nanosStr;
if (nanosStr.substring(3) === "000000") {
nanosStr = nanosStr.substring(0, 3);
}
else if (nanosStr.substring(6) === "000") {
nanosStr = nanosStr.substring(0, 6);
}
text += "." + nanosStr;
if (this.nanos < 0 && Number(this.seconds) == 0) {
text = "-" + text;
}
}
return text + "s";
}
static fromBinary(bytes, options) {
return new Duration().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new Duration().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new Duration().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto3_js_1.proto3.util.equals(Duration, a, b);
}
}
exports.Duration = Duration;
Duration.runtime = proto3_js_1.proto3;
Duration.typeName = "google.protobuf.Duration";
Duration.fields = proto3_js_1.proto3.util.newFieldList(() => [
{ no: 1, name: "seconds", kind: "scalar", T: 3 /* ScalarType.INT64 */ },
{ no: 2, name: "nanos", kind: "scalar", T: 5 /* ScalarType.INT32 */ },
]);
+28
View File
@@ -0,0 +1,28 @@
import type { PartialMessage, PlainMessage } from "../../message.js";
import { Message } from "../../message.js";
import { proto3 } from "../../proto3.js";
import type { FieldList } from "../../field-list.js";
import type { BinaryReadOptions } from "../../binary-format.js";
import type { JsonReadOptions, JsonValue } from "../../json-format.js";
/**
* A generic empty message that you can re-use to avoid defining duplicated
* empty messages in your APIs. A typical example is to use it as the request
* or the response type of an API method. For instance:
*
* service Foo {
* rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
* }
*
*
* @generated from message google.protobuf.Empty
*/
export declare class Empty extends Message<Empty> {
constructor(data?: PartialMessage<Empty>);
static readonly runtime: typeof proto3;
static readonly typeName = "google.protobuf.Empty";
static readonly fields: FieldList;
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): Empty;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): Empty;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): Empty;
static equals(a: Empty | PlainMessage<Empty> | undefined, b: Empty | PlainMessage<Empty> | undefined): boolean;
}
+52
View File
@@ -0,0 +1,52 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.Empty = void 0;
const message_js_1 = require("../../message.js");
const proto3_js_1 = require("../../proto3.js");
/**
* A generic empty message that you can re-use to avoid defining duplicated
* empty messages in your APIs. A typical example is to use it as the request
* or the response type of an API method. For instance:
*
* service Foo {
* rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
* }
*
*
* @generated from message google.protobuf.Empty
*/
class Empty extends message_js_1.Message {
constructor(data) {
super();
proto3_js_1.proto3.util.initPartial(data, this);
}
static fromBinary(bytes, options) {
return new Empty().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new Empty().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new Empty().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto3_js_1.proto3.util.equals(Empty, a, b);
}
}
exports.Empty = Empty;
Empty.runtime = proto3_js_1.proto3;
Empty.typeName = "google.protobuf.Empty";
Empty.fields = proto3_js_1.proto3.util.newFieldList(() => []);
@@ -0,0 +1,227 @@
import type { PartialMessage, PlainMessage } from "../../message.js";
import { Message } from "../../message.js";
import { proto3 } from "../../proto3.js";
import type { JsonReadOptions, JsonValue, JsonWriteOptions } from "../../json-format.js";
import type { FieldList } from "../../field-list.js";
import type { BinaryReadOptions } from "../../binary-format.js";
/**
* `FieldMask` represents a set of symbolic field paths, for example:
*
* paths: "f.a"
* paths: "f.b.d"
*
* Here `f` represents a field in some root message, `a` and `b`
* fields in the message found in `f`, and `d` a field found in the
* message in `f.b`.
*
* Field masks are used to specify a subset of fields that should be
* returned by a get operation or modified by an update operation.
* Field masks also have a custom JSON encoding (see below).
*
* # Field Masks in Projections
*
* When used in the context of a projection, a response message or
* sub-message is filtered by the API to only contain those fields as
* specified in the mask. For example, if the mask in the previous
* example is applied to a response message as follows:
*
* f {
* a : 22
* b {
* d : 1
* x : 2
* }
* y : 13
* }
* z: 8
*
* The result will not contain specific values for fields x,y and z
* (their value will be set to the default, and omitted in proto text
* output):
*
*
* f {
* a : 22
* b {
* d : 1
* }
* }
*
* A repeated field is not allowed except at the last position of a
* paths string.
*
* If a FieldMask object is not present in a get operation, the
* operation applies to all fields (as if a FieldMask of all fields
* had been specified).
*
* Note that a field mask does not necessarily apply to the
* top-level response message. In case of a REST get operation, the
* field mask applies directly to the response, but in case of a REST
* list operation, the mask instead applies to each individual message
* in the returned resource list. In case of a REST custom method,
* other definitions may be used. Where the mask applies will be
* clearly documented together with its declaration in the API. In
* any case, the effect on the returned resource/resources is required
* behavior for APIs.
*
* # Field Masks in Update Operations
*
* A field mask in update operations specifies which fields of the
* targeted resource are going to be updated. The API is required
* to only change the values of the fields as specified in the mask
* and leave the others untouched. If a resource is passed in to
* describe the updated values, the API ignores the values of all
* fields not covered by the mask.
*
* If a repeated field is specified for an update operation, new values will
* be appended to the existing repeated field in the target resource. Note that
* a repeated field is only allowed in the last position of a `paths` string.
*
* If a sub-message is specified in the last position of the field mask for an
* update operation, then new value will be merged into the existing sub-message
* in the target resource.
*
* For example, given the target message:
*
* f {
* b {
* d: 1
* x: 2
* }
* c: [1]
* }
*
* And an update message:
*
* f {
* b {
* d: 10
* }
* c: [2]
* }
*
* then if the field mask is:
*
* paths: ["f.b", "f.c"]
*
* then the result will be:
*
* f {
* b {
* d: 10
* x: 2
* }
* c: [1, 2]
* }
*
* An implementation may provide options to override this default behavior for
* repeated and message fields.
*
* In order to reset a field's value to the default, the field must
* be in the mask and set to the default value in the provided resource.
* Hence, in order to reset all fields of a resource, provide a default
* instance of the resource and set all fields in the mask, or do
* not provide a mask as described below.
*
* If a field mask is not present on update, the operation applies to
* all fields (as if a field mask of all fields has been specified).
* Note that in the presence of schema evolution, this may mean that
* fields the client does not know and has therefore not filled into
* the request will be reset to their default. If this is unwanted
* behavior, a specific service may require a client to always specify
* a field mask, producing an error if not.
*
* As with get operations, the location of the resource which
* describes the updated values in the request message depends on the
* operation kind. In any case, the effect of the field mask is
* required to be honored by the API.
*
* ## Considerations for HTTP REST
*
* The HTTP kind of an update operation which uses a field mask must
* be set to PATCH instead of PUT in order to satisfy HTTP semantics
* (PUT must only be used for full updates).
*
* # JSON Encoding of Field Masks
*
* In JSON, a field mask is encoded as a single string where paths are
* separated by a comma. Fields name in each path are converted
* to/from lower-camel naming conventions.
*
* As an example, consider the following message declarations:
*
* message Profile {
* User user = 1;
* Photo photo = 2;
* }
* message User {
* string display_name = 1;
* string address = 2;
* }
*
* In proto a field mask for `Profile` may look as such:
*
* mask {
* paths: "user.display_name"
* paths: "photo"
* }
*
* In JSON, the same mask is represented as below:
*
* {
* mask: "user.displayName,photo"
* }
*
* # Field Masks and Oneof Fields
*
* Field masks treat fields in oneofs just as regular fields. Consider the
* following message:
*
* message SampleMessage {
* oneof test_oneof {
* string name = 4;
* SubMessage sub_message = 9;
* }
* }
*
* The field mask can be:
*
* mask {
* paths: "name"
* }
*
* Or:
*
* mask {
* paths: "sub_message"
* }
*
* Note that oneof type names ("test_oneof" in this case) cannot be used in
* paths.
*
* ## Field Mask Verification
*
* The implementation of any API method which has a FieldMask type field in the
* request should verify the included field paths, and return an
* `INVALID_ARGUMENT` error if any path is unmappable.
*
* @generated from message google.protobuf.FieldMask
*/
export declare class FieldMask extends Message<FieldMask> {
/**
* The set of field mask paths.
*
* @generated from field: repeated string paths = 1;
*/
paths: string[];
constructor(data?: PartialMessage<FieldMask>);
toJson(options?: Partial<JsonWriteOptions>): JsonValue;
fromJson(json: JsonValue, options?: Partial<JsonReadOptions>): this;
static readonly runtime: typeof proto3;
static readonly typeName = "google.protobuf.FieldMask";
static readonly fields: FieldList;
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): FieldMask;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): FieldMask;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): FieldMask;
static equals(a: FieldMask | PlainMessage<FieldMask> | undefined, b: FieldMask | PlainMessage<FieldMask> | undefined): boolean;
}
@@ -0,0 +1,311 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.FieldMask = void 0;
const message_js_1 = require("../../message.js");
const proto3_js_1 = require("../../proto3.js");
/**
* `FieldMask` represents a set of symbolic field paths, for example:
*
* paths: "f.a"
* paths: "f.b.d"
*
* Here `f` represents a field in some root message, `a` and `b`
* fields in the message found in `f`, and `d` a field found in the
* message in `f.b`.
*
* Field masks are used to specify a subset of fields that should be
* returned by a get operation or modified by an update operation.
* Field masks also have a custom JSON encoding (see below).
*
* # Field Masks in Projections
*
* When used in the context of a projection, a response message or
* sub-message is filtered by the API to only contain those fields as
* specified in the mask. For example, if the mask in the previous
* example is applied to a response message as follows:
*
* f {
* a : 22
* b {
* d : 1
* x : 2
* }
* y : 13
* }
* z: 8
*
* The result will not contain specific values for fields x,y and z
* (their value will be set to the default, and omitted in proto text
* output):
*
*
* f {
* a : 22
* b {
* d : 1
* }
* }
*
* A repeated field is not allowed except at the last position of a
* paths string.
*
* If a FieldMask object is not present in a get operation, the
* operation applies to all fields (as if a FieldMask of all fields
* had been specified).
*
* Note that a field mask does not necessarily apply to the
* top-level response message. In case of a REST get operation, the
* field mask applies directly to the response, but in case of a REST
* list operation, the mask instead applies to each individual message
* in the returned resource list. In case of a REST custom method,
* other definitions may be used. Where the mask applies will be
* clearly documented together with its declaration in the API. In
* any case, the effect on the returned resource/resources is required
* behavior for APIs.
*
* # Field Masks in Update Operations
*
* A field mask in update operations specifies which fields of the
* targeted resource are going to be updated. The API is required
* to only change the values of the fields as specified in the mask
* and leave the others untouched. If a resource is passed in to
* describe the updated values, the API ignores the values of all
* fields not covered by the mask.
*
* If a repeated field is specified for an update operation, new values will
* be appended to the existing repeated field in the target resource. Note that
* a repeated field is only allowed in the last position of a `paths` string.
*
* If a sub-message is specified in the last position of the field mask for an
* update operation, then new value will be merged into the existing sub-message
* in the target resource.
*
* For example, given the target message:
*
* f {
* b {
* d: 1
* x: 2
* }
* c: [1]
* }
*
* And an update message:
*
* f {
* b {
* d: 10
* }
* c: [2]
* }
*
* then if the field mask is:
*
* paths: ["f.b", "f.c"]
*
* then the result will be:
*
* f {
* b {
* d: 10
* x: 2
* }
* c: [1, 2]
* }
*
* An implementation may provide options to override this default behavior for
* repeated and message fields.
*
* In order to reset a field's value to the default, the field must
* be in the mask and set to the default value in the provided resource.
* Hence, in order to reset all fields of a resource, provide a default
* instance of the resource and set all fields in the mask, or do
* not provide a mask as described below.
*
* If a field mask is not present on update, the operation applies to
* all fields (as if a field mask of all fields has been specified).
* Note that in the presence of schema evolution, this may mean that
* fields the client does not know and has therefore not filled into
* the request will be reset to their default. If this is unwanted
* behavior, a specific service may require a client to always specify
* a field mask, producing an error if not.
*
* As with get operations, the location of the resource which
* describes the updated values in the request message depends on the
* operation kind. In any case, the effect of the field mask is
* required to be honored by the API.
*
* ## Considerations for HTTP REST
*
* The HTTP kind of an update operation which uses a field mask must
* be set to PATCH instead of PUT in order to satisfy HTTP semantics
* (PUT must only be used for full updates).
*
* # JSON Encoding of Field Masks
*
* In JSON, a field mask is encoded as a single string where paths are
* separated by a comma. Fields name in each path are converted
* to/from lower-camel naming conventions.
*
* As an example, consider the following message declarations:
*
* message Profile {
* User user = 1;
* Photo photo = 2;
* }
* message User {
* string display_name = 1;
* string address = 2;
* }
*
* In proto a field mask for `Profile` may look as such:
*
* mask {
* paths: "user.display_name"
* paths: "photo"
* }
*
* In JSON, the same mask is represented as below:
*
* {
* mask: "user.displayName,photo"
* }
*
* # Field Masks and Oneof Fields
*
* Field masks treat fields in oneofs just as regular fields. Consider the
* following message:
*
* message SampleMessage {
* oneof test_oneof {
* string name = 4;
* SubMessage sub_message = 9;
* }
* }
*
* The field mask can be:
*
* mask {
* paths: "name"
* }
*
* Or:
*
* mask {
* paths: "sub_message"
* }
*
* Note that oneof type names ("test_oneof" in this case) cannot be used in
* paths.
*
* ## Field Mask Verification
*
* The implementation of any API method which has a FieldMask type field in the
* request should verify the included field paths, and return an
* `INVALID_ARGUMENT` error if any path is unmappable.
*
* @generated from message google.protobuf.FieldMask
*/
class FieldMask extends message_js_1.Message {
constructor(data) {
super();
/**
* The set of field mask paths.
*
* @generated from field: repeated string paths = 1;
*/
this.paths = [];
proto3_js_1.proto3.util.initPartial(data, this);
}
toJson(options) {
// Converts snake_case to protoCamelCase according to the convention
// used by protoc to convert a field name to a JSON name.
function protoCamelCase(snakeCase) {
let capNext = false;
const b = [];
for (let i = 0; i < snakeCase.length; i++) {
let c = snakeCase.charAt(i);
switch (c) {
case '_':
capNext = true;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
b.push(c);
capNext = false;
break;
default:
if (capNext) {
capNext = false;
c = c.toUpperCase();
}
b.push(c);
break;
}
}
return b.join('');
}
return this.paths.map(p => {
if (p.match(/_[0-9]?_/g) || p.match(/[A-Z]/g)) {
throw new Error("cannot encode google.protobuf.FieldMask to JSON: lowerCamelCase of path name \"" + p + "\" is irreversible");
}
return protoCamelCase(p);
}).join(",");
}
fromJson(json, options) {
if (typeof json !== "string") {
throw new Error("cannot decode google.protobuf.FieldMask from JSON: " + proto3_js_1.proto3.json.debug(json));
}
if (json === "") {
return this;
}
function camelToSnake(str) {
if (str.includes("_")) {
throw new Error("cannot decode google.protobuf.FieldMask from JSON: path names must be lowerCamelCase");
}
const sc = str.replace(/[A-Z]/g, letter => "_" + letter.toLowerCase());
return (sc[0] === "_") ? sc.substring(1) : sc;
}
this.paths = json.split(",").map(camelToSnake);
return this;
}
static fromBinary(bytes, options) {
return new FieldMask().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new FieldMask().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new FieldMask().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto3_js_1.proto3.util.equals(FieldMask, a, b);
}
}
exports.FieldMask = FieldMask;
FieldMask.runtime = proto3_js_1.proto3;
FieldMask.typeName = "google.protobuf.FieldMask";
FieldMask.fields = proto3_js_1.proto3.util.newFieldList(() => [
{ no: 1, name: "paths", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true },
]);
@@ -0,0 +1,29 @@
import type { PartialMessage, PlainMessage } from "../../message.js";
import { Message } from "../../message.js";
import { proto3 } from "../../proto3.js";
import type { FieldList } from "../../field-list.js";
import type { BinaryReadOptions } from "../../binary-format.js";
import type { JsonReadOptions, JsonValue } from "../../json-format.js";
/**
* `SourceContext` represents information about the source of a
* protobuf element, like the file in which it is defined.
*
* @generated from message google.protobuf.SourceContext
*/
export declare class SourceContext extends Message<SourceContext> {
/**
* The path-qualified name of the .proto file that contained the associated
* protobuf element. For example: `"google/protobuf/source_context.proto"`.
*
* @generated from field: string file_name = 1;
*/
fileName: string;
constructor(data?: PartialMessage<SourceContext>);
static readonly runtime: typeof proto3;
static readonly typeName = "google.protobuf.SourceContext";
static readonly fields: FieldList;
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): SourceContext;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): SourceContext;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): SourceContext;
static equals(a: SourceContext | PlainMessage<SourceContext> | undefined, b: SourceContext | PlainMessage<SourceContext> | undefined): boolean;
}
@@ -0,0 +1,55 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.SourceContext = void 0;
const message_js_1 = require("../../message.js");
const proto3_js_1 = require("../../proto3.js");
/**
* `SourceContext` represents information about the source of a
* protobuf element, like the file in which it is defined.
*
* @generated from message google.protobuf.SourceContext
*/
class SourceContext extends message_js_1.Message {
constructor(data) {
super();
/**
* The path-qualified name of the .proto file that contained the associated
* protobuf element. For example: `"google/protobuf/source_context.proto"`.
*
* @generated from field: string file_name = 1;
*/
this.fileName = "";
proto3_js_1.proto3.util.initPartial(data, this);
}
static fromBinary(bytes, options) {
return new SourceContext().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new SourceContext().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new SourceContext().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto3_js_1.proto3.util.equals(SourceContext, a, b);
}
}
exports.SourceContext = SourceContext;
SourceContext.runtime = proto3_js_1.proto3;
SourceContext.typeName = "google.protobuf.SourceContext";
SourceContext.fields = proto3_js_1.proto3.util.newFieldList(() => [
{ no: 1, name: "file_name", kind: "scalar", T: 9 /* ScalarType.STRING */ },
]);
+158
View File
@@ -0,0 +1,158 @@
import { proto3 } from "../../proto3.js";
import type { PartialMessage, PlainMessage } from "../../message.js";
import { Message } from "../../message.js";
import type { JsonReadOptions, JsonValue, JsonWriteOptions } from "../../json-format.js";
import type { FieldList } from "../../field-list.js";
import type { BinaryReadOptions } from "../../binary-format.js";
/**
* `NullValue` is a singleton enumeration to represent the null value for the
* `Value` type union.
*
* The JSON representation for `NullValue` is JSON `null`.
*
* @generated from enum google.protobuf.NullValue
*/
export declare enum NullValue {
/**
* Null value.
*
* @generated from enum value: NULL_VALUE = 0;
*/
NULL_VALUE = 0
}
/**
* `Struct` represents a structured data value, consisting of fields
* which map to dynamically typed values. In some languages, `Struct`
* might be supported by a native representation. For example, in
* scripting languages like JS a struct is represented as an
* object. The details of that representation are described together
* with the proto support for the language.
*
* The JSON representation for `Struct` is JSON object.
*
* @generated from message google.protobuf.Struct
*/
export declare class Struct extends Message<Struct> {
/**
* Unordered map of dynamically typed values.
*
* @generated from field: map<string, google.protobuf.Value> fields = 1;
*/
fields: {
[key: string]: Value;
};
constructor(data?: PartialMessage<Struct>);
toJson(options?: Partial<JsonWriteOptions>): JsonValue;
fromJson(json: JsonValue, options?: Partial<JsonReadOptions>): this;
static readonly runtime: typeof proto3;
static readonly typeName = "google.protobuf.Struct";
static readonly fields: FieldList;
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): Struct;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): Struct;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): Struct;
static equals(a: Struct | PlainMessage<Struct> | undefined, b: Struct | PlainMessage<Struct> | undefined): boolean;
}
/**
* `Value` represents a dynamically typed value which can be either
* null, a number, a string, a boolean, a recursive struct value, or a
* list of values. A producer of value is expected to set one of these
* variants. Absence of any variant indicates an error.
*
* The JSON representation for `Value` is JSON value.
*
* @generated from message google.protobuf.Value
*/
export declare class Value extends Message<Value> {
/**
* The kind of value.
*
* @generated from oneof google.protobuf.Value.kind
*/
kind: {
/**
* Represents a null value.
*
* @generated from field: google.protobuf.NullValue null_value = 1;
*/
value: NullValue;
case: "nullValue";
} | {
/**
* Represents a double value.
*
* @generated from field: double number_value = 2;
*/
value: number;
case: "numberValue";
} | {
/**
* Represents a string value.
*
* @generated from field: string string_value = 3;
*/
value: string;
case: "stringValue";
} | {
/**
* Represents a boolean value.
*
* @generated from field: bool bool_value = 4;
*/
value: boolean;
case: "boolValue";
} | {
/**
* Represents a structured value.
*
* @generated from field: google.protobuf.Struct struct_value = 5;
*/
value: Struct;
case: "structValue";
} | {
/**
* Represents a repeated `Value`.
*
* @generated from field: google.protobuf.ListValue list_value = 6;
*/
value: ListValue;
case: "listValue";
} | {
case: undefined;
value?: undefined;
};
constructor(data?: PartialMessage<Value>);
toJson(options?: Partial<JsonWriteOptions>): JsonValue;
fromJson(json: JsonValue, options?: Partial<JsonReadOptions>): this;
static readonly runtime: typeof proto3;
static readonly typeName = "google.protobuf.Value";
static readonly fields: FieldList;
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): Value;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): Value;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): Value;
static equals(a: Value | PlainMessage<Value> | undefined, b: Value | PlainMessage<Value> | undefined): boolean;
}
/**
* `ListValue` is a wrapper around a repeated field of values.
*
* The JSON representation for `ListValue` is JSON array.
*
* @generated from message google.protobuf.ListValue
*/
export declare class ListValue extends Message<ListValue> {
/**
* Repeated field of dynamically typed values.
*
* @generated from field: repeated google.protobuf.Value values = 1;
*/
values: Value[];
constructor(data?: PartialMessage<ListValue>);
toJson(options?: Partial<JsonWriteOptions>): JsonValue;
fromJson(json: JsonValue, options?: Partial<JsonReadOptions>): this;
static readonly runtime: typeof proto3;
static readonly typeName = "google.protobuf.ListValue";
static readonly fields: FieldList;
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): ListValue;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): ListValue;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): ListValue;
static equals(a: ListValue | PlainMessage<ListValue> | undefined, b: ListValue | PlainMessage<ListValue> | undefined): boolean;
}
+240
View File
@@ -0,0 +1,240 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ListValue = exports.Value = exports.Struct = exports.NullValue = void 0;
// @generated by protoc-gen-es v1.10.1 with parameter "bootstrap_wkt=true,ts_nocheck=false,target=ts"
// @generated from file google/protobuf/struct.proto (package google.protobuf, syntax proto3)
/* eslint-disable */
const proto3_js_1 = require("../../proto3.js");
const message_js_1 = require("../../message.js");
/**
* `NullValue` is a singleton enumeration to represent the null value for the
* `Value` type union.
*
* The JSON representation for `NullValue` is JSON `null`.
*
* @generated from enum google.protobuf.NullValue
*/
var NullValue;
(function (NullValue) {
/**
* Null value.
*
* @generated from enum value: NULL_VALUE = 0;
*/
NullValue[NullValue["NULL_VALUE"] = 0] = "NULL_VALUE";
})(NullValue || (exports.NullValue = NullValue = {}));
// Retrieve enum metadata with: proto3.getEnumType(NullValue)
proto3_js_1.proto3.util.setEnumType(NullValue, "google.protobuf.NullValue", [
{ no: 0, name: "NULL_VALUE" },
]);
/**
* `Struct` represents a structured data value, consisting of fields
* which map to dynamically typed values. In some languages, `Struct`
* might be supported by a native representation. For example, in
* scripting languages like JS a struct is represented as an
* object. The details of that representation are described together
* with the proto support for the language.
*
* The JSON representation for `Struct` is JSON object.
*
* @generated from message google.protobuf.Struct
*/
class Struct extends message_js_1.Message {
constructor(data) {
super();
/**
* Unordered map of dynamically typed values.
*
* @generated from field: map<string, google.protobuf.Value> fields = 1;
*/
this.fields = {};
proto3_js_1.proto3.util.initPartial(data, this);
}
toJson(options) {
const json = {};
for (const [k, v] of Object.entries(this.fields)) {
json[k] = v.toJson(options);
}
return json;
}
fromJson(json, options) {
if (typeof json != "object" || json == null || Array.isArray(json)) {
throw new Error("cannot decode google.protobuf.Struct from JSON " + proto3_js_1.proto3.json.debug(json));
}
for (const [k, v] of Object.entries(json)) {
this.fields[k] = Value.fromJson(v);
}
return this;
}
static fromBinary(bytes, options) {
return new Struct().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new Struct().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new Struct().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto3_js_1.proto3.util.equals(Struct, a, b);
}
}
exports.Struct = Struct;
Struct.runtime = proto3_js_1.proto3;
Struct.typeName = "google.protobuf.Struct";
Struct.fields = proto3_js_1.proto3.util.newFieldList(() => [
{ no: 1, name: "fields", kind: "map", K: 9 /* ScalarType.STRING */, V: { kind: "message", T: Value } },
]);
/**
* `Value` represents a dynamically typed value which can be either
* null, a number, a string, a boolean, a recursive struct value, or a
* list of values. A producer of value is expected to set one of these
* variants. Absence of any variant indicates an error.
*
* The JSON representation for `Value` is JSON value.
*
* @generated from message google.protobuf.Value
*/
class Value extends message_js_1.Message {
constructor(data) {
super();
/**
* The kind of value.
*
* @generated from oneof google.protobuf.Value.kind
*/
this.kind = { case: undefined };
proto3_js_1.proto3.util.initPartial(data, this);
}
toJson(options) {
switch (this.kind.case) {
case "nullValue":
return null;
case "numberValue":
if (!Number.isFinite(this.kind.value)) {
throw new Error("google.protobuf.Value cannot be NaN or Infinity");
}
return this.kind.value;
case "boolValue":
return this.kind.value;
case "stringValue":
return this.kind.value;
case "structValue":
case "listValue":
return this.kind.value.toJson(Object.assign(Object.assign({}, options), { emitDefaultValues: true }));
}
throw new Error("google.protobuf.Value must have a value");
}
fromJson(json, options) {
switch (typeof json) {
case "number":
this.kind = { case: "numberValue", value: json };
break;
case "string":
this.kind = { case: "stringValue", value: json };
break;
case "boolean":
this.kind = { case: "boolValue", value: json };
break;
case "object":
if (json === null) {
this.kind = { case: "nullValue", value: NullValue.NULL_VALUE };
}
else if (Array.isArray(json)) {
this.kind = { case: "listValue", value: ListValue.fromJson(json) };
}
else {
this.kind = { case: "structValue", value: Struct.fromJson(json) };
}
break;
default:
throw new Error("cannot decode google.protobuf.Value from JSON " + proto3_js_1.proto3.json.debug(json));
}
return this;
}
static fromBinary(bytes, options) {
return new Value().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new Value().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new Value().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto3_js_1.proto3.util.equals(Value, a, b);
}
}
exports.Value = Value;
Value.runtime = proto3_js_1.proto3;
Value.typeName = "google.protobuf.Value";
Value.fields = proto3_js_1.proto3.util.newFieldList(() => [
{ no: 1, name: "null_value", kind: "enum", T: proto3_js_1.proto3.getEnumType(NullValue), oneof: "kind" },
{ no: 2, name: "number_value", kind: "scalar", T: 1 /* ScalarType.DOUBLE */, oneof: "kind" },
{ no: 3, name: "string_value", kind: "scalar", T: 9 /* ScalarType.STRING */, oneof: "kind" },
{ no: 4, name: "bool_value", kind: "scalar", T: 8 /* ScalarType.BOOL */, oneof: "kind" },
{ no: 5, name: "struct_value", kind: "message", T: Struct, oneof: "kind" },
{ no: 6, name: "list_value", kind: "message", T: ListValue, oneof: "kind" },
]);
/**
* `ListValue` is a wrapper around a repeated field of values.
*
* The JSON representation for `ListValue` is JSON array.
*
* @generated from message google.protobuf.ListValue
*/
class ListValue extends message_js_1.Message {
constructor(data) {
super();
/**
* Repeated field of dynamically typed values.
*
* @generated from field: repeated google.protobuf.Value values = 1;
*/
this.values = [];
proto3_js_1.proto3.util.initPartial(data, this);
}
toJson(options) {
return this.values.map(v => v.toJson());
}
fromJson(json, options) {
if (!Array.isArray(json)) {
throw new Error("cannot decode google.protobuf.ListValue from JSON " + proto3_js_1.proto3.json.debug(json));
}
for (let e of json) {
this.values.push(Value.fromJson(e));
}
return this;
}
static fromBinary(bytes, options) {
return new ListValue().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new ListValue().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new ListValue().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto3_js_1.proto3.util.equals(ListValue, a, b);
}
}
exports.ListValue = ListValue;
ListValue.runtime = proto3_js_1.proto3;
ListValue.typeName = "google.protobuf.ListValue";
ListValue.fields = proto3_js_1.proto3.util.newFieldList(() => [
{ no: 1, name: "values", kind: "message", T: Value, repeated: true },
]);
@@ -0,0 +1,132 @@
import type { PartialMessage, PlainMessage } from "../../message.js";
import { Message } from "../../message.js";
import { proto3 } from "../../proto3.js";
import type { JsonReadOptions, JsonValue, JsonWriteOptions } from "../../json-format.js";
import type { FieldList } from "../../field-list.js";
import type { BinaryReadOptions } from "../../binary-format.js";
/**
* A Timestamp represents a point in time independent of any time zone or local
* calendar, encoded as a count of seconds and fractions of seconds at
* nanosecond resolution. The count is relative to an epoch at UTC midnight on
* January 1, 1970, in the proleptic Gregorian calendar which extends the
* Gregorian calendar backwards to year one.
*
* All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap
* second table is needed for interpretation, using a [24-hour linear
* smear](https://developers.google.com/time/smear).
*
* The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By
* restricting to that range, we ensure that we can convert to and from [RFC
* 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings.
*
* # Examples
*
* Example 1: Compute Timestamp from POSIX `time()`.
*
* Timestamp timestamp;
* timestamp.set_seconds(time(NULL));
* timestamp.set_nanos(0);
*
* Example 2: Compute Timestamp from POSIX `gettimeofday()`.
*
* struct timeval tv;
* gettimeofday(&tv, NULL);
*
* Timestamp timestamp;
* timestamp.set_seconds(tv.tv_sec);
* timestamp.set_nanos(tv.tv_usec * 1000);
*
* Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
*
* FILETIME ft;
* GetSystemTimeAsFileTime(&ft);
* UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
*
* // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
* // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
* Timestamp timestamp;
* timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
* timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
*
* Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
*
* long millis = System.currentTimeMillis();
*
* Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
* .setNanos((int) ((millis % 1000) * 1000000)).build();
*
* Example 5: Compute Timestamp from Java `Instant.now()`.
*
* Instant now = Instant.now();
*
* Timestamp timestamp =
* Timestamp.newBuilder().setSeconds(now.getEpochSecond())
* .setNanos(now.getNano()).build();
*
* Example 6: Compute Timestamp from current time in Python.
*
* timestamp = Timestamp()
* timestamp.GetCurrentTime()
*
* # JSON Mapping
*
* In JSON format, the Timestamp type is encoded as a string in the
* [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
* format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
* where {year} is always expressed using four digits while {month}, {day},
* {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
* seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
* are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
* is required. A proto3 JSON serializer should always use UTC (as indicated by
* "Z") when printing the Timestamp type and a proto3 JSON parser should be
* able to accept both UTC and other timezones (as indicated by an offset).
*
* For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
* 01:30 UTC on January 15, 2017.
*
* In JavaScript, one can convert a Date object to this format using the
* standard
* [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)
* method. In Python, a standard `datetime.datetime` object can be converted
* to this format using
* [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with
* the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use
* the Joda Time's [`ISODateTimeFormat.dateTime()`](
* http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime()
* ) to obtain a formatter capable of generating timestamps in this format.
*
*
* @generated from message google.protobuf.Timestamp
*/
export declare class Timestamp extends Message<Timestamp> {
/**
* Represents seconds of UTC time since Unix epoch
* 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
* 9999-12-31T23:59:59Z inclusive.
*
* @generated from field: int64 seconds = 1;
*/
seconds: bigint;
/**
* Non-negative fractions of a second at nanosecond resolution. Negative
* second values with fractions must still have non-negative nanos values
* that count forward in time. Must be from 0 to 999,999,999
* inclusive.
*
* @generated from field: int32 nanos = 2;
*/
nanos: number;
constructor(data?: PartialMessage<Timestamp>);
fromJson(json: JsonValue, options?: Partial<JsonReadOptions>): this;
toJson(options?: Partial<JsonWriteOptions>): JsonValue;
toDate(): Date;
static readonly runtime: typeof proto3;
static readonly typeName = "google.protobuf.Timestamp";
static readonly fields: FieldList;
static now(): Timestamp;
static fromDate(date: Date): Timestamp;
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): Timestamp;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): Timestamp;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): Timestamp;
static equals(a: Timestamp | PlainMessage<Timestamp> | undefined, b: Timestamp | PlainMessage<Timestamp> | undefined): boolean;
}
@@ -0,0 +1,213 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.Timestamp = void 0;
const message_js_1 = require("../../message.js");
const proto_int64_js_1 = require("../../proto-int64.js");
const proto3_js_1 = require("../../proto3.js");
/**
* A Timestamp represents a point in time independent of any time zone or local
* calendar, encoded as a count of seconds and fractions of seconds at
* nanosecond resolution. The count is relative to an epoch at UTC midnight on
* January 1, 1970, in the proleptic Gregorian calendar which extends the
* Gregorian calendar backwards to year one.
*
* All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap
* second table is needed for interpretation, using a [24-hour linear
* smear](https://developers.google.com/time/smear).
*
* The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By
* restricting to that range, we ensure that we can convert to and from [RFC
* 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings.
*
* # Examples
*
* Example 1: Compute Timestamp from POSIX `time()`.
*
* Timestamp timestamp;
* timestamp.set_seconds(time(NULL));
* timestamp.set_nanos(0);
*
* Example 2: Compute Timestamp from POSIX `gettimeofday()`.
*
* struct timeval tv;
* gettimeofday(&tv, NULL);
*
* Timestamp timestamp;
* timestamp.set_seconds(tv.tv_sec);
* timestamp.set_nanos(tv.tv_usec * 1000);
*
* Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
*
* FILETIME ft;
* GetSystemTimeAsFileTime(&ft);
* UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
*
* // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
* // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
* Timestamp timestamp;
* timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
* timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
*
* Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
*
* long millis = System.currentTimeMillis();
*
* Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
* .setNanos((int) ((millis % 1000) * 1000000)).build();
*
* Example 5: Compute Timestamp from Java `Instant.now()`.
*
* Instant now = Instant.now();
*
* Timestamp timestamp =
* Timestamp.newBuilder().setSeconds(now.getEpochSecond())
* .setNanos(now.getNano()).build();
*
* Example 6: Compute Timestamp from current time in Python.
*
* timestamp = Timestamp()
* timestamp.GetCurrentTime()
*
* # JSON Mapping
*
* In JSON format, the Timestamp type is encoded as a string in the
* [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
* format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
* where {year} is always expressed using four digits while {month}, {day},
* {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
* seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
* are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
* is required. A proto3 JSON serializer should always use UTC (as indicated by
* "Z") when printing the Timestamp type and a proto3 JSON parser should be
* able to accept both UTC and other timezones (as indicated by an offset).
*
* For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
* 01:30 UTC on January 15, 2017.
*
* In JavaScript, one can convert a Date object to this format using the
* standard
* [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)
* method. In Python, a standard `datetime.datetime` object can be converted
* to this format using
* [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with
* the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use
* the Joda Time's [`ISODateTimeFormat.dateTime()`](
* http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime()
* ) to obtain a formatter capable of generating timestamps in this format.
*
*
* @generated from message google.protobuf.Timestamp
*/
class Timestamp extends message_js_1.Message {
constructor(data) {
super();
/**
* Represents seconds of UTC time since Unix epoch
* 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
* 9999-12-31T23:59:59Z inclusive.
*
* @generated from field: int64 seconds = 1;
*/
this.seconds = proto_int64_js_1.protoInt64.zero;
/**
* Non-negative fractions of a second at nanosecond resolution. Negative
* second values with fractions must still have non-negative nanos values
* that count forward in time. Must be from 0 to 999,999,999
* inclusive.
*
* @generated from field: int32 nanos = 2;
*/
this.nanos = 0;
proto3_js_1.proto3.util.initPartial(data, this);
}
fromJson(json, options) {
if (typeof json !== "string") {
throw new Error(`cannot decode google.protobuf.Timestamp from JSON: ${proto3_js_1.proto3.json.debug(json)}`);
}
const matches = json.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);
if (!matches) {
throw new Error(`cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string`);
}
const ms = Date.parse(matches[1] + "-" + matches[2] + "-" + matches[3] + "T" + matches[4] + ":" + matches[5] + ":" + matches[6] + (matches[8] ? matches[8] : "Z"));
if (Number.isNaN(ms)) {
throw new Error(`cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string`);
}
if (ms < Date.parse("0001-01-01T00:00:00Z") || ms > Date.parse("9999-12-31T23:59:59Z")) {
throw new Error(`cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive`);
}
this.seconds = proto_int64_js_1.protoInt64.parse(ms / 1000);
this.nanos = 0;
if (matches[7]) {
this.nanos = (parseInt("1" + matches[7] + "0".repeat(9 - matches[7].length)) - 1000000000);
}
return this;
}
toJson(options) {
const ms = Number(this.seconds) * 1000;
if (ms < Date.parse("0001-01-01T00:00:00Z") || ms > Date.parse("9999-12-31T23:59:59Z")) {
throw new Error(`cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive`);
}
if (this.nanos < 0) {
throw new Error(`cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative`);
}
let z = "Z";
if (this.nanos > 0) {
const nanosStr = (this.nanos + 1000000000).toString().substring(1);
if (nanosStr.substring(3) === "000000") {
z = "." + nanosStr.substring(0, 3) + "Z";
}
else if (nanosStr.substring(6) === "000") {
z = "." + nanosStr.substring(0, 6) + "Z";
}
else {
z = "." + nanosStr + "Z";
}
}
return new Date(ms).toISOString().replace(".000Z", z);
}
toDate() {
return new Date(Number(this.seconds) * 1000 + Math.ceil(this.nanos / 1000000));
}
static now() {
return Timestamp.fromDate(new Date());
}
static fromDate(date) {
const ms = date.getTime();
return new Timestamp({
seconds: proto_int64_js_1.protoInt64.parse(Math.floor(ms / 1000)),
nanos: (ms % 1000) * 1000000,
});
}
static fromBinary(bytes, options) {
return new Timestamp().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new Timestamp().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new Timestamp().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto3_js_1.proto3.util.equals(Timestamp, a, b);
}
}
exports.Timestamp = Timestamp;
Timestamp.runtime = proto3_js_1.proto3;
Timestamp.typeName = "google.protobuf.Timestamp";
Timestamp.fields = proto3_js_1.proto3.util.newFieldList(() => [
{ no: 1, name: "seconds", kind: "scalar", T: 3 /* ScalarType.INT64 */ },
{ no: 2, name: "nanos", kind: "scalar", T: 5 /* ScalarType.INT32 */ },
]);
+437
View File
@@ -0,0 +1,437 @@
import { proto3 } from "../../proto3.js";
import type { PartialMessage, PlainMessage } from "../../message.js";
import { Message } from "../../message.js";
import { SourceContext } from "./source_context_pb.js";
import type { FieldList } from "../../field-list.js";
import type { BinaryReadOptions } from "../../binary-format.js";
import type { JsonReadOptions, JsonValue } from "../../json-format.js";
import { Any } from "./any_pb.js";
/**
* The syntax in which a protocol buffer element is defined.
*
* @generated from enum google.protobuf.Syntax
*/
export declare enum Syntax {
/**
* Syntax `proto2`.
*
* @generated from enum value: SYNTAX_PROTO2 = 0;
*/
PROTO2 = 0,
/**
* Syntax `proto3`.
*
* @generated from enum value: SYNTAX_PROTO3 = 1;
*/
PROTO3 = 1,
/**
* Syntax `editions`.
*
* @generated from enum value: SYNTAX_EDITIONS = 2;
*/
EDITIONS = 2
}
/**
* A protocol buffer message type.
*
* @generated from message google.protobuf.Type
*/
export declare class Type extends Message<Type> {
/**
* The fully qualified message name.
*
* @generated from field: string name = 1;
*/
name: string;
/**
* The list of fields.
*
* @generated from field: repeated google.protobuf.Field fields = 2;
*/
fields: Field[];
/**
* The list of types appearing in `oneof` definitions in this type.
*
* @generated from field: repeated string oneofs = 3;
*/
oneofs: string[];
/**
* The protocol buffer options.
*
* @generated from field: repeated google.protobuf.Option options = 4;
*/
options: Option[];
/**
* The source context.
*
* @generated from field: google.protobuf.SourceContext source_context = 5;
*/
sourceContext?: SourceContext;
/**
* The source syntax.
*
* @generated from field: google.protobuf.Syntax syntax = 6;
*/
syntax: Syntax;
/**
* The source edition string, only valid when syntax is SYNTAX_EDITIONS.
*
* @generated from field: string edition = 7;
*/
edition: string;
constructor(data?: PartialMessage<Type>);
static readonly runtime: typeof proto3;
static readonly typeName = "google.protobuf.Type";
static readonly fields: FieldList;
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): Type;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): Type;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): Type;
static equals(a: Type | PlainMessage<Type> | undefined, b: Type | PlainMessage<Type> | undefined): boolean;
}
/**
* A single field of a message type.
*
* @generated from message google.protobuf.Field
*/
export declare class Field extends Message<Field> {
/**
* The field type.
*
* @generated from field: google.protobuf.Field.Kind kind = 1;
*/
kind: Field_Kind;
/**
* The field cardinality.
*
* @generated from field: google.protobuf.Field.Cardinality cardinality = 2;
*/
cardinality: Field_Cardinality;
/**
* The field number.
*
* @generated from field: int32 number = 3;
*/
number: number;
/**
* The field name.
*
* @generated from field: string name = 4;
*/
name: string;
/**
* The field type URL, without the scheme, for message or enumeration
* types. Example: `"type.googleapis.com/google.protobuf.Timestamp"`.
*
* @generated from field: string type_url = 6;
*/
typeUrl: string;
/**
* The index of the field type in `Type.oneofs`, for message or enumeration
* types. The first type has index 1; zero means the type is not in the list.
*
* @generated from field: int32 oneof_index = 7;
*/
oneofIndex: number;
/**
* Whether to use alternative packed wire representation.
*
* @generated from field: bool packed = 8;
*/
packed: boolean;
/**
* The protocol buffer options.
*
* @generated from field: repeated google.protobuf.Option options = 9;
*/
options: Option[];
/**
* The field JSON name.
*
* @generated from field: string json_name = 10;
*/
jsonName: string;
/**
* The string value of the default value of this field. Proto2 syntax only.
*
* @generated from field: string default_value = 11;
*/
defaultValue: string;
constructor(data?: PartialMessage<Field>);
static readonly runtime: typeof proto3;
static readonly typeName = "google.protobuf.Field";
static readonly fields: FieldList;
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): Field;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): Field;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): Field;
static equals(a: Field | PlainMessage<Field> | undefined, b: Field | PlainMessage<Field> | undefined): boolean;
}
/**
* Basic field types.
*
* @generated from enum google.protobuf.Field.Kind
*/
export declare enum Field_Kind {
/**
* Field type unknown.
*
* @generated from enum value: TYPE_UNKNOWN = 0;
*/
TYPE_UNKNOWN = 0,
/**
* Field type double.
*
* @generated from enum value: TYPE_DOUBLE = 1;
*/
TYPE_DOUBLE = 1,
/**
* Field type float.
*
* @generated from enum value: TYPE_FLOAT = 2;
*/
TYPE_FLOAT = 2,
/**
* Field type int64.
*
* @generated from enum value: TYPE_INT64 = 3;
*/
TYPE_INT64 = 3,
/**
* Field type uint64.
*
* @generated from enum value: TYPE_UINT64 = 4;
*/
TYPE_UINT64 = 4,
/**
* Field type int32.
*
* @generated from enum value: TYPE_INT32 = 5;
*/
TYPE_INT32 = 5,
/**
* Field type fixed64.
*
* @generated from enum value: TYPE_FIXED64 = 6;
*/
TYPE_FIXED64 = 6,
/**
* Field type fixed32.
*
* @generated from enum value: TYPE_FIXED32 = 7;
*/
TYPE_FIXED32 = 7,
/**
* Field type bool.
*
* @generated from enum value: TYPE_BOOL = 8;
*/
TYPE_BOOL = 8,
/**
* Field type string.
*
* @generated from enum value: TYPE_STRING = 9;
*/
TYPE_STRING = 9,
/**
* Field type group. Proto2 syntax only, and deprecated.
*
* @generated from enum value: TYPE_GROUP = 10;
*/
TYPE_GROUP = 10,
/**
* Field type message.
*
* @generated from enum value: TYPE_MESSAGE = 11;
*/
TYPE_MESSAGE = 11,
/**
* Field type bytes.
*
* @generated from enum value: TYPE_BYTES = 12;
*/
TYPE_BYTES = 12,
/**
* Field type uint32.
*
* @generated from enum value: TYPE_UINT32 = 13;
*/
TYPE_UINT32 = 13,
/**
* Field type enum.
*
* @generated from enum value: TYPE_ENUM = 14;
*/
TYPE_ENUM = 14,
/**
* Field type sfixed32.
*
* @generated from enum value: TYPE_SFIXED32 = 15;
*/
TYPE_SFIXED32 = 15,
/**
* Field type sfixed64.
*
* @generated from enum value: TYPE_SFIXED64 = 16;
*/
TYPE_SFIXED64 = 16,
/**
* Field type sint32.
*
* @generated from enum value: TYPE_SINT32 = 17;
*/
TYPE_SINT32 = 17,
/**
* Field type sint64.
*
* @generated from enum value: TYPE_SINT64 = 18;
*/
TYPE_SINT64 = 18
}
/**
* Whether a field is optional, required, or repeated.
*
* @generated from enum google.protobuf.Field.Cardinality
*/
export declare enum Field_Cardinality {
/**
* For fields with unknown cardinality.
*
* @generated from enum value: CARDINALITY_UNKNOWN = 0;
*/
UNKNOWN = 0,
/**
* For optional fields.
*
* @generated from enum value: CARDINALITY_OPTIONAL = 1;
*/
OPTIONAL = 1,
/**
* For required fields. Proto2 syntax only.
*
* @generated from enum value: CARDINALITY_REQUIRED = 2;
*/
REQUIRED = 2,
/**
* For repeated fields.
*
* @generated from enum value: CARDINALITY_REPEATED = 3;
*/
REPEATED = 3
}
/**
* Enum type definition.
*
* @generated from message google.protobuf.Enum
*/
export declare class Enum extends Message<Enum> {
/**
* Enum type name.
*
* @generated from field: string name = 1;
*/
name: string;
/**
* Enum value definitions.
*
* @generated from field: repeated google.protobuf.EnumValue enumvalue = 2;
*/
enumvalue: EnumValue[];
/**
* Protocol buffer options.
*
* @generated from field: repeated google.protobuf.Option options = 3;
*/
options: Option[];
/**
* The source context.
*
* @generated from field: google.protobuf.SourceContext source_context = 4;
*/
sourceContext?: SourceContext;
/**
* The source syntax.
*
* @generated from field: google.protobuf.Syntax syntax = 5;
*/
syntax: Syntax;
/**
* The source edition string, only valid when syntax is SYNTAX_EDITIONS.
*
* @generated from field: string edition = 6;
*/
edition: string;
constructor(data?: PartialMessage<Enum>);
static readonly runtime: typeof proto3;
static readonly typeName = "google.protobuf.Enum";
static readonly fields: FieldList;
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): Enum;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): Enum;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): Enum;
static equals(a: Enum | PlainMessage<Enum> | undefined, b: Enum | PlainMessage<Enum> | undefined): boolean;
}
/**
* Enum value definition.
*
* @generated from message google.protobuf.EnumValue
*/
export declare class EnumValue extends Message<EnumValue> {
/**
* Enum value name.
*
* @generated from field: string name = 1;
*/
name: string;
/**
* Enum value number.
*
* @generated from field: int32 number = 2;
*/
number: number;
/**
* Protocol buffer options.
*
* @generated from field: repeated google.protobuf.Option options = 3;
*/
options: Option[];
constructor(data?: PartialMessage<EnumValue>);
static readonly runtime: typeof proto3;
static readonly typeName = "google.protobuf.EnumValue";
static readonly fields: FieldList;
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): EnumValue;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): EnumValue;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): EnumValue;
static equals(a: EnumValue | PlainMessage<EnumValue> | undefined, b: EnumValue | PlainMessage<EnumValue> | undefined): boolean;
}
/**
* A protocol buffer option, which can be attached to a message, field,
* enumeration, etc.
*
* @generated from message google.protobuf.Option
*/
export declare class Option extends Message<Option> {
/**
* The option's name. For protobuf built-in options (options defined in
* descriptor.proto), this is the short name. For example, `"map_entry"`.
* For custom options, it should be the fully-qualified name. For example,
* `"google.api.http"`.
*
* @generated from field: string name = 1;
*/
name: string;
/**
* The option's value packed in an Any message. If the value is a primitive,
* the corresponding wrapper type defined in google/protobuf/wrappers.proto
* should be used. If the value is an enum, it should be stored as an int32
* value using the google.protobuf.Int32Value type.
*
* @generated from field: google.protobuf.Any value = 2;
*/
value?: Any;
constructor(data?: PartialMessage<Option>);
static readonly runtime: typeof proto3;
static readonly typeName = "google.protobuf.Option";
static readonly fields: FieldList;
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): Option;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): Option;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): Option;
static equals(a: Option | PlainMessage<Option> | undefined, b: Option | PlainMessage<Option> | undefined): boolean;
}
+562
View File
@@ -0,0 +1,562 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.Option = exports.EnumValue = exports.Enum = exports.Field_Cardinality = exports.Field_Kind = exports.Field = exports.Type = exports.Syntax = void 0;
// @generated by protoc-gen-es v1.10.1 with parameter "bootstrap_wkt=true,ts_nocheck=false,target=ts"
// @generated from file google/protobuf/type.proto (package google.protobuf, syntax proto3)
/* eslint-disable */
const proto3_js_1 = require("../../proto3.js");
const message_js_1 = require("../../message.js");
const source_context_pb_js_1 = require("./source_context_pb.js");
const any_pb_js_1 = require("./any_pb.js");
/**
* The syntax in which a protocol buffer element is defined.
*
* @generated from enum google.protobuf.Syntax
*/
var Syntax;
(function (Syntax) {
/**
* Syntax `proto2`.
*
* @generated from enum value: SYNTAX_PROTO2 = 0;
*/
Syntax[Syntax["PROTO2"] = 0] = "PROTO2";
/**
* Syntax `proto3`.
*
* @generated from enum value: SYNTAX_PROTO3 = 1;
*/
Syntax[Syntax["PROTO3"] = 1] = "PROTO3";
/**
* Syntax `editions`.
*
* @generated from enum value: SYNTAX_EDITIONS = 2;
*/
Syntax[Syntax["EDITIONS"] = 2] = "EDITIONS";
})(Syntax || (exports.Syntax = Syntax = {}));
// Retrieve enum metadata with: proto3.getEnumType(Syntax)
proto3_js_1.proto3.util.setEnumType(Syntax, "google.protobuf.Syntax", [
{ no: 0, name: "SYNTAX_PROTO2" },
{ no: 1, name: "SYNTAX_PROTO3" },
{ no: 2, name: "SYNTAX_EDITIONS" },
]);
/**
* A protocol buffer message type.
*
* @generated from message google.protobuf.Type
*/
class Type extends message_js_1.Message {
constructor(data) {
super();
/**
* The fully qualified message name.
*
* @generated from field: string name = 1;
*/
this.name = "";
/**
* The list of fields.
*
* @generated from field: repeated google.protobuf.Field fields = 2;
*/
this.fields = [];
/**
* The list of types appearing in `oneof` definitions in this type.
*
* @generated from field: repeated string oneofs = 3;
*/
this.oneofs = [];
/**
* The protocol buffer options.
*
* @generated from field: repeated google.protobuf.Option options = 4;
*/
this.options = [];
/**
* The source syntax.
*
* @generated from field: google.protobuf.Syntax syntax = 6;
*/
this.syntax = Syntax.PROTO2;
/**
* The source edition string, only valid when syntax is SYNTAX_EDITIONS.
*
* @generated from field: string edition = 7;
*/
this.edition = "";
proto3_js_1.proto3.util.initPartial(data, this);
}
static fromBinary(bytes, options) {
return new Type().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new Type().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new Type().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto3_js_1.proto3.util.equals(Type, a, b);
}
}
exports.Type = Type;
Type.runtime = proto3_js_1.proto3;
Type.typeName = "google.protobuf.Type";
Type.fields = proto3_js_1.proto3.util.newFieldList(() => [
{ no: 1, name: "name", kind: "scalar", T: 9 /* ScalarType.STRING */ },
{ no: 2, name: "fields", kind: "message", T: Field, repeated: true },
{ no: 3, name: "oneofs", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true },
{ no: 4, name: "options", kind: "message", T: Option, repeated: true },
{ no: 5, name: "source_context", kind: "message", T: source_context_pb_js_1.SourceContext },
{ no: 6, name: "syntax", kind: "enum", T: proto3_js_1.proto3.getEnumType(Syntax) },
{ no: 7, name: "edition", kind: "scalar", T: 9 /* ScalarType.STRING */ },
]);
/**
* A single field of a message type.
*
* @generated from message google.protobuf.Field
*/
class Field extends message_js_1.Message {
constructor(data) {
super();
/**
* The field type.
*
* @generated from field: google.protobuf.Field.Kind kind = 1;
*/
this.kind = Field_Kind.TYPE_UNKNOWN;
/**
* The field cardinality.
*
* @generated from field: google.protobuf.Field.Cardinality cardinality = 2;
*/
this.cardinality = Field_Cardinality.UNKNOWN;
/**
* The field number.
*
* @generated from field: int32 number = 3;
*/
this.number = 0;
/**
* The field name.
*
* @generated from field: string name = 4;
*/
this.name = "";
/**
* The field type URL, without the scheme, for message or enumeration
* types. Example: `"type.googleapis.com/google.protobuf.Timestamp"`.
*
* @generated from field: string type_url = 6;
*/
this.typeUrl = "";
/**
* The index of the field type in `Type.oneofs`, for message or enumeration
* types. The first type has index 1; zero means the type is not in the list.
*
* @generated from field: int32 oneof_index = 7;
*/
this.oneofIndex = 0;
/**
* Whether to use alternative packed wire representation.
*
* @generated from field: bool packed = 8;
*/
this.packed = false;
/**
* The protocol buffer options.
*
* @generated from field: repeated google.protobuf.Option options = 9;
*/
this.options = [];
/**
* The field JSON name.
*
* @generated from field: string json_name = 10;
*/
this.jsonName = "";
/**
* The string value of the default value of this field. Proto2 syntax only.
*
* @generated from field: string default_value = 11;
*/
this.defaultValue = "";
proto3_js_1.proto3.util.initPartial(data, this);
}
static fromBinary(bytes, options) {
return new Field().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new Field().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new Field().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto3_js_1.proto3.util.equals(Field, a, b);
}
}
exports.Field = Field;
Field.runtime = proto3_js_1.proto3;
Field.typeName = "google.protobuf.Field";
Field.fields = proto3_js_1.proto3.util.newFieldList(() => [
{ no: 1, name: "kind", kind: "enum", T: proto3_js_1.proto3.getEnumType(Field_Kind) },
{ no: 2, name: "cardinality", kind: "enum", T: proto3_js_1.proto3.getEnumType(Field_Cardinality) },
{ no: 3, name: "number", kind: "scalar", T: 5 /* ScalarType.INT32 */ },
{ no: 4, name: "name", kind: "scalar", T: 9 /* ScalarType.STRING */ },
{ no: 6, name: "type_url", kind: "scalar", T: 9 /* ScalarType.STRING */ },
{ no: 7, name: "oneof_index", kind: "scalar", T: 5 /* ScalarType.INT32 */ },
{ no: 8, name: "packed", kind: "scalar", T: 8 /* ScalarType.BOOL */ },
{ no: 9, name: "options", kind: "message", T: Option, repeated: true },
{ no: 10, name: "json_name", kind: "scalar", T: 9 /* ScalarType.STRING */ },
{ no: 11, name: "default_value", kind: "scalar", T: 9 /* ScalarType.STRING */ },
]);
/**
* Basic field types.
*
* @generated from enum google.protobuf.Field.Kind
*/
var Field_Kind;
(function (Field_Kind) {
/**
* Field type unknown.
*
* @generated from enum value: TYPE_UNKNOWN = 0;
*/
Field_Kind[Field_Kind["TYPE_UNKNOWN"] = 0] = "TYPE_UNKNOWN";
/**
* Field type double.
*
* @generated from enum value: TYPE_DOUBLE = 1;
*/
Field_Kind[Field_Kind["TYPE_DOUBLE"] = 1] = "TYPE_DOUBLE";
/**
* Field type float.
*
* @generated from enum value: TYPE_FLOAT = 2;
*/
Field_Kind[Field_Kind["TYPE_FLOAT"] = 2] = "TYPE_FLOAT";
/**
* Field type int64.
*
* @generated from enum value: TYPE_INT64 = 3;
*/
Field_Kind[Field_Kind["TYPE_INT64"] = 3] = "TYPE_INT64";
/**
* Field type uint64.
*
* @generated from enum value: TYPE_UINT64 = 4;
*/
Field_Kind[Field_Kind["TYPE_UINT64"] = 4] = "TYPE_UINT64";
/**
* Field type int32.
*
* @generated from enum value: TYPE_INT32 = 5;
*/
Field_Kind[Field_Kind["TYPE_INT32"] = 5] = "TYPE_INT32";
/**
* Field type fixed64.
*
* @generated from enum value: TYPE_FIXED64 = 6;
*/
Field_Kind[Field_Kind["TYPE_FIXED64"] = 6] = "TYPE_FIXED64";
/**
* Field type fixed32.
*
* @generated from enum value: TYPE_FIXED32 = 7;
*/
Field_Kind[Field_Kind["TYPE_FIXED32"] = 7] = "TYPE_FIXED32";
/**
* Field type bool.
*
* @generated from enum value: TYPE_BOOL = 8;
*/
Field_Kind[Field_Kind["TYPE_BOOL"] = 8] = "TYPE_BOOL";
/**
* Field type string.
*
* @generated from enum value: TYPE_STRING = 9;
*/
Field_Kind[Field_Kind["TYPE_STRING"] = 9] = "TYPE_STRING";
/**
* Field type group. Proto2 syntax only, and deprecated.
*
* @generated from enum value: TYPE_GROUP = 10;
*/
Field_Kind[Field_Kind["TYPE_GROUP"] = 10] = "TYPE_GROUP";
/**
* Field type message.
*
* @generated from enum value: TYPE_MESSAGE = 11;
*/
Field_Kind[Field_Kind["TYPE_MESSAGE"] = 11] = "TYPE_MESSAGE";
/**
* Field type bytes.
*
* @generated from enum value: TYPE_BYTES = 12;
*/
Field_Kind[Field_Kind["TYPE_BYTES"] = 12] = "TYPE_BYTES";
/**
* Field type uint32.
*
* @generated from enum value: TYPE_UINT32 = 13;
*/
Field_Kind[Field_Kind["TYPE_UINT32"] = 13] = "TYPE_UINT32";
/**
* Field type enum.
*
* @generated from enum value: TYPE_ENUM = 14;
*/
Field_Kind[Field_Kind["TYPE_ENUM"] = 14] = "TYPE_ENUM";
/**
* Field type sfixed32.
*
* @generated from enum value: TYPE_SFIXED32 = 15;
*/
Field_Kind[Field_Kind["TYPE_SFIXED32"] = 15] = "TYPE_SFIXED32";
/**
* Field type sfixed64.
*
* @generated from enum value: TYPE_SFIXED64 = 16;
*/
Field_Kind[Field_Kind["TYPE_SFIXED64"] = 16] = "TYPE_SFIXED64";
/**
* Field type sint32.
*
* @generated from enum value: TYPE_SINT32 = 17;
*/
Field_Kind[Field_Kind["TYPE_SINT32"] = 17] = "TYPE_SINT32";
/**
* Field type sint64.
*
* @generated from enum value: TYPE_SINT64 = 18;
*/
Field_Kind[Field_Kind["TYPE_SINT64"] = 18] = "TYPE_SINT64";
})(Field_Kind || (exports.Field_Kind = Field_Kind = {}));
// Retrieve enum metadata with: proto3.getEnumType(Field_Kind)
proto3_js_1.proto3.util.setEnumType(Field_Kind, "google.protobuf.Field.Kind", [
{ no: 0, name: "TYPE_UNKNOWN" },
{ no: 1, name: "TYPE_DOUBLE" },
{ no: 2, name: "TYPE_FLOAT" },
{ no: 3, name: "TYPE_INT64" },
{ no: 4, name: "TYPE_UINT64" },
{ no: 5, name: "TYPE_INT32" },
{ no: 6, name: "TYPE_FIXED64" },
{ no: 7, name: "TYPE_FIXED32" },
{ no: 8, name: "TYPE_BOOL" },
{ no: 9, name: "TYPE_STRING" },
{ no: 10, name: "TYPE_GROUP" },
{ no: 11, name: "TYPE_MESSAGE" },
{ no: 12, name: "TYPE_BYTES" },
{ no: 13, name: "TYPE_UINT32" },
{ no: 14, name: "TYPE_ENUM" },
{ no: 15, name: "TYPE_SFIXED32" },
{ no: 16, name: "TYPE_SFIXED64" },
{ no: 17, name: "TYPE_SINT32" },
{ no: 18, name: "TYPE_SINT64" },
]);
/**
* Whether a field is optional, required, or repeated.
*
* @generated from enum google.protobuf.Field.Cardinality
*/
var Field_Cardinality;
(function (Field_Cardinality) {
/**
* For fields with unknown cardinality.
*
* @generated from enum value: CARDINALITY_UNKNOWN = 0;
*/
Field_Cardinality[Field_Cardinality["UNKNOWN"] = 0] = "UNKNOWN";
/**
* For optional fields.
*
* @generated from enum value: CARDINALITY_OPTIONAL = 1;
*/
Field_Cardinality[Field_Cardinality["OPTIONAL"] = 1] = "OPTIONAL";
/**
* For required fields. Proto2 syntax only.
*
* @generated from enum value: CARDINALITY_REQUIRED = 2;
*/
Field_Cardinality[Field_Cardinality["REQUIRED"] = 2] = "REQUIRED";
/**
* For repeated fields.
*
* @generated from enum value: CARDINALITY_REPEATED = 3;
*/
Field_Cardinality[Field_Cardinality["REPEATED"] = 3] = "REPEATED";
})(Field_Cardinality || (exports.Field_Cardinality = Field_Cardinality = {}));
// Retrieve enum metadata with: proto3.getEnumType(Field_Cardinality)
proto3_js_1.proto3.util.setEnumType(Field_Cardinality, "google.protobuf.Field.Cardinality", [
{ no: 0, name: "CARDINALITY_UNKNOWN" },
{ no: 1, name: "CARDINALITY_OPTIONAL" },
{ no: 2, name: "CARDINALITY_REQUIRED" },
{ no: 3, name: "CARDINALITY_REPEATED" },
]);
/**
* Enum type definition.
*
* @generated from message google.protobuf.Enum
*/
class Enum extends message_js_1.Message {
constructor(data) {
super();
/**
* Enum type name.
*
* @generated from field: string name = 1;
*/
this.name = "";
/**
* Enum value definitions.
*
* @generated from field: repeated google.protobuf.EnumValue enumvalue = 2;
*/
this.enumvalue = [];
/**
* Protocol buffer options.
*
* @generated from field: repeated google.protobuf.Option options = 3;
*/
this.options = [];
/**
* The source syntax.
*
* @generated from field: google.protobuf.Syntax syntax = 5;
*/
this.syntax = Syntax.PROTO2;
/**
* The source edition string, only valid when syntax is SYNTAX_EDITIONS.
*
* @generated from field: string edition = 6;
*/
this.edition = "";
proto3_js_1.proto3.util.initPartial(data, this);
}
static fromBinary(bytes, options) {
return new Enum().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new Enum().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new Enum().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto3_js_1.proto3.util.equals(Enum, a, b);
}
}
exports.Enum = Enum;
Enum.runtime = proto3_js_1.proto3;
Enum.typeName = "google.protobuf.Enum";
Enum.fields = proto3_js_1.proto3.util.newFieldList(() => [
{ no: 1, name: "name", kind: "scalar", T: 9 /* ScalarType.STRING */ },
{ no: 2, name: "enumvalue", kind: "message", T: EnumValue, repeated: true },
{ no: 3, name: "options", kind: "message", T: Option, repeated: true },
{ no: 4, name: "source_context", kind: "message", T: source_context_pb_js_1.SourceContext },
{ no: 5, name: "syntax", kind: "enum", T: proto3_js_1.proto3.getEnumType(Syntax) },
{ no: 6, name: "edition", kind: "scalar", T: 9 /* ScalarType.STRING */ },
]);
/**
* Enum value definition.
*
* @generated from message google.protobuf.EnumValue
*/
class EnumValue extends message_js_1.Message {
constructor(data) {
super();
/**
* Enum value name.
*
* @generated from field: string name = 1;
*/
this.name = "";
/**
* Enum value number.
*
* @generated from field: int32 number = 2;
*/
this.number = 0;
/**
* Protocol buffer options.
*
* @generated from field: repeated google.protobuf.Option options = 3;
*/
this.options = [];
proto3_js_1.proto3.util.initPartial(data, this);
}
static fromBinary(bytes, options) {
return new EnumValue().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new EnumValue().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new EnumValue().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto3_js_1.proto3.util.equals(EnumValue, a, b);
}
}
exports.EnumValue = EnumValue;
EnumValue.runtime = proto3_js_1.proto3;
EnumValue.typeName = "google.protobuf.EnumValue";
EnumValue.fields = proto3_js_1.proto3.util.newFieldList(() => [
{ no: 1, name: "name", kind: "scalar", T: 9 /* ScalarType.STRING */ },
{ no: 2, name: "number", kind: "scalar", T: 5 /* ScalarType.INT32 */ },
{ no: 3, name: "options", kind: "message", T: Option, repeated: true },
]);
/**
* A protocol buffer option, which can be attached to a message, field,
* enumeration, etc.
*
* @generated from message google.protobuf.Option
*/
class Option extends message_js_1.Message {
constructor(data) {
super();
/**
* The option's name. For protobuf built-in options (options defined in
* descriptor.proto), this is the short name. For example, `"map_entry"`.
* For custom options, it should be the fully-qualified name. For example,
* `"google.api.http"`.
*
* @generated from field: string name = 1;
*/
this.name = "";
proto3_js_1.proto3.util.initPartial(data, this);
}
static fromBinary(bytes, options) {
return new Option().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new Option().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new Option().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto3_js_1.proto3.util.equals(Option, a, b);
}
}
exports.Option = Option;
Option.runtime = proto3_js_1.proto3;
Option.typeName = "google.protobuf.Option";
Option.fields = proto3_js_1.proto3.util.newFieldList(() => [
{ no: 1, name: "name", kind: "scalar", T: 9 /* ScalarType.STRING */ },
{ no: 2, name: "value", kind: "message", T: any_pb_js_1.Any },
]);
@@ -0,0 +1,267 @@
import type { PartialMessage, PlainMessage } from "../../message.js";
import { Message } from "../../message.js";
import { proto3 } from "../../proto3.js";
import type { JsonReadOptions, JsonValue, JsonWriteOptions } from "../../json-format.js";
import type { FieldList } from "../../field-list.js";
import type { BinaryReadOptions } from "../../binary-format.js";
/**
* Wrapper message for `double`.
*
* The JSON representation for `DoubleValue` is JSON number.
*
* @generated from message google.protobuf.DoubleValue
*/
export declare class DoubleValue extends Message<DoubleValue> {
/**
* The double value.
*
* @generated from field: double value = 1;
*/
value: number;
constructor(data?: PartialMessage<DoubleValue>);
toJson(options?: Partial<JsonWriteOptions>): JsonValue;
fromJson(json: JsonValue, options?: Partial<JsonReadOptions>): this;
static readonly runtime: typeof proto3;
static readonly typeName = "google.protobuf.DoubleValue";
static readonly fields: FieldList;
static readonly fieldWrapper: {
wrapField(value: number): DoubleValue;
unwrapField(value: DoubleValue): number;
};
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): DoubleValue;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): DoubleValue;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): DoubleValue;
static equals(a: DoubleValue | PlainMessage<DoubleValue> | undefined, b: DoubleValue | PlainMessage<DoubleValue> | undefined): boolean;
}
/**
* Wrapper message for `float`.
*
* The JSON representation for `FloatValue` is JSON number.
*
* @generated from message google.protobuf.FloatValue
*/
export declare class FloatValue extends Message<FloatValue> {
/**
* The float value.
*
* @generated from field: float value = 1;
*/
value: number;
constructor(data?: PartialMessage<FloatValue>);
toJson(options?: Partial<JsonWriteOptions>): JsonValue;
fromJson(json: JsonValue, options?: Partial<JsonReadOptions>): this;
static readonly runtime: typeof proto3;
static readonly typeName = "google.protobuf.FloatValue";
static readonly fields: FieldList;
static readonly fieldWrapper: {
wrapField(value: number): FloatValue;
unwrapField(value: FloatValue): number;
};
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): FloatValue;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): FloatValue;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): FloatValue;
static equals(a: FloatValue | PlainMessage<FloatValue> | undefined, b: FloatValue | PlainMessage<FloatValue> | undefined): boolean;
}
/**
* Wrapper message for `int64`.
*
* The JSON representation for `Int64Value` is JSON string.
*
* @generated from message google.protobuf.Int64Value
*/
export declare class Int64Value extends Message<Int64Value> {
/**
* The int64 value.
*
* @generated from field: int64 value = 1;
*/
value: bigint;
constructor(data?: PartialMessage<Int64Value>);
toJson(options?: Partial<JsonWriteOptions>): JsonValue;
fromJson(json: JsonValue, options?: Partial<JsonReadOptions>): this;
static readonly runtime: typeof proto3;
static readonly typeName = "google.protobuf.Int64Value";
static readonly fields: FieldList;
static readonly fieldWrapper: {
wrapField(value: bigint): Int64Value;
unwrapField(value: Int64Value): bigint;
};
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): Int64Value;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): Int64Value;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): Int64Value;
static equals(a: Int64Value | PlainMessage<Int64Value> | undefined, b: Int64Value | PlainMessage<Int64Value> | undefined): boolean;
}
/**
* Wrapper message for `uint64`.
*
* The JSON representation for `UInt64Value` is JSON string.
*
* @generated from message google.protobuf.UInt64Value
*/
export declare class UInt64Value extends Message<UInt64Value> {
/**
* The uint64 value.
*
* @generated from field: uint64 value = 1;
*/
value: bigint;
constructor(data?: PartialMessage<UInt64Value>);
toJson(options?: Partial<JsonWriteOptions>): JsonValue;
fromJson(json: JsonValue, options?: Partial<JsonReadOptions>): this;
static readonly runtime: typeof proto3;
static readonly typeName = "google.protobuf.UInt64Value";
static readonly fields: FieldList;
static readonly fieldWrapper: {
wrapField(value: bigint): UInt64Value;
unwrapField(value: UInt64Value): bigint;
};
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): UInt64Value;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): UInt64Value;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): UInt64Value;
static equals(a: UInt64Value | PlainMessage<UInt64Value> | undefined, b: UInt64Value | PlainMessage<UInt64Value> | undefined): boolean;
}
/**
* Wrapper message for `int32`.
*
* The JSON representation for `Int32Value` is JSON number.
*
* @generated from message google.protobuf.Int32Value
*/
export declare class Int32Value extends Message<Int32Value> {
/**
* The int32 value.
*
* @generated from field: int32 value = 1;
*/
value: number;
constructor(data?: PartialMessage<Int32Value>);
toJson(options?: Partial<JsonWriteOptions>): JsonValue;
fromJson(json: JsonValue, options?: Partial<JsonReadOptions>): this;
static readonly runtime: typeof proto3;
static readonly typeName = "google.protobuf.Int32Value";
static readonly fields: FieldList;
static readonly fieldWrapper: {
wrapField(value: number): Int32Value;
unwrapField(value: Int32Value): number;
};
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): Int32Value;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): Int32Value;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): Int32Value;
static equals(a: Int32Value | PlainMessage<Int32Value> | undefined, b: Int32Value | PlainMessage<Int32Value> | undefined): boolean;
}
/**
* Wrapper message for `uint32`.
*
* The JSON representation for `UInt32Value` is JSON number.
*
* @generated from message google.protobuf.UInt32Value
*/
export declare class UInt32Value extends Message<UInt32Value> {
/**
* The uint32 value.
*
* @generated from field: uint32 value = 1;
*/
value: number;
constructor(data?: PartialMessage<UInt32Value>);
toJson(options?: Partial<JsonWriteOptions>): JsonValue;
fromJson(json: JsonValue, options?: Partial<JsonReadOptions>): this;
static readonly runtime: typeof proto3;
static readonly typeName = "google.protobuf.UInt32Value";
static readonly fields: FieldList;
static readonly fieldWrapper: {
wrapField(value: number): UInt32Value;
unwrapField(value: UInt32Value): number;
};
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): UInt32Value;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): UInt32Value;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): UInt32Value;
static equals(a: UInt32Value | PlainMessage<UInt32Value> | undefined, b: UInt32Value | PlainMessage<UInt32Value> | undefined): boolean;
}
/**
* Wrapper message for `bool`.
*
* The JSON representation for `BoolValue` is JSON `true` and `false`.
*
* @generated from message google.protobuf.BoolValue
*/
export declare class BoolValue extends Message<BoolValue> {
/**
* The bool value.
*
* @generated from field: bool value = 1;
*/
value: boolean;
constructor(data?: PartialMessage<BoolValue>);
toJson(options?: Partial<JsonWriteOptions>): JsonValue;
fromJson(json: JsonValue, options?: Partial<JsonReadOptions>): this;
static readonly runtime: typeof proto3;
static readonly typeName = "google.protobuf.BoolValue";
static readonly fields: FieldList;
static readonly fieldWrapper: {
wrapField(value: boolean): BoolValue;
unwrapField(value: BoolValue): boolean;
};
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): BoolValue;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): BoolValue;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): BoolValue;
static equals(a: BoolValue | PlainMessage<BoolValue> | undefined, b: BoolValue | PlainMessage<BoolValue> | undefined): boolean;
}
/**
* Wrapper message for `string`.
*
* The JSON representation for `StringValue` is JSON string.
*
* @generated from message google.protobuf.StringValue
*/
export declare class StringValue extends Message<StringValue> {
/**
* The string value.
*
* @generated from field: string value = 1;
*/
value: string;
constructor(data?: PartialMessage<StringValue>);
toJson(options?: Partial<JsonWriteOptions>): JsonValue;
fromJson(json: JsonValue, options?: Partial<JsonReadOptions>): this;
static readonly runtime: typeof proto3;
static readonly typeName = "google.protobuf.StringValue";
static readonly fields: FieldList;
static readonly fieldWrapper: {
wrapField(value: string): StringValue;
unwrapField(value: StringValue): string;
};
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): StringValue;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): StringValue;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): StringValue;
static equals(a: StringValue | PlainMessage<StringValue> | undefined, b: StringValue | PlainMessage<StringValue> | undefined): boolean;
}
/**
* Wrapper message for `bytes`.
*
* The JSON representation for `BytesValue` is JSON string.
*
* @generated from message google.protobuf.BytesValue
*/
export declare class BytesValue extends Message<BytesValue> {
/**
* The bytes value.
*
* @generated from field: bytes value = 1;
*/
value: Uint8Array;
constructor(data?: PartialMessage<BytesValue>);
toJson(options?: Partial<JsonWriteOptions>): JsonValue;
fromJson(json: JsonValue, options?: Partial<JsonReadOptions>): this;
static readonly runtime: typeof proto3;
static readonly typeName = "google.protobuf.BytesValue";
static readonly fields: FieldList;
static readonly fieldWrapper: {
wrapField(value: Uint8Array): BytesValue;
unwrapField(value: BytesValue): Uint8Array;
};
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): BytesValue;
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): BytesValue;
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): BytesValue;
static equals(a: BytesValue | PlainMessage<BytesValue> | undefined, b: BytesValue | PlainMessage<BytesValue> | undefined): boolean;
}
+569
View File
@@ -0,0 +1,569 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.BytesValue = exports.StringValue = exports.BoolValue = exports.UInt32Value = exports.Int32Value = exports.UInt64Value = exports.Int64Value = exports.FloatValue = exports.DoubleValue = void 0;
const message_js_1 = require("../../message.js");
const proto3_js_1 = require("../../proto3.js");
const scalar_js_1 = require("../../scalar.js");
const proto_int64_js_1 = require("../../proto-int64.js");
/**
* Wrapper message for `double`.
*
* The JSON representation for `DoubleValue` is JSON number.
*
* @generated from message google.protobuf.DoubleValue
*/
class DoubleValue extends message_js_1.Message {
constructor(data) {
super();
/**
* The double value.
*
* @generated from field: double value = 1;
*/
this.value = 0;
proto3_js_1.proto3.util.initPartial(data, this);
}
toJson(options) {
return proto3_js_1.proto3.json.writeScalar(scalar_js_1.ScalarType.DOUBLE, this.value, true);
}
fromJson(json, options) {
try {
this.value = proto3_js_1.proto3.json.readScalar(scalar_js_1.ScalarType.DOUBLE, json);
}
catch (e) {
let m = `cannot decode message google.protobuf.DoubleValue from JSON"`;
if (e instanceof Error && e.message.length > 0) {
m += `: ${e.message}`;
}
throw new Error(m);
}
return this;
}
static fromBinary(bytes, options) {
return new DoubleValue().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new DoubleValue().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new DoubleValue().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto3_js_1.proto3.util.equals(DoubleValue, a, b);
}
}
exports.DoubleValue = DoubleValue;
DoubleValue.runtime = proto3_js_1.proto3;
DoubleValue.typeName = "google.protobuf.DoubleValue";
DoubleValue.fields = proto3_js_1.proto3.util.newFieldList(() => [
{ no: 1, name: "value", kind: "scalar", T: 1 /* ScalarType.DOUBLE */ },
]);
DoubleValue.fieldWrapper = {
wrapField(value) {
return new DoubleValue({ value });
},
unwrapField(value) {
return value.value;
}
};
/**
* Wrapper message for `float`.
*
* The JSON representation for `FloatValue` is JSON number.
*
* @generated from message google.protobuf.FloatValue
*/
class FloatValue extends message_js_1.Message {
constructor(data) {
super();
/**
* The float value.
*
* @generated from field: float value = 1;
*/
this.value = 0;
proto3_js_1.proto3.util.initPartial(data, this);
}
toJson(options) {
return proto3_js_1.proto3.json.writeScalar(scalar_js_1.ScalarType.FLOAT, this.value, true);
}
fromJson(json, options) {
try {
this.value = proto3_js_1.proto3.json.readScalar(scalar_js_1.ScalarType.FLOAT, json);
}
catch (e) {
let m = `cannot decode message google.protobuf.FloatValue from JSON"`;
if (e instanceof Error && e.message.length > 0) {
m += `: ${e.message}`;
}
throw new Error(m);
}
return this;
}
static fromBinary(bytes, options) {
return new FloatValue().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new FloatValue().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new FloatValue().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto3_js_1.proto3.util.equals(FloatValue, a, b);
}
}
exports.FloatValue = FloatValue;
FloatValue.runtime = proto3_js_1.proto3;
FloatValue.typeName = "google.protobuf.FloatValue";
FloatValue.fields = proto3_js_1.proto3.util.newFieldList(() => [
{ no: 1, name: "value", kind: "scalar", T: 2 /* ScalarType.FLOAT */ },
]);
FloatValue.fieldWrapper = {
wrapField(value) {
return new FloatValue({ value });
},
unwrapField(value) {
return value.value;
}
};
/**
* Wrapper message for `int64`.
*
* The JSON representation for `Int64Value` is JSON string.
*
* @generated from message google.protobuf.Int64Value
*/
class Int64Value extends message_js_1.Message {
constructor(data) {
super();
/**
* The int64 value.
*
* @generated from field: int64 value = 1;
*/
this.value = proto_int64_js_1.protoInt64.zero;
proto3_js_1.proto3.util.initPartial(data, this);
}
toJson(options) {
return proto3_js_1.proto3.json.writeScalar(scalar_js_1.ScalarType.INT64, this.value, true);
}
fromJson(json, options) {
try {
this.value = proto3_js_1.proto3.json.readScalar(scalar_js_1.ScalarType.INT64, json);
}
catch (e) {
let m = `cannot decode message google.protobuf.Int64Value from JSON"`;
if (e instanceof Error && e.message.length > 0) {
m += `: ${e.message}`;
}
throw new Error(m);
}
return this;
}
static fromBinary(bytes, options) {
return new Int64Value().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new Int64Value().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new Int64Value().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto3_js_1.proto3.util.equals(Int64Value, a, b);
}
}
exports.Int64Value = Int64Value;
Int64Value.runtime = proto3_js_1.proto3;
Int64Value.typeName = "google.protobuf.Int64Value";
Int64Value.fields = proto3_js_1.proto3.util.newFieldList(() => [
{ no: 1, name: "value", kind: "scalar", T: 3 /* ScalarType.INT64 */ },
]);
Int64Value.fieldWrapper = {
wrapField(value) {
return new Int64Value({ value });
},
unwrapField(value) {
return value.value;
}
};
/**
* Wrapper message for `uint64`.
*
* The JSON representation for `UInt64Value` is JSON string.
*
* @generated from message google.protobuf.UInt64Value
*/
class UInt64Value extends message_js_1.Message {
constructor(data) {
super();
/**
* The uint64 value.
*
* @generated from field: uint64 value = 1;
*/
this.value = proto_int64_js_1.protoInt64.zero;
proto3_js_1.proto3.util.initPartial(data, this);
}
toJson(options) {
return proto3_js_1.proto3.json.writeScalar(scalar_js_1.ScalarType.UINT64, this.value, true);
}
fromJson(json, options) {
try {
this.value = proto3_js_1.proto3.json.readScalar(scalar_js_1.ScalarType.UINT64, json);
}
catch (e) {
let m = `cannot decode message google.protobuf.UInt64Value from JSON"`;
if (e instanceof Error && e.message.length > 0) {
m += `: ${e.message}`;
}
throw new Error(m);
}
return this;
}
static fromBinary(bytes, options) {
return new UInt64Value().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new UInt64Value().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new UInt64Value().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto3_js_1.proto3.util.equals(UInt64Value, a, b);
}
}
exports.UInt64Value = UInt64Value;
UInt64Value.runtime = proto3_js_1.proto3;
UInt64Value.typeName = "google.protobuf.UInt64Value";
UInt64Value.fields = proto3_js_1.proto3.util.newFieldList(() => [
{ no: 1, name: "value", kind: "scalar", T: 4 /* ScalarType.UINT64 */ },
]);
UInt64Value.fieldWrapper = {
wrapField(value) {
return new UInt64Value({ value });
},
unwrapField(value) {
return value.value;
}
};
/**
* Wrapper message for `int32`.
*
* The JSON representation for `Int32Value` is JSON number.
*
* @generated from message google.protobuf.Int32Value
*/
class Int32Value extends message_js_1.Message {
constructor(data) {
super();
/**
* The int32 value.
*
* @generated from field: int32 value = 1;
*/
this.value = 0;
proto3_js_1.proto3.util.initPartial(data, this);
}
toJson(options) {
return proto3_js_1.proto3.json.writeScalar(scalar_js_1.ScalarType.INT32, this.value, true);
}
fromJson(json, options) {
try {
this.value = proto3_js_1.proto3.json.readScalar(scalar_js_1.ScalarType.INT32, json);
}
catch (e) {
let m = `cannot decode message google.protobuf.Int32Value from JSON"`;
if (e instanceof Error && e.message.length > 0) {
m += `: ${e.message}`;
}
throw new Error(m);
}
return this;
}
static fromBinary(bytes, options) {
return new Int32Value().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new Int32Value().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new Int32Value().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto3_js_1.proto3.util.equals(Int32Value, a, b);
}
}
exports.Int32Value = Int32Value;
Int32Value.runtime = proto3_js_1.proto3;
Int32Value.typeName = "google.protobuf.Int32Value";
Int32Value.fields = proto3_js_1.proto3.util.newFieldList(() => [
{ no: 1, name: "value", kind: "scalar", T: 5 /* ScalarType.INT32 */ },
]);
Int32Value.fieldWrapper = {
wrapField(value) {
return new Int32Value({ value });
},
unwrapField(value) {
return value.value;
}
};
/**
* Wrapper message for `uint32`.
*
* The JSON representation for `UInt32Value` is JSON number.
*
* @generated from message google.protobuf.UInt32Value
*/
class UInt32Value extends message_js_1.Message {
constructor(data) {
super();
/**
* The uint32 value.
*
* @generated from field: uint32 value = 1;
*/
this.value = 0;
proto3_js_1.proto3.util.initPartial(data, this);
}
toJson(options) {
return proto3_js_1.proto3.json.writeScalar(scalar_js_1.ScalarType.UINT32, this.value, true);
}
fromJson(json, options) {
try {
this.value = proto3_js_1.proto3.json.readScalar(scalar_js_1.ScalarType.UINT32, json);
}
catch (e) {
let m = `cannot decode message google.protobuf.UInt32Value from JSON"`;
if (e instanceof Error && e.message.length > 0) {
m += `: ${e.message}`;
}
throw new Error(m);
}
return this;
}
static fromBinary(bytes, options) {
return new UInt32Value().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new UInt32Value().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new UInt32Value().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto3_js_1.proto3.util.equals(UInt32Value, a, b);
}
}
exports.UInt32Value = UInt32Value;
UInt32Value.runtime = proto3_js_1.proto3;
UInt32Value.typeName = "google.protobuf.UInt32Value";
UInt32Value.fields = proto3_js_1.proto3.util.newFieldList(() => [
{ no: 1, name: "value", kind: "scalar", T: 13 /* ScalarType.UINT32 */ },
]);
UInt32Value.fieldWrapper = {
wrapField(value) {
return new UInt32Value({ value });
},
unwrapField(value) {
return value.value;
}
};
/**
* Wrapper message for `bool`.
*
* The JSON representation for `BoolValue` is JSON `true` and `false`.
*
* @generated from message google.protobuf.BoolValue
*/
class BoolValue extends message_js_1.Message {
constructor(data) {
super();
/**
* The bool value.
*
* @generated from field: bool value = 1;
*/
this.value = false;
proto3_js_1.proto3.util.initPartial(data, this);
}
toJson(options) {
return proto3_js_1.proto3.json.writeScalar(scalar_js_1.ScalarType.BOOL, this.value, true);
}
fromJson(json, options) {
try {
this.value = proto3_js_1.proto3.json.readScalar(scalar_js_1.ScalarType.BOOL, json);
}
catch (e) {
let m = `cannot decode message google.protobuf.BoolValue from JSON"`;
if (e instanceof Error && e.message.length > 0) {
m += `: ${e.message}`;
}
throw new Error(m);
}
return this;
}
static fromBinary(bytes, options) {
return new BoolValue().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new BoolValue().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new BoolValue().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto3_js_1.proto3.util.equals(BoolValue, a, b);
}
}
exports.BoolValue = BoolValue;
BoolValue.runtime = proto3_js_1.proto3;
BoolValue.typeName = "google.protobuf.BoolValue";
BoolValue.fields = proto3_js_1.proto3.util.newFieldList(() => [
{ no: 1, name: "value", kind: "scalar", T: 8 /* ScalarType.BOOL */ },
]);
BoolValue.fieldWrapper = {
wrapField(value) {
return new BoolValue({ value });
},
unwrapField(value) {
return value.value;
}
};
/**
* Wrapper message for `string`.
*
* The JSON representation for `StringValue` is JSON string.
*
* @generated from message google.protobuf.StringValue
*/
class StringValue extends message_js_1.Message {
constructor(data) {
super();
/**
* The string value.
*
* @generated from field: string value = 1;
*/
this.value = "";
proto3_js_1.proto3.util.initPartial(data, this);
}
toJson(options) {
return proto3_js_1.proto3.json.writeScalar(scalar_js_1.ScalarType.STRING, this.value, true);
}
fromJson(json, options) {
try {
this.value = proto3_js_1.proto3.json.readScalar(scalar_js_1.ScalarType.STRING, json);
}
catch (e) {
let m = `cannot decode message google.protobuf.StringValue from JSON"`;
if (e instanceof Error && e.message.length > 0) {
m += `: ${e.message}`;
}
throw new Error(m);
}
return this;
}
static fromBinary(bytes, options) {
return new StringValue().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new StringValue().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new StringValue().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto3_js_1.proto3.util.equals(StringValue, a, b);
}
}
exports.StringValue = StringValue;
StringValue.runtime = proto3_js_1.proto3;
StringValue.typeName = "google.protobuf.StringValue";
StringValue.fields = proto3_js_1.proto3.util.newFieldList(() => [
{ no: 1, name: "value", kind: "scalar", T: 9 /* ScalarType.STRING */ },
]);
StringValue.fieldWrapper = {
wrapField(value) {
return new StringValue({ value });
},
unwrapField(value) {
return value.value;
}
};
/**
* Wrapper message for `bytes`.
*
* The JSON representation for `BytesValue` is JSON string.
*
* @generated from message google.protobuf.BytesValue
*/
class BytesValue extends message_js_1.Message {
constructor(data) {
super();
/**
* The bytes value.
*
* @generated from field: bytes value = 1;
*/
this.value = new Uint8Array(0);
proto3_js_1.proto3.util.initPartial(data, this);
}
toJson(options) {
return proto3_js_1.proto3.json.writeScalar(scalar_js_1.ScalarType.BYTES, this.value, true);
}
fromJson(json, options) {
try {
this.value = proto3_js_1.proto3.json.readScalar(scalar_js_1.ScalarType.BYTES, json);
}
catch (e) {
let m = `cannot decode message google.protobuf.BytesValue from JSON"`;
if (e instanceof Error && e.message.length > 0) {
m += `: ${e.message}`;
}
throw new Error(m);
}
return this;
}
static fromBinary(bytes, options) {
return new BytesValue().fromBinary(bytes, options);
}
static fromJson(jsonValue, options) {
return new BytesValue().fromJson(jsonValue, options);
}
static fromJsonString(jsonString, options) {
return new BytesValue().fromJsonString(jsonString, options);
}
static equals(a, b) {
return proto3_js_1.proto3.util.equals(BytesValue, a, b);
}
}
exports.BytesValue = BytesValue;
BytesValue.runtime = proto3_js_1.proto3;
BytesValue.typeName = "google.protobuf.BytesValue";
BytesValue.fields = proto3_js_1.proto3.util.newFieldList(() => [
{ no: 1, name: "value", kind: "scalar", T: 12 /* ScalarType.BYTES */ },
]);
BytesValue.fieldWrapper = {
wrapField(value) {
return new BytesValue({ value });
},
unwrapField(value) {
return value.value;
}
};
+70
View File
@@ -0,0 +1,70 @@
/**
* Read a 64 bit varint as two JS numbers.
*
* Returns tuple:
* [0]: low bits
* [1]: high bits
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L175
*/
export declare function varint64read(this: ReaderLike): [number, number];
/**
* Write a 64 bit varint, given as two JS numbers, to the given bytes array.
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/writer.js#L344
*/
export declare function varint64write(lo: number, hi: number, bytes: number[]): void;
/**
* Parse decimal string of 64 bit integer value as two JS numbers.
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf-javascript/blob/a428c58273abad07c66071d9753bc4d1289de426/experimental/runtime/int64.js#L10
*/
export declare function int64FromString(dec: string): {
lo: number;
hi: number;
};
/**
* Losslessly converts a 64-bit signed integer in 32:32 split representation
* into a decimal string.
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf-javascript/blob/a428c58273abad07c66071d9753bc4d1289de426/experimental/runtime/int64.js#L10
*/
export declare function int64ToString(lo: number, hi: number): string;
/**
* Losslessly converts a 64-bit unsigned integer in 32:32 split representation
* into a decimal string.
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf-javascript/blob/a428c58273abad07c66071d9753bc4d1289de426/experimental/runtime/int64.js#L10
*/
export declare function uInt64ToString(lo: number, hi: number): string;
/**
* Write a 32 bit varint, signed or unsigned. Same as `varint64write(0, value, bytes)`
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf/blob/1b18833f4f2a2f681f4e4a25cdf3b0a43115ec26/js/binary/encoder.js#L144
*/
export declare function varint32write(value: number, bytes: number[]): void;
/**
* Read an unsigned 32 bit varint.
*
* See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L220
*/
export declare function varint32read(this: ReaderLike): number;
type ReaderLike = {
buf: Uint8Array;
pos: number;
len: number;
assertBounds(): void;
};
export {};
+323
View File
@@ -0,0 +1,323 @@
"use strict";
// Copyright 2008 Google Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Code generated by the Protocol Buffer compiler is owned by the owner
// of the input file used when generating it. This code is not
// standalone and requires a support library to be linked with it. This
// support library is itself covered by the above license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.varint32read = exports.varint32write = exports.uInt64ToString = exports.int64ToString = exports.int64FromString = exports.varint64write = exports.varint64read = void 0;
/* eslint-disable prefer-const,@typescript-eslint/restrict-plus-operands */
/**
* Read a 64 bit varint as two JS numbers.
*
* Returns tuple:
* [0]: low bits
* [1]: high bits
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L175
*/
function varint64read() {
let lowBits = 0;
let highBits = 0;
for (let shift = 0; shift < 28; shift += 7) {
let b = this.buf[this.pos++];
lowBits |= (b & 0x7f) << shift;
if ((b & 0x80) == 0) {
this.assertBounds();
return [lowBits, highBits];
}
}
let middleByte = this.buf[this.pos++];
// last four bits of the first 32 bit number
lowBits |= (middleByte & 0x0f) << 28;
// 3 upper bits are part of the next 32 bit number
highBits = (middleByte & 0x70) >> 4;
if ((middleByte & 0x80) == 0) {
this.assertBounds();
return [lowBits, highBits];
}
for (let shift = 3; shift <= 31; shift += 7) {
let b = this.buf[this.pos++];
highBits |= (b & 0x7f) << shift;
if ((b & 0x80) == 0) {
this.assertBounds();
return [lowBits, highBits];
}
}
throw new Error("invalid varint");
}
exports.varint64read = varint64read;
/**
* Write a 64 bit varint, given as two JS numbers, to the given bytes array.
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/writer.js#L344
*/
function varint64write(lo, hi, bytes) {
for (let i = 0; i < 28; i = i + 7) {
const shift = lo >>> i;
const hasNext = !(shift >>> 7 == 0 && hi == 0);
const byte = (hasNext ? shift | 0x80 : shift) & 0xff;
bytes.push(byte);
if (!hasNext) {
return;
}
}
const splitBits = ((lo >>> 28) & 0x0f) | ((hi & 0x07) << 4);
const hasMoreBits = !(hi >> 3 == 0);
bytes.push((hasMoreBits ? splitBits | 0x80 : splitBits) & 0xff);
if (!hasMoreBits) {
return;
}
for (let i = 3; i < 31; i = i + 7) {
const shift = hi >>> i;
const hasNext = !(shift >>> 7 == 0);
const byte = (hasNext ? shift | 0x80 : shift) & 0xff;
bytes.push(byte);
if (!hasNext) {
return;
}
}
bytes.push((hi >>> 31) & 0x01);
}
exports.varint64write = varint64write;
// constants for binary math
const TWO_PWR_32_DBL = 0x100000000;
/**
* Parse decimal string of 64 bit integer value as two JS numbers.
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf-javascript/blob/a428c58273abad07c66071d9753bc4d1289de426/experimental/runtime/int64.js#L10
*/
function int64FromString(dec) {
// Check for minus sign.
const minus = dec[0] === "-";
if (minus) {
dec = dec.slice(1);
}
// Work 6 decimal digits at a time, acting like we're converting base 1e6
// digits to binary. This is safe to do with floating point math because
// Number.isSafeInteger(ALL_32_BITS * 1e6) == true.
const base = 1e6;
let lowBits = 0;
let highBits = 0;
function add1e6digit(begin, end) {
// Note: Number('') is 0.
const digit1e6 = Number(dec.slice(begin, end));
highBits *= base;
lowBits = lowBits * base + digit1e6;
// Carry bits from lowBits to
if (lowBits >= TWO_PWR_32_DBL) {
highBits = highBits + ((lowBits / TWO_PWR_32_DBL) | 0);
lowBits = lowBits % TWO_PWR_32_DBL;
}
}
add1e6digit(-24, -18);
add1e6digit(-18, -12);
add1e6digit(-12, -6);
add1e6digit(-6);
return minus ? negate(lowBits, highBits) : newBits(lowBits, highBits);
}
exports.int64FromString = int64FromString;
/**
* Losslessly converts a 64-bit signed integer in 32:32 split representation
* into a decimal string.
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf-javascript/blob/a428c58273abad07c66071d9753bc4d1289de426/experimental/runtime/int64.js#L10
*/
function int64ToString(lo, hi) {
let bits = newBits(lo, hi);
// If we're treating the input as a signed value and the high bit is set, do
// a manual two's complement conversion before the decimal conversion.
const negative = (bits.hi & 0x80000000);
if (negative) {
bits = negate(bits.lo, bits.hi);
}
const result = uInt64ToString(bits.lo, bits.hi);
return negative ? "-" + result : result;
}
exports.int64ToString = int64ToString;
/**
* Losslessly converts a 64-bit unsigned integer in 32:32 split representation
* into a decimal string.
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf-javascript/blob/a428c58273abad07c66071d9753bc4d1289de426/experimental/runtime/int64.js#L10
*/
function uInt64ToString(lo, hi) {
({ lo, hi } = toUnsigned(lo, hi));
// Skip the expensive conversion if the number is small enough to use the
// built-in conversions.
// Number.MAX_SAFE_INTEGER = 0x001FFFFF FFFFFFFF, thus any number with
// highBits <= 0x1FFFFF can be safely expressed with a double and retain
// integer precision.
// Proven by: Number.isSafeInteger(0x1FFFFF * 2**32 + 0xFFFFFFFF) == true.
if (hi <= 0x1FFFFF) {
return String(TWO_PWR_32_DBL * hi + lo);
}
// What this code is doing is essentially converting the input number from
// base-2 to base-1e7, which allows us to represent the 64-bit range with
// only 3 (very large) digits. Those digits are then trivial to convert to
// a base-10 string.
// The magic numbers used here are -
// 2^24 = 16777216 = (1,6777216) in base-1e7.
// 2^48 = 281474976710656 = (2,8147497,6710656) in base-1e7.
// Split 32:32 representation into 16:24:24 representation so our
// intermediate digits don't overflow.
const low = lo & 0xFFFFFF;
const mid = ((lo >>> 24) | (hi << 8)) & 0xFFFFFF;
const high = (hi >> 16) & 0xFFFF;
// Assemble our three base-1e7 digits, ignoring carries. The maximum
// value in a digit at this step is representable as a 48-bit integer, which
// can be stored in a 64-bit floating point number.
let digitA = low + (mid * 6777216) + (high * 6710656);
let digitB = mid + (high * 8147497);
let digitC = (high * 2);
// Apply carries from A to B and from B to C.
const base = 10000000;
if (digitA >= base) {
digitB += Math.floor(digitA / base);
digitA %= base;
}
if (digitB >= base) {
digitC += Math.floor(digitB / base);
digitB %= base;
}
// If digitC is 0, then we should have returned in the trivial code path
// at the top for non-safe integers. Given this, we can assume both digitB
// and digitA need leading zeros.
return digitC.toString() + decimalFrom1e7WithLeadingZeros(digitB) +
decimalFrom1e7WithLeadingZeros(digitA);
}
exports.uInt64ToString = uInt64ToString;
function toUnsigned(lo, hi) {
return { lo: lo >>> 0, hi: hi >>> 0 };
}
function newBits(lo, hi) {
return { lo: lo | 0, hi: hi | 0 };
}
/**
* Returns two's compliment negation of input.
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Signed_32-bit_integers
*/
function negate(lowBits, highBits) {
highBits = ~highBits;
if (lowBits) {
lowBits = ~lowBits + 1;
}
else {
// If lowBits is 0, then bitwise-not is 0xFFFFFFFF,
// adding 1 to that, results in 0x100000000, which leaves
// the low bits 0x0 and simply adds one to the high bits.
highBits += 1;
}
return newBits(lowBits, highBits);
}
/**
* Returns decimal representation of digit1e7 with leading zeros.
*/
const decimalFrom1e7WithLeadingZeros = (digit1e7) => {
const partial = String(digit1e7);
return "0000000".slice(partial.length) + partial;
};
/**
* Write a 32 bit varint, signed or unsigned. Same as `varint64write(0, value, bytes)`
*
* Copyright 2008 Google Inc. All rights reserved.
*
* See https://github.com/protocolbuffers/protobuf/blob/1b18833f4f2a2f681f4e4a25cdf3b0a43115ec26/js/binary/encoder.js#L144
*/
function varint32write(value, bytes) {
if (value >= 0) {
// write value as varint 32
while (value > 0x7f) {
bytes.push((value & 0x7f) | 0x80);
value = value >>> 7;
}
bytes.push(value);
}
else {
for (let i = 0; i < 9; i++) {
bytes.push((value & 127) | 128);
value = value >> 7;
}
bytes.push(1);
}
}
exports.varint32write = varint32write;
/**
* Read an unsigned 32 bit varint.
*
* See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L220
*/
function varint32read() {
let b = this.buf[this.pos++];
let result = b & 0x7f;
if ((b & 0x80) == 0) {
this.assertBounds();
return result;
}
b = this.buf[this.pos++];
result |= (b & 0x7f) << 7;
if ((b & 0x80) == 0) {
this.assertBounds();
return result;
}
b = this.buf[this.pos++];
result |= (b & 0x7f) << 14;
if ((b & 0x80) == 0) {
this.assertBounds();
return result;
}
b = this.buf[this.pos++];
result |= (b & 0x7f) << 21;
if ((b & 0x80) == 0) {
this.assertBounds();
return result;
}
// Extract only last 4 bits
b = this.buf[this.pos++];
result |= (b & 0x0f) << 28;
for (let readBytes = 5; (b & 0x80) !== 0 && readBytes < 10; readBytes++)
b = this.buf[this.pos++];
if ((b & 0x80) != 0)
throw new Error("invalid varint");
this.assertBounds();
// Result can have 32 bits, convert it to unsigned
return result >>> 0;
}
exports.varint32read = varint32read;
+42
View File
@@ -0,0 +1,42 @@
export { proto3 } from "./proto3.js";
export { proto2 } from "./proto2.js";
export { protoDouble } from "./proto-double.js";
export { protoInt64 } from "./proto-int64.js";
export { protoBase64 } from "./proto-base64.js";
export { protoDelimited } from "./proto-delimited.js";
export { codegenInfo } from "./codegen-info.js";
export { Message } from "./message.js";
export type { AnyMessage, PartialMessage, PlainMessage } from "./message.js";
export { isMessage } from "./is-message.js";
export type { FieldInfo, OneofInfo } from "./field.js";
export type { FieldList } from "./field-list.js";
export { LongType, ScalarType } from "./scalar.js";
export type { ScalarValue } from "./scalar.js";
export type { MessageType } from "./message-type.js";
export type { EnumType, EnumValueInfo } from "./enum.js";
export type { Extension } from "./extension.js";
export { getExtension, setExtension, hasExtension, clearExtension, } from "./extension-accessor.js";
export type { ServiceType, MethodInfo, MethodInfoUnary, MethodInfoServerStreaming, MethodInfoClientStreaming, MethodInfoBiDiStreaming, } from "./service-type.js";
export { MethodKind, MethodIdempotency } from "./service-type.js";
export { WireType, BinaryWriter, BinaryReader } from "./binary-encoding.js";
export type { IBinaryReader, IBinaryWriter } from "./binary-encoding.js";
export type { BinaryFormat, BinaryWriteOptions, BinaryReadOptions, } from "./binary-format.js";
export type { JsonFormat, JsonObject, JsonValue, JsonReadOptions, JsonWriteOptions, JsonWriteStringOptions, } from "./json-format.js";
export type { DescriptorSet, AnyDesc, DescFile, DescEnum, DescEnumValue, DescMessage, DescOneof, DescField, DescService, DescMethod, DescExtension, DescComments, } from "./descriptor-set.js";
export { createDescriptorSet } from "./create-descriptor-set.js";
export type { IMessageTypeRegistry, IExtensionRegistry, } from "./type-registry.js";
export { createRegistry, createMutableRegistry } from "./create-registry.js";
export { createRegistryFromDescriptors } from "./create-registry-from-desc.js";
export { toPlainMessage } from "./to-plain-message.js";
export * from "./google/protobuf/compiler/plugin_pb.js";
export * from "./google/protobuf/api_pb.js";
export * from "./google/protobuf/any_pb.js";
export * from "./google/protobuf/descriptor_pb.js";
export * from "./google/protobuf/duration_pb.js";
export * from "./google/protobuf/empty_pb.js";
export * from "./google/protobuf/field_mask_pb.js";
export * from "./google/protobuf/source_context_pb.js";
export * from "./google/protobuf/struct_pb.js";
export * from "./google/protobuf/timestamp_pb.js";
export * from "./google/protobuf/type_pb.js";
export * from "./google/protobuf/wrappers_pb.js";
+85
View File
@@ -0,0 +1,85 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.toPlainMessage = exports.createRegistryFromDescriptors = exports.createMutableRegistry = exports.createRegistry = exports.createDescriptorSet = exports.BinaryReader = exports.BinaryWriter = exports.WireType = exports.MethodIdempotency = exports.MethodKind = exports.clearExtension = exports.hasExtension = exports.setExtension = exports.getExtension = exports.ScalarType = exports.LongType = exports.isMessage = exports.Message = exports.codegenInfo = exports.protoDelimited = exports.protoBase64 = exports.protoInt64 = exports.protoDouble = exports.proto2 = exports.proto3 = void 0;
var proto3_js_1 = require("./proto3.js");
Object.defineProperty(exports, "proto3", { enumerable: true, get: function () { return proto3_js_1.proto3; } });
var proto2_js_1 = require("./proto2.js");
Object.defineProperty(exports, "proto2", { enumerable: true, get: function () { return proto2_js_1.proto2; } });
var proto_double_js_1 = require("./proto-double.js");
Object.defineProperty(exports, "protoDouble", { enumerable: true, get: function () { return proto_double_js_1.protoDouble; } });
var proto_int64_js_1 = require("./proto-int64.js");
Object.defineProperty(exports, "protoInt64", { enumerable: true, get: function () { return proto_int64_js_1.protoInt64; } });
var proto_base64_js_1 = require("./proto-base64.js");
Object.defineProperty(exports, "protoBase64", { enumerable: true, get: function () { return proto_base64_js_1.protoBase64; } });
var proto_delimited_js_1 = require("./proto-delimited.js");
Object.defineProperty(exports, "protoDelimited", { enumerable: true, get: function () { return proto_delimited_js_1.protoDelimited; } });
var codegen_info_js_1 = require("./codegen-info.js");
Object.defineProperty(exports, "codegenInfo", { enumerable: true, get: function () { return codegen_info_js_1.codegenInfo; } });
var message_js_1 = require("./message.js");
Object.defineProperty(exports, "Message", { enumerable: true, get: function () { return message_js_1.Message; } });
var is_message_js_1 = require("./is-message.js");
Object.defineProperty(exports, "isMessage", { enumerable: true, get: function () { return is_message_js_1.isMessage; } });
var scalar_js_1 = require("./scalar.js");
Object.defineProperty(exports, "LongType", { enumerable: true, get: function () { return scalar_js_1.LongType; } });
Object.defineProperty(exports, "ScalarType", { enumerable: true, get: function () { return scalar_js_1.ScalarType; } });
var extension_accessor_js_1 = require("./extension-accessor.js");
Object.defineProperty(exports, "getExtension", { enumerable: true, get: function () { return extension_accessor_js_1.getExtension; } });
Object.defineProperty(exports, "setExtension", { enumerable: true, get: function () { return extension_accessor_js_1.setExtension; } });
Object.defineProperty(exports, "hasExtension", { enumerable: true, get: function () { return extension_accessor_js_1.hasExtension; } });
Object.defineProperty(exports, "clearExtension", { enumerable: true, get: function () { return extension_accessor_js_1.clearExtension; } });
var service_type_js_1 = require("./service-type.js");
Object.defineProperty(exports, "MethodKind", { enumerable: true, get: function () { return service_type_js_1.MethodKind; } });
Object.defineProperty(exports, "MethodIdempotency", { enumerable: true, get: function () { return service_type_js_1.MethodIdempotency; } });
var binary_encoding_js_1 = require("./binary-encoding.js");
Object.defineProperty(exports, "WireType", { enumerable: true, get: function () { return binary_encoding_js_1.WireType; } });
Object.defineProperty(exports, "BinaryWriter", { enumerable: true, get: function () { return binary_encoding_js_1.BinaryWriter; } });
Object.defineProperty(exports, "BinaryReader", { enumerable: true, get: function () { return binary_encoding_js_1.BinaryReader; } });
var create_descriptor_set_js_1 = require("./create-descriptor-set.js");
Object.defineProperty(exports, "createDescriptorSet", { enumerable: true, get: function () { return create_descriptor_set_js_1.createDescriptorSet; } });
var create_registry_js_1 = require("./create-registry.js");
Object.defineProperty(exports, "createRegistry", { enumerable: true, get: function () { return create_registry_js_1.createRegistry; } });
Object.defineProperty(exports, "createMutableRegistry", { enumerable: true, get: function () { return create_registry_js_1.createMutableRegistry; } });
var create_registry_from_desc_js_1 = require("./create-registry-from-desc.js");
Object.defineProperty(exports, "createRegistryFromDescriptors", { enumerable: true, get: function () { return create_registry_from_desc_js_1.createRegistryFromDescriptors; } });
var to_plain_message_js_1 = require("./to-plain-message.js");
Object.defineProperty(exports, "toPlainMessage", { enumerable: true, get: function () { return to_plain_message_js_1.toPlainMessage; } });
// ideally, we would export these types with sub-path exports:
__exportStar(require("./google/protobuf/compiler/plugin_pb.js"), exports);
__exportStar(require("./google/protobuf/api_pb.js"), exports);
__exportStar(require("./google/protobuf/any_pb.js"), exports);
__exportStar(require("./google/protobuf/descriptor_pb.js"), exports);
__exportStar(require("./google/protobuf/duration_pb.js"), exports);
__exportStar(require("./google/protobuf/empty_pb.js"), exports);
__exportStar(require("./google/protobuf/field_mask_pb.js"), exports);
__exportStar(require("./google/protobuf/source_context_pb.js"), exports);
__exportStar(require("./google/protobuf/struct_pb.js"), exports);
__exportStar(require("./google/protobuf/timestamp_pb.js"), exports);
__exportStar(require("./google/protobuf/type_pb.js"), exports);
__exportStar(require("./google/protobuf/wrappers_pb.js"), exports);
+22
View File
@@ -0,0 +1,22 @@
import type { MessageType } from "./message-type.js";
import type { AnyMessage } from "./message.js";
import { Message } from "./message.js";
/**
* Check whether the given object is any subtype of Message or is a specific
* Message by passing the type.
*
* Just like `instanceof`, `isMessage` narrows the type. The advantage of
* `isMessage` is that it compares identity by the message type name, not by
* class identity. This makes it robust against the dual package hazard and
* similar situations, where the same message is duplicated.
*
* This function is _mostly_ equivalent to the `instanceof` operator. For
* example, `isMessage(foo, MyMessage)` is the same as `foo instanceof MyMessage`,
* and `isMessage(foo)` is the same as `foo instanceof Message`. In most cases,
* `isMessage` should be preferred over `instanceof`.
*
* However, due to the fact that `isMessage` does not use class identity, there
* are subtle differences between this function and `instanceof`. Notably,
* calling `isMessage` on an explicit type of Message will return false.
*/
export declare function isMessage<T extends Message<T> = AnyMessage>(arg: unknown, type?: MessageType<T>): arg is T;
+52
View File
@@ -0,0 +1,52 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.isMessage = void 0;
const message_js_1 = require("./message.js");
/**
* Check whether the given object is any subtype of Message or is a specific
* Message by passing the type.
*
* Just like `instanceof`, `isMessage` narrows the type. The advantage of
* `isMessage` is that it compares identity by the message type name, not by
* class identity. This makes it robust against the dual package hazard and
* similar situations, where the same message is duplicated.
*
* This function is _mostly_ equivalent to the `instanceof` operator. For
* example, `isMessage(foo, MyMessage)` is the same as `foo instanceof MyMessage`,
* and `isMessage(foo)` is the same as `foo instanceof Message`. In most cases,
* `isMessage` should be preferred over `instanceof`.
*
* However, due to the fact that `isMessage` does not use class identity, there
* are subtle differences between this function and `instanceof`. Notably,
* calling `isMessage` on an explicit type of Message will return false.
*/
function isMessage(arg, type) {
if (arg === null || typeof arg != "object") {
return false;
}
if (!Object.getOwnPropertyNames(message_js_1.Message.prototype).every((m) => m in arg && typeof arg[m] == "function")) {
return false;
}
const actualType = arg.getType();
if (actualType === null ||
typeof actualType != "function" ||
!("typeName" in actualType) ||
typeof actualType.typeName != "string") {
return false;
}
return type === undefined ? true : actualType.typeName == type.typeName;
}
exports.isMessage = isMessage;
+111
View File
@@ -0,0 +1,111 @@
import type { Message } from "./message.js";
import type { MessageType } from "./message-type.js";
import type { ScalarType, LongType } from "./scalar.js";
import type { IExtensionRegistry, IMessageTypeRegistry } from "./type-registry.js";
/**
* JsonFormat is the contract for serializing messages to and from JSON.
* Implementations may be specific to a proto syntax, and can be reflection
* based, or delegate to speed optimized generated code.
*/
export interface JsonFormat {
/**
* Provide options for parsing JSON data.
*/
makeReadOptions(options?: Partial<JsonReadOptions>): Readonly<JsonReadOptions>;
/**
* Provide options for serializing to JSON.
*/
makeWriteOptions(options?: Partial<JsonWriteStringOptions>): Readonly<JsonWriteStringOptions>;
/**
* Parse a message from JSON.
*/
readMessage<T extends Message<T>>(type: MessageType<T>, jsonValue: JsonValue, options: JsonReadOptions, message?: T): T;
/**
* Serialize a message to JSON.
*/
writeMessage(message: Message, options: JsonWriteOptions): JsonValue;
/**
* Parse a single scalar value from JSON.
*
* This method may throw an error, but it may have a blank error message.
* Callers are expected to provide context.
*/
readScalar(type: ScalarType, json: JsonValue, longType?: LongType): any;
/**
* Serialize a single scalar value to JSON.
*/
writeScalar(type: ScalarType, value: any, emitDefaultValues: boolean): JsonValue | undefined;
/**
* Returns a short string representation of a JSON value, suitable for error messages.
*/
debug(json: JsonValue): string;
}
/**
* Options for parsing JSON data.
*/
export interface JsonReadOptions {
/**
* Ignore unknown fields: Proto3 JSON parser should reject unknown fields
* by default. This option ignores unknown fields in parsing, as well as
* unrecognized enum string representations.
*/
ignoreUnknownFields: boolean;
/**
* This option is required to read `google.protobuf.Any` and extensions
* from JSON format.
*/
typeRegistry?: IMessageTypeRegistry & Partial<IExtensionRegistry>;
}
/**
* Options for serializing to JSON.
*/
export interface JsonWriteOptions {
/**
* Emit fields with default values: Fields with default values are omitted
* by default in proto3 JSON output. This option overrides this behavior
* and outputs fields with their default values.
*/
emitDefaultValues: boolean;
/**
* Emit enum values as integers instead of strings: The name of an enum
* value is used by default in JSON output. An option may be provided to
* use the numeric value of the enum value instead.
*/
enumAsInteger: boolean;
/**
* Use proto field name instead of lowerCamelCase name: By default proto3
* JSON printer should convert the field name to lowerCamelCase and use
* that as the JSON name. An implementation may provide an option to use
* proto field name as the JSON name instead. Proto3 JSON parsers are
* required to accept both the converted lowerCamelCase name and the proto
* field name.
*/
useProtoFieldName: boolean;
/**
* This option is required to write `google.protobuf.Any` and extensions
* to JSON format.
*/
typeRegistry?: IMessageTypeRegistry & Partial<IExtensionRegistry>;
}
/**
* Options for serializing to JSON.
*/
export interface JsonWriteStringOptions extends JsonWriteOptions {
prettySpaces: number;
}
/**
* Represents any possible JSON value:
* - number
* - string
* - boolean
* - null
* - object (with any JSON value as property)
* - array (with any JSON value as element)
*/
export type JsonValue = number | string | boolean | null | JsonObject | JsonValue[];
/**
* Represents a JSON object.
*/
export type JsonObject = {
[k: string]: JsonValue;
};
+15
View File
@@ -0,0 +1,15 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
+51
View File
@@ -0,0 +1,51 @@
import type { FieldList } from "./field-list.js";
import type { ProtoRuntime } from "./private/proto-runtime.js";
import type { JsonReadOptions, JsonValue } from "./json-format.js";
import type { BinaryReadOptions } from "./binary-format.js";
import type { AnyMessage, Message, PartialMessage, PlainMessage } from "./message.js";
import type { FieldWrapper } from "./private/field-wrapper.js";
/**
* MessageType represents a protobuf message. It provides:
* - a constructor that produces an instance of the message
* - metadata for reflection-based operations
* - common functionality like serialization
*/
export interface MessageType<T extends Message<T> = AnyMessage> {
/**
* Create a new instance of this type.
*/
new (data?: PartialMessage<T>): T;
/**
* The fully qualified name of the message.
*/
readonly typeName: string;
/**
* Field metadata.
*/
readonly fields: FieldList;
/**
* Provides serialization and other functionality.
*/
readonly runtime: ProtoRuntime;
/**
* When used as a field, unwrap this message to a simple value.
*/
readonly fieldWrapper?: FieldWrapper<T>;
/**
* Parse serialized binary data.
*/
fromBinary(data: Uint8Array, options?: Partial<BinaryReadOptions>): T;
/**
* Parse a JSON object.
*/
fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): T;
/**
* Parse a JSON string.
*/
fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): T;
/**
* Returns true if the given arguments have equal field values, recursively.
* Will also return true if both messages are `undefined` or `null`.
*/
equals(a: T | PlainMessage<T> | undefined | null, b: T | PlainMessage<T> | undefined | null): boolean;
}
+15
View File
@@ -0,0 +1,15 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
+131
View File
@@ -0,0 +1,131 @@
import type { BinaryReadOptions, BinaryWriteOptions } from "./binary-format.js";
import type { JsonReadOptions, JsonValue, JsonWriteOptions, JsonWriteStringOptions } from "./json-format.js";
import type { MessageType } from "./message-type.js";
/**
* AnyMessage is an interface implemented by all messages. If you need to
* handle messages of unknown type, this interface provides a convenient
* index signature to access fields with message["fieldname"].
*/
export interface AnyMessage extends Message<AnyMessage> {
[k: string]: any;
}
/**
* Message is the base class of every message, generated, or created at
* runtime.
*
* It is _not_ safe to extend this class. If you want to create a message at
* run time, use proto3.makeMessageType().
*/
export declare class Message<T extends Message<T> = AnyMessage> {
/**
* Compare with a message of the same type.
* Note that this function disregards extensions and unknown fields.
*/
equals(other: T | PlainMessage<T> | undefined | null): boolean;
/**
* Create a deep copy.
*/
clone(): T;
/**
* Parse from binary data, merging fields.
*
* Repeated fields are appended. Map entries are added, overwriting
* existing keys.
*
* If a message field is already present, it will be merged with the
* new data.
*/
fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): this;
/**
* Parse a message from a JSON value.
*/
fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): this;
/**
* Parse a message from a JSON string.
*/
fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): this;
/**
* Serialize the message to binary data.
*/
toBinary(options?: Partial<BinaryWriteOptions>): Uint8Array;
/**
* Serialize the message to a JSON value, a JavaScript value that can be
* passed to JSON.stringify().
*/
toJson(options?: Partial<JsonWriteOptions>): JsonValue;
/**
* Serialize the message to a JSON string.
*/
toJsonString(options?: Partial<JsonWriteStringOptions>): string;
/**
* Override for serialization behavior. This will be invoked when calling
* JSON.stringify on this message (i.e. JSON.stringify(msg)).
*
* Note that this will not serialize google.protobuf.Any with a packed
* message because the protobuf JSON format specifies that it needs to be
* unpacked, and this is only possible with a type registry to look up the
* message type. As a result, attempting to serialize a message with this
* type will throw an Error.
*
* This method is protected because you should not need to invoke it
* directly -- instead use JSON.stringify or toJsonString for
* stringified JSON. Alternatively, if actual JSON is desired, you should
* use toJson.
*/
protected toJSON(): JsonValue;
/**
* Retrieve the MessageType of this message - a singleton that represents
* the protobuf message declaration and provides metadata for reflection-
* based operations.
*/
getType(): MessageType<T>;
}
/**
* PlainMessage<T> strips all methods from a message, leaving only fields
* and oneof groups. It is recursive, meaning it applies this same logic to all
* nested message fields as well.
*/
export type PlainMessage<T extends Message<T>> = {
[P in keyof T as T[P] extends Function ? never : P]: PlainField<T[P]>;
};
type PlainField<F> = F extends (Date | Uint8Array | bigint | boolean | string | number) ? F : F extends Array<infer U> ? Array<PlainField<U>> : F extends ReadonlyArray<infer U> ? ReadonlyArray<PlainField<U>> : F extends Message<infer U> ? PlainMessage<U> : F extends OneofSelectedMessage<infer C, infer V> ? {
case: C;
value: PlainField<V>;
} : F extends {
case: string | undefined;
value?: unknown;
} ? F : F extends {
[key: string | number]: Message<infer U>;
} ? {
[key: string | number]: PlainField<U>;
} : F;
/**
* PartialMessage<T> constructs a type from a message. The resulting type
* only contains the protobuf field members of the message, and all of them
* are optional.
*
* Note that the optionality of the fields is the only difference between
* PartialMessage and PlainMessage.
*
* PartialMessage is similar to the built-in type Partial<T>, but recursive,
* and respects `oneof` groups.
*/
export type PartialMessage<T extends Message<T>> = {
[P in keyof T as T[P] extends Function ? never : P]?: PartialField<T[P]>;
};
type PartialField<F> = F extends (Date | Uint8Array | bigint | boolean | string | number) ? F : F extends Array<infer U> ? Array<PartialField<U>> : F extends ReadonlyArray<infer U> ? ReadonlyArray<PartialField<U>> : F extends Message<infer U> ? PartialMessage<U> : F extends OneofSelectedMessage<infer C, infer V> ? {
case: C;
value: PartialMessage<V>;
} : F extends {
case: string | undefined;
value?: unknown;
} ? F : F extends {
[key: string | number]: Message<infer U>;
} ? {
[key: string | number]: PartialMessage<U>;
} : F;
type OneofSelectedMessage<K extends string, M extends Message<M>> = {
case: K;
value: M;
};
export {};
+129
View File
@@ -0,0 +1,129 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.Message = void 0;
/**
* Message is the base class of every message, generated, or created at
* runtime.
*
* It is _not_ safe to extend this class. If you want to create a message at
* run time, use proto3.makeMessageType().
*/
class Message {
/**
* Compare with a message of the same type.
* Note that this function disregards extensions and unknown fields.
*/
equals(other) {
return this.getType().runtime.util.equals(this.getType(), this, other);
}
/**
* Create a deep copy.
*/
clone() {
return this.getType().runtime.util.clone(this);
}
/**
* Parse from binary data, merging fields.
*
* Repeated fields are appended. Map entries are added, overwriting
* existing keys.
*
* If a message field is already present, it will be merged with the
* new data.
*/
fromBinary(bytes, options) {
const type = this.getType(), format = type.runtime.bin, opt = format.makeReadOptions(options);
format.readMessage(this, opt.readerFactory(bytes), bytes.byteLength, opt);
return this;
}
/**
* Parse a message from a JSON value.
*/
fromJson(jsonValue, options) {
const type = this.getType(), format = type.runtime.json, opt = format.makeReadOptions(options);
format.readMessage(type, jsonValue, opt, this);
return this;
}
/**
* Parse a message from a JSON string.
*/
fromJsonString(jsonString, options) {
let json;
try {
json = JSON.parse(jsonString);
}
catch (e) {
throw new Error(`cannot decode ${this.getType().typeName} from JSON: ${e instanceof Error ? e.message : String(e)}`);
}
return this.fromJson(json, options);
}
/**
* Serialize the message to binary data.
*/
toBinary(options) {
const type = this.getType(), bin = type.runtime.bin, opt = bin.makeWriteOptions(options), writer = opt.writerFactory();
bin.writeMessage(this, writer, opt);
return writer.finish();
}
/**
* Serialize the message to a JSON value, a JavaScript value that can be
* passed to JSON.stringify().
*/
toJson(options) {
const type = this.getType(), json = type.runtime.json, opt = json.makeWriteOptions(options);
return json.writeMessage(this, opt);
}
/**
* Serialize the message to a JSON string.
*/
toJsonString(options) {
var _a;
const value = this.toJson(options);
return JSON.stringify(value, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0);
}
/**
* Override for serialization behavior. This will be invoked when calling
* JSON.stringify on this message (i.e. JSON.stringify(msg)).
*
* Note that this will not serialize google.protobuf.Any with a packed
* message because the protobuf JSON format specifies that it needs to be
* unpacked, and this is only possible with a type registry to look up the
* message type. As a result, attempting to serialize a message with this
* type will throw an Error.
*
* This method is protected because you should not need to invoke it
* directly -- instead use JSON.stringify or toJsonString for
* stringified JSON. Alternatively, if actual JSON is desired, you should
* use toJson.
*/
toJSON() {
return this.toJson({
emitDefaultValues: true,
});
}
/**
* Retrieve the MessageType of this message - a singleton that represents
* the protobuf message declaration and provides metadata for reflection-
* based operations.
*/
getType() {
// Any class that extends Message _must_ provide a complete static
// implementation of MessageType.
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-return
return Object.getPrototypeOf(this).constructor;
}
}
exports.Message = Message;
+1
View File
@@ -0,0 +1 @@
{"type":"commonjs"}
+16
View File
@@ -0,0 +1,16 @@
/**
* Assert that condition is truthy or throw error (with message)
*/
export declare function assert(condition: unknown, msg?: string): asserts condition;
/**
* Assert a valid signed protobuf 32-bit integer.
*/
export declare function assertInt32(arg: unknown): asserts arg is number;
/**
* Assert a valid unsigned protobuf 32-bit integer.
*/
export declare function assertUInt32(arg: unknown): asserts arg is number;
/**
* Assert a valid protobuf float value.
*/
export declare function assertFloat32(arg: unknown): asserts arg is number;
+59
View File
@@ -0,0 +1,59 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.assertFloat32 = exports.assertUInt32 = exports.assertInt32 = exports.assert = void 0;
/**
* Assert that condition is truthy or throw error (with message)
*/
function assert(condition, msg) {
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions -- we want the implicit conversion to boolean
if (!condition) {
throw new Error(msg);
}
}
exports.assert = assert;
const FLOAT32_MAX = 3.4028234663852886e38, FLOAT32_MIN = -3.4028234663852886e38, UINT32_MAX = 0xffffffff, INT32_MAX = 0x7fffffff, INT32_MIN = -0x80000000;
/**
* Assert a valid signed protobuf 32-bit integer.
*/
function assertInt32(arg) {
if (typeof arg !== "number")
throw new Error("invalid int 32: " + typeof arg);
if (!Number.isInteger(arg) || arg > INT32_MAX || arg < INT32_MIN)
throw new Error("invalid int 32: " + arg); // eslint-disable-line @typescript-eslint/restrict-plus-operands -- we want the implicit conversion to string
}
exports.assertInt32 = assertInt32;
/**
* Assert a valid unsigned protobuf 32-bit integer.
*/
function assertUInt32(arg) {
if (typeof arg !== "number")
throw new Error("invalid uint 32: " + typeof arg);
if (!Number.isInteger(arg) || arg > UINT32_MAX || arg < 0)
throw new Error("invalid uint 32: " + arg); // eslint-disable-line @typescript-eslint/restrict-plus-operands -- we want the implicit conversion to string
}
exports.assertUInt32 = assertUInt32;
/**
* Assert a valid protobuf float value.
*/
function assertFloat32(arg) {
if (typeof arg !== "number")
throw new Error("invalid float 32: " + typeof arg);
if (!Number.isFinite(arg))
return;
if (arg > FLOAT32_MAX || arg < FLOAT32_MIN)
throw new Error("invalid float 32: " + arg); // eslint-disable-line @typescript-eslint/restrict-plus-operands -- we want the implicit conversion to string
}
exports.assertFloat32 = assertFloat32;
+7
View File
@@ -0,0 +1,7 @@
import type { IBinaryWriter } from "../binary-encoding.js";
import type { BinaryFormat, BinaryWriteOptions } from "../binary-format.js";
import type { FieldInfo } from "../field.js";
export declare function makeBinaryFormat(): BinaryFormat;
export declare function writeMapEntry(writer: IBinaryWriter, options: BinaryWriteOptions, field: FieldInfo & {
kind: "map";
}, key: string, value: any): void;
+431
View File
@@ -0,0 +1,431 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.writeMapEntry = exports.makeBinaryFormat = void 0;
const binary_encoding_js_1 = require("../binary-encoding.js");
const field_wrapper_js_1 = require("./field-wrapper.js");
const scalars_js_1 = require("./scalars.js");
const assert_js_1 = require("./assert.js");
const reflect_js_1 = require("./reflect.js");
const scalar_js_1 = require("../scalar.js");
const is_message_js_1 = require("../is-message.js");
/* eslint-disable prefer-const,no-case-declarations,@typescript-eslint/no-explicit-any,@typescript-eslint/no-unsafe-argument,@typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-return */
const unknownFieldsSymbol = Symbol("@bufbuild/protobuf/unknown-fields");
// Default options for parsing binary data.
const readDefaults = {
readUnknownFields: true,
readerFactory: (bytes) => new binary_encoding_js_1.BinaryReader(bytes),
};
// Default options for serializing binary data.
const writeDefaults = {
writeUnknownFields: true,
writerFactory: () => new binary_encoding_js_1.BinaryWriter(),
};
function makeReadOptions(options) {
return options ? Object.assign(Object.assign({}, readDefaults), options) : readDefaults;
}
function makeWriteOptions(options) {
return options ? Object.assign(Object.assign({}, writeDefaults), options) : writeDefaults;
}
function makeBinaryFormat() {
return {
makeReadOptions,
makeWriteOptions,
listUnknownFields(message) {
var _a;
return (_a = message[unknownFieldsSymbol]) !== null && _a !== void 0 ? _a : [];
},
discardUnknownFields(message) {
delete message[unknownFieldsSymbol];
},
writeUnknownFields(message, writer) {
const m = message;
const c = m[unknownFieldsSymbol];
if (c) {
for (const f of c) {
writer.tag(f.no, f.wireType).raw(f.data);
}
}
},
onUnknownField(message, no, wireType, data) {
const m = message;
if (!Array.isArray(m[unknownFieldsSymbol])) {
m[unknownFieldsSymbol] = [];
}
m[unknownFieldsSymbol].push({ no, wireType, data });
},
readMessage(message, reader, lengthOrEndTagFieldNo, options, delimitedMessageEncoding) {
const type = message.getType();
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
const end = delimitedMessageEncoding
? reader.len
: reader.pos + lengthOrEndTagFieldNo;
let fieldNo, wireType;
while (reader.pos < end) {
[fieldNo, wireType] = reader.tag();
if (delimitedMessageEncoding === true &&
wireType == binary_encoding_js_1.WireType.EndGroup) {
break;
}
const field = type.fields.find(fieldNo);
if (!field) {
const data = reader.skip(wireType, fieldNo);
if (options.readUnknownFields) {
this.onUnknownField(message, fieldNo, wireType, data);
}
continue;
}
readField(message, reader, field, wireType, options);
}
if (delimitedMessageEncoding && // eslint-disable-line @typescript-eslint/strict-boolean-expressions
(wireType != binary_encoding_js_1.WireType.EndGroup || fieldNo !== lengthOrEndTagFieldNo)) {
throw new Error(`invalid end group tag`);
}
},
readField,
writeMessage(message, writer, options) {
const type = message.getType();
for (const field of type.fields.byNumber()) {
if (!(0, reflect_js_1.isFieldSet)(field, message)) {
if (field.req) {
throw new Error(`cannot encode field ${type.typeName}.${field.name} to binary: required field not set`);
}
continue;
}
const value = field.oneof
? message[field.oneof.localName].value
: message[field.localName];
writeField(field, value, writer, options);
}
if (options.writeUnknownFields) {
this.writeUnknownFields(message, writer);
}
return writer;
},
writeField(field, value, writer, options) {
// The behavior of our internal function has changed, it does no longer
// accept `undefined` values for singular scalar and map.
// For backwards-compatibility, we support the old form that is part of
// the public API through the interface BinaryFormat.
if (value === undefined) {
return undefined;
}
writeField(field, value, writer, options);
},
};
}
exports.makeBinaryFormat = makeBinaryFormat;
function readField(target, // eslint-disable-line @typescript-eslint/no-explicit-any -- `any` is the best choice for dynamic access
reader, field, wireType, options) {
let { repeated, localName } = field;
if (field.oneof) {
target = target[field.oneof.localName];
if (target.case != localName) {
delete target.value;
}
target.case = localName;
localName = "value";
}
switch (field.kind) {
case "scalar":
case "enum":
const scalarType = field.kind == "enum" ? scalar_js_1.ScalarType.INT32 : field.T;
let read = readScalar;
// eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison -- acceptable since it's covered by tests
if (field.kind == "scalar" && field.L > 0) {
read = readScalarLTString;
}
if (repeated) {
let arr = target[localName]; // safe to assume presence of array, oneof cannot contain repeated values
const isPacked = wireType == binary_encoding_js_1.WireType.LengthDelimited &&
scalarType != scalar_js_1.ScalarType.STRING &&
scalarType != scalar_js_1.ScalarType.BYTES;
if (isPacked) {
let e = reader.uint32() + reader.pos;
while (reader.pos < e) {
arr.push(read(reader, scalarType));
}
}
else {
arr.push(read(reader, scalarType));
}
}
else {
target[localName] = read(reader, scalarType);
}
break;
case "message":
const messageType = field.T;
if (repeated) {
// safe to assume presence of array, oneof cannot contain repeated values
target[localName].push(readMessageField(reader, new messageType(), options, field));
}
else {
if ((0, is_message_js_1.isMessage)(target[localName])) {
readMessageField(reader, target[localName], options, field);
}
else {
target[localName] = readMessageField(reader, new messageType(), options, field);
if (messageType.fieldWrapper && !field.oneof && !field.repeated) {
target[localName] = messageType.fieldWrapper.unwrapField(target[localName]);
}
}
}
break;
case "map":
let [mapKey, mapVal] = readMapEntry(field, reader, options);
// safe to assume presence of map object, oneof cannot contain repeated values
target[localName][mapKey] = mapVal;
break;
}
}
// Read a message, avoiding MessageType.fromBinary() to re-use the
// BinaryReadOptions and the IBinaryReader.
function readMessageField(reader, message, options, field) {
const format = message.getType().runtime.bin;
const delimited = field === null || field === void 0 ? void 0 : field.delimited;
format.readMessage(message, reader, delimited ? field.no : reader.uint32(), // eslint-disable-line @typescript-eslint/strict-boolean-expressions
options, delimited);
return message;
}
// Read a map field, expecting key field = 1, value field = 2
function readMapEntry(field, reader, options) {
const length = reader.uint32(), end = reader.pos + length;
let key, val;
while (reader.pos < end) {
const [fieldNo] = reader.tag();
switch (fieldNo) {
case 1:
key = readScalar(reader, field.K);
break;
case 2:
switch (field.V.kind) {
case "scalar":
val = readScalar(reader, field.V.T);
break;
case "enum":
val = reader.int32();
break;
case "message":
val = readMessageField(reader, new field.V.T(), options, undefined);
break;
}
break;
}
}
if (key === undefined) {
key = (0, scalars_js_1.scalarZeroValue)(field.K, scalar_js_1.LongType.BIGINT);
}
if (typeof key != "string" && typeof key != "number") {
key = key.toString();
}
if (val === undefined) {
switch (field.V.kind) {
case "scalar":
val = (0, scalars_js_1.scalarZeroValue)(field.V.T, scalar_js_1.LongType.BIGINT);
break;
case "enum":
val = field.V.T.values[0].no;
break;
case "message":
val = new field.V.T();
break;
}
}
return [key, val];
}
// Read a scalar value, but return 64 bit integral types (int64, uint64,
// sint64, fixed64, sfixed64) as string instead of bigint.
function readScalarLTString(reader, type) {
const v = readScalar(reader, type);
return typeof v == "bigint" ? v.toString() : v;
}
// Does not use scalarTypeInfo() for better performance.
function readScalar(reader, type) {
switch (type) {
case scalar_js_1.ScalarType.STRING:
return reader.string();
case scalar_js_1.ScalarType.BOOL:
return reader.bool();
case scalar_js_1.ScalarType.DOUBLE:
return reader.double();
case scalar_js_1.ScalarType.FLOAT:
return reader.float();
case scalar_js_1.ScalarType.INT32:
return reader.int32();
case scalar_js_1.ScalarType.INT64:
return reader.int64();
case scalar_js_1.ScalarType.UINT64:
return reader.uint64();
case scalar_js_1.ScalarType.FIXED64:
return reader.fixed64();
case scalar_js_1.ScalarType.BYTES:
return reader.bytes();
case scalar_js_1.ScalarType.FIXED32:
return reader.fixed32();
case scalar_js_1.ScalarType.SFIXED32:
return reader.sfixed32();
case scalar_js_1.ScalarType.SFIXED64:
return reader.sfixed64();
case scalar_js_1.ScalarType.SINT64:
return reader.sint64();
case scalar_js_1.ScalarType.UINT32:
return reader.uint32();
case scalar_js_1.ScalarType.SINT32:
return reader.sint32();
}
}
function writeField(field, value, writer, options) {
(0, assert_js_1.assert)(value !== undefined);
const repeated = field.repeated;
switch (field.kind) {
case "scalar":
case "enum":
let scalarType = field.kind == "enum" ? scalar_js_1.ScalarType.INT32 : field.T;
if (repeated) {
(0, assert_js_1.assert)(Array.isArray(value));
if (field.packed) {
writePacked(writer, scalarType, field.no, value);
}
else {
for (const item of value) {
writeScalar(writer, scalarType, field.no, item);
}
}
}
else {
writeScalar(writer, scalarType, field.no, value);
}
break;
case "message":
if (repeated) {
(0, assert_js_1.assert)(Array.isArray(value));
for (const item of value) {
writeMessageField(writer, options, field, item);
}
}
else {
writeMessageField(writer, options, field, value);
}
break;
case "map":
(0, assert_js_1.assert)(typeof value == "object" && value != null);
for (const [key, val] of Object.entries(value)) {
writeMapEntry(writer, options, field, key, val);
}
break;
}
}
function writeMapEntry(writer, options, field, key, value) {
writer.tag(field.no, binary_encoding_js_1.WireType.LengthDelimited);
writer.fork();
// javascript only allows number or string for object properties
// we convert from our representation to the protobuf type
let keyValue = key;
// eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check -- we deliberately handle just the special cases for map keys
switch (field.K) {
case scalar_js_1.ScalarType.INT32:
case scalar_js_1.ScalarType.FIXED32:
case scalar_js_1.ScalarType.UINT32:
case scalar_js_1.ScalarType.SFIXED32:
case scalar_js_1.ScalarType.SINT32:
keyValue = Number.parseInt(key);
break;
case scalar_js_1.ScalarType.BOOL:
(0, assert_js_1.assert)(key == "true" || key == "false");
keyValue = key == "true";
break;
}
// write key, expecting key field number = 1
writeScalar(writer, field.K, 1, keyValue);
// write value, expecting value field number = 2
switch (field.V.kind) {
case "scalar":
writeScalar(writer, field.V.T, 2, value);
break;
case "enum":
writeScalar(writer, scalar_js_1.ScalarType.INT32, 2, value);
break;
case "message":
(0, assert_js_1.assert)(value !== undefined);
writer.tag(2, binary_encoding_js_1.WireType.LengthDelimited).bytes(value.toBinary(options));
break;
}
writer.join();
}
exports.writeMapEntry = writeMapEntry;
// Value must not be undefined
function writeMessageField(writer, options, field, value) {
const message = (0, field_wrapper_js_1.wrapField)(field.T, value);
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
if (field.delimited)
writer
.tag(field.no, binary_encoding_js_1.WireType.StartGroup)
.raw(message.toBinary(options))
.tag(field.no, binary_encoding_js_1.WireType.EndGroup);
else
writer
.tag(field.no, binary_encoding_js_1.WireType.LengthDelimited)
.bytes(message.toBinary(options));
}
function writeScalar(writer, type, fieldNo, value) {
(0, assert_js_1.assert)(value !== undefined);
let [wireType, method] = scalarTypeInfo(type);
writer.tag(fieldNo, wireType)[method](value);
}
function writePacked(writer, type, fieldNo, value) {
if (!value.length) {
return;
}
writer.tag(fieldNo, binary_encoding_js_1.WireType.LengthDelimited).fork();
let [, method] = scalarTypeInfo(type);
for (let i = 0; i < value.length; i++) {
writer[method](value[i]);
}
writer.join();
}
/**
* Get information for writing a scalar value.
*
* Returns tuple:
* [0]: appropriate WireType
* [1]: name of the appropriate method of IBinaryWriter
* [2]: whether the given value is a default value for proto3 semantics
*
* If argument `value` is omitted, [2] is always false.
*/
// TODO replace call-sites writeScalar() and writePacked(), then remove
function scalarTypeInfo(type) {
let wireType = binary_encoding_js_1.WireType.Varint;
// eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check -- INT32, UINT32, SINT32 are covered by the defaults
switch (type) {
case scalar_js_1.ScalarType.BYTES:
case scalar_js_1.ScalarType.STRING:
wireType = binary_encoding_js_1.WireType.LengthDelimited;
break;
case scalar_js_1.ScalarType.DOUBLE:
case scalar_js_1.ScalarType.FIXED64:
case scalar_js_1.ScalarType.SFIXED64:
wireType = binary_encoding_js_1.WireType.Bit64;
break;
case scalar_js_1.ScalarType.FIXED32:
case scalar_js_1.ScalarType.SFIXED32:
case scalar_js_1.ScalarType.FLOAT:
wireType = binary_encoding_js_1.WireType.Bit32;
break;
}
const method = scalar_js_1.ScalarType[type].toLowerCase();
return [wireType, method];
}
+27
View File
@@ -0,0 +1,27 @@
import type { EnumType, EnumValueInfo } from "../enum.js";
/**
* Represents a generated enum.
*/
export interface EnumObject {
[key: number]: string;
[k: string]: number | string;
}
/**
* Get reflection information from a generated enum.
* If this function is called on something other than a generated
* enum, it raises an error.
*/
export declare function getEnumType(enumObject: EnumObject): EnumType;
/**
* Sets reflection information on a generated enum.
*/
export declare function setEnumType(enumObject: EnumObject, typeName: string, values: Omit<EnumValueInfo, "localName">[], opt?: {}): void;
/**
* Create a new EnumType with the given values.
*/
export declare function makeEnumType(typeName: string, values: (EnumValueInfo | Omit<EnumValueInfo, "localName">)[], _opt?: {}): EnumType;
/**
* Create a new enum object with the given values.
* Sets reflection information.
*/
export declare function makeEnum(typeName: string, values: (EnumValueInfo | Omit<EnumValueInfo, "localName">)[], opt?: {}): EnumObject;
+94
View File
@@ -0,0 +1,94 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeEnum = exports.makeEnumType = exports.setEnumType = exports.getEnumType = void 0;
const assert_js_1 = require("./assert.js");
const enumTypeSymbol = Symbol("@bufbuild/protobuf/enum-type");
/**
* Get reflection information from a generated enum.
* If this function is called on something other than a generated
* enum, it raises an error.
*/
function getEnumType(enumObject) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-explicit-any
const t = enumObject[enumTypeSymbol];
(0, assert_js_1.assert)(t, "missing enum type on enum object");
return t; // eslint-disable-line @typescript-eslint/no-unsafe-return
}
exports.getEnumType = getEnumType;
/**
* Sets reflection information on a generated enum.
*/
function setEnumType(enumObject, typeName, values, opt) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
enumObject[enumTypeSymbol] = makeEnumType(typeName, values.map((v) => ({
no: v.no,
name: v.name,
localName: enumObject[v.no],
})), opt);
}
exports.setEnumType = setEnumType;
/**
* Create a new EnumType with the given values.
*/
function makeEnumType(typeName, values,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_opt) {
const names = Object.create(null);
const numbers = Object.create(null);
const normalValues = [];
for (const value of values) {
// We do not surface options at this time
// const value: EnumValueInfo = {...v, options: v.options ?? emptyReadonlyObject};
const n = normalizeEnumValue(value);
normalValues.push(n);
names[value.name] = n;
numbers[value.no] = n;
}
return {
typeName,
values: normalValues,
// We do not surface options at this time
// options: opt?.options ?? Object.create(null),
findName(name) {
return names[name];
},
findNumber(no) {
return numbers[no];
},
};
}
exports.makeEnumType = makeEnumType;
/**
* Create a new enum object with the given values.
* Sets reflection information.
*/
function makeEnum(typeName, values, opt) {
const enumObject = {};
for (const value of values) {
const n = normalizeEnumValue(value);
enumObject[n.localName] = n.no;
enumObject[n.no] = n.localName;
}
setEnumType(enumObject, typeName, values, opt);
return enumObject;
}
exports.makeEnum = makeEnum;
function normalizeEnumValue(value) {
if ("localName" in value) {
return value;
}
return Object.assign(Object.assign({}, value), { localName: value.name });
}
+34
View File
@@ -0,0 +1,34 @@
import type { Extension } from "../extension.js";
import type { AnyMessage, Message } from "../message.js";
import type { FieldInfo, OneofInfo, PartialFieldInfo } from "../field.js";
import { WireType } from "../binary-encoding.js";
import type { ProtoRuntime } from "./proto-runtime.js";
import type { MessageType } from "../message-type.js";
export type ExtensionFieldSource = extensionFieldRules<FieldInfo> | extensionFieldRules<PartialFieldInfo> | (() => extensionFieldRules<FieldInfo>) | (() => extensionFieldRules<PartialFieldInfo>);
type extensionFieldRules<T extends FieldInfo | PartialFieldInfo> = T extends {
kind: "map";
} ? never : T extends {
oneof: string;
} ? never : T extends {
oneof: OneofInfo;
} ? never : Omit<T, "name"> & Partial<Pick<T, "name">>;
/**
* Create a new extension using the given runtime.
*/
export declare function makeExtension<E extends Message<E> = AnyMessage, V = unknown>(runtime: ProtoRuntime, typeName: string, extendee: MessageType<E>, field: ExtensionFieldSource): Extension<E, V>;
/**
* Create a container that allows us to read extension fields into it with the
* same logic as regular fields.
*/
export declare function createExtensionContainer<E extends Message<E> = AnyMessage, V = unknown>(extension: Extension<E, V>): [Record<string, V>, () => V];
type UnknownField = {
no: number;
wireType: WireType;
data: Uint8Array;
};
type UnknownFields = ReadonlyArray<UnknownField>;
/**
* Helper to filter unknown fields, optimized based on field type.
*/
export declare function filterUnknownFields(unknownFields: UnknownFields, field: Pick<FieldInfo, "no" | "kind" | "repeated">): UnknownField[];
export {};
+86
View File
@@ -0,0 +1,86 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.filterUnknownFields = exports.createExtensionContainer = exports.makeExtension = void 0;
const scalars_js_1 = require("./scalars.js");
/**
* Create a new extension using the given runtime.
*/
function makeExtension(runtime, typeName, extendee, field) {
let fi;
return {
typeName,
extendee,
get field() {
if (!fi) {
const i = (typeof field == "function" ? field() : field);
i.name = typeName.split(".").pop();
i.jsonName = `[${typeName}]`;
fi = runtime.util.newFieldList([i]).list()[0];
}
return fi;
},
runtime,
};
}
exports.makeExtension = makeExtension;
/**
* Create a container that allows us to read extension fields into it with the
* same logic as regular fields.
*/
function createExtensionContainer(extension) {
const localName = extension.field.localName;
const container = Object.create(null);
container[localName] = initExtensionField(extension);
return [container, () => container[localName]];
}
exports.createExtensionContainer = createExtensionContainer;
function initExtensionField(ext) {
const field = ext.field;
if (field.repeated) {
return [];
}
if (field.default !== undefined) {
return field.default;
}
switch (field.kind) {
case "enum":
return field.T.values[0].no;
case "scalar":
return (0, scalars_js_1.scalarZeroValue)(field.T, field.L);
case "message":
// eslint-disable-next-line no-case-declarations
const T = field.T, value = new T();
return T.fieldWrapper ? T.fieldWrapper.unwrapField(value) : value;
case "map":
throw "map fields are not allowed to be extensions";
}
}
/**
* Helper to filter unknown fields, optimized based on field type.
*/
function filterUnknownFields(unknownFields, field) {
if (!field.repeated && (field.kind == "enum" || field.kind == "scalar")) {
// singular scalar fields do not merge, we pick the last
for (let i = unknownFields.length - 1; i >= 0; --i) {
if (unknownFields[i].no == field.no) {
return [unknownFields[i]];
}
}
return [];
}
return unknownFields.filter((uf) => uf.no === field.no);
}
exports.filterUnknownFields = filterUnknownFields;
+19
View File
@@ -0,0 +1,19 @@
import { Edition, FeatureSet, FeatureSetDefaults } from "../google/protobuf/descriptor_pb.js";
import type { BinaryReadOptions, BinaryWriteOptions } from "../binary-format.js";
/**
* A merged google.protobuf.FeaturesSet, with all fields guaranteed to be set.
*/
export type MergedFeatureSet = FeatureSet & Required<FeatureSet>;
/**
* A function that resolves features.
*
* If no feature set is provided, the default feature set for the edition is
* returned. If features are provided, they are merged into the edition default
* features.
*/
export type FeatureResolverFn = (a?: FeatureSet, b?: FeatureSet) => MergedFeatureSet;
/**
* Create an edition feature resolver with the given feature set defaults, or
* the feature set defaults supported by @bufbuild/protobuf.
*/
export declare function createFeatureResolver(edition: Edition, compiledFeatureSetDefaults?: FeatureSetDefaults, serializationOptions?: Partial<BinaryReadOptions & BinaryWriteOptions>): FeatureResolverFn;
+120
View File
@@ -0,0 +1,120 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.createFeatureResolver = void 0;
const descriptor_pb_js_1 = require("../google/protobuf/descriptor_pb.js");
const proto_base64_js_1 = require("../proto-base64.js");
/**
* Return the edition feature defaults supported by @bufbuild/protobuf.
*/
function getFeatureSetDefaults(options) {
return descriptor_pb_js_1.FeatureSetDefaults.fromBinary(proto_base64_js_1.protoBase64.dec(
/*upstream-inject-feature-defaults-start*/ "ChMY5gciACoMCAEQAhgCIAMoATACChMY5wciACoMCAIQARgBIAIoATABChMY6AciDAgBEAEYASACKAEwASoAIOYHKOgH" /*upstream-inject-feature-defaults-end*/), options);
}
/**
* Create an edition feature resolver with the given feature set defaults, or
* the feature set defaults supported by @bufbuild/protobuf.
*/
function createFeatureResolver(edition, compiledFeatureSetDefaults, serializationOptions) {
var _a;
const fds = compiledFeatureSetDefaults !== null && compiledFeatureSetDefaults !== void 0 ? compiledFeatureSetDefaults : getFeatureSetDefaults(serializationOptions);
const min = fds.minimumEdition;
const max = fds.maximumEdition;
if (min === undefined ||
max === undefined ||
fds.defaults.some((d) => d.edition === undefined)) {
throw new Error("Invalid FeatureSetDefaults");
}
if (edition < min) {
throw new Error(`Edition ${descriptor_pb_js_1.Edition[edition]} is earlier than the minimum supported edition ${descriptor_pb_js_1.Edition[min]}`);
}
if (max < edition) {
throw new Error(`Edition ${descriptor_pb_js_1.Edition[edition]} is later than the maximum supported edition ${descriptor_pb_js_1.Edition[max]}`);
}
let highestMatch = undefined;
for (const c of fds.defaults) {
const e = (_a = c.edition) !== null && _a !== void 0 ? _a : 0;
if (e > edition) {
continue;
}
if (highestMatch !== undefined && highestMatch.e > e) {
continue;
}
let f;
if (c.fixedFeatures && c.overridableFeatures) {
f = c.fixedFeatures;
f.fromBinary(c.overridableFeatures.toBinary());
}
else if (c.fixedFeatures) {
f = c.fixedFeatures;
}
else if (c.overridableFeatures) {
f = c.overridableFeatures;
}
else {
f = new descriptor_pb_js_1.FeatureSet();
}
highestMatch = {
e,
f,
};
}
if (highestMatch === undefined) {
throw new Error(`No valid default found for edition ${descriptor_pb_js_1.Edition[edition]}`);
}
const featureSetBin = highestMatch.f.toBinary(serializationOptions);
return (...rest) => {
const f = descriptor_pb_js_1.FeatureSet.fromBinary(featureSetBin, serializationOptions);
for (const c of rest) {
if (c !== undefined) {
f.fromBinary(c.toBinary(serializationOptions), serializationOptions);
}
}
if (!validateMergedFeatures(f)) {
throw new Error(`Invalid FeatureSet for edition ${descriptor_pb_js_1.Edition[edition]}`);
}
return f;
};
}
exports.createFeatureResolver = createFeatureResolver;
// When protoc generates google.protobuf.FeatureSetDefaults, it ensures that
// fields are not repeated or required, do not use oneof, and have a default
// value.
//
// When features for an element are resolved, features of the element and its
// parents are merged into the default FeatureSet for the edition. Because unset
// fields in the FeatureSet of an element do not unset the default FeatureSet
// values, a resolved FeatureSet is guaranteed to have all fields set. This is
// also the case for extensions to FeatureSet that a user might provide, and for
// features from the future.
//
// We cannot exhaustively validate correctness of FeatureSetDefaults at runtime
// without knowing the schema: If no value for a feature is provided, we do not
// know that it exists at all.
//
// As a sanity check, we validate that all fields known to our version of
// FeatureSet are set.
function validateMergedFeatures(featureSet) {
for (const fi of descriptor_pb_js_1.FeatureSet.fields.list()) {
const v = featureSet[fi.localName];
if (v === undefined) {
return false;
}
if (fi.kind == "enum" && v === 0) {
return false;
}
}
return true;
}
+18
View File
@@ -0,0 +1,18 @@
import type { FieldInfo, OneofInfo, PartialFieldInfo } from "../field.js";
import type { FieldList } from "../field-list.js";
export type FieldListSource = readonly PartialFieldInfo[] | readonly FieldInfo[] | (() => readonly PartialFieldInfo[]) | (() => readonly FieldInfo[]);
export declare class InternalFieldList implements FieldList {
private readonly _fields;
private readonly _normalizer;
private all?;
private numbersAsc?;
private jsonNames?;
private numbers?;
private members?;
constructor(fields: FieldListSource, normalizer: (p: FieldListSource) => FieldInfo[]);
findJsonName(jsonName: string): FieldInfo | undefined;
find(fieldNo: number): FieldInfo | undefined;
list(): readonly FieldInfo[];
byNumber(): readonly FieldInfo[];
byMember(): readonly (FieldInfo | OneofInfo)[];
}
+76
View File
@@ -0,0 +1,76 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.InternalFieldList = void 0;
class InternalFieldList {
constructor(fields, normalizer) {
this._fields = fields;
this._normalizer = normalizer;
}
findJsonName(jsonName) {
if (!this.jsonNames) {
const t = {};
for (const f of this.list()) {
t[f.jsonName] = t[f.name] = f;
}
this.jsonNames = t;
}
return this.jsonNames[jsonName];
}
find(fieldNo) {
if (!this.numbers) {
const t = {};
for (const f of this.list()) {
t[f.no] = f;
}
this.numbers = t;
}
return this.numbers[fieldNo];
}
list() {
if (!this.all) {
this.all = this._normalizer(this._fields);
}
return this.all;
}
byNumber() {
if (!this.numbersAsc) {
this.numbersAsc = this.list()
.concat()
.sort((a, b) => a.no - b.no);
}
return this.numbersAsc;
}
byMember() {
if (!this.members) {
this.members = [];
const a = this.members;
let o;
for (const f of this.list()) {
if (f.oneof) {
if (f.oneof !== o) {
o = f.oneof;
a.push(o);
}
}
else {
a.push(f);
}
}
}
return this.members;
}
}
exports.InternalFieldList = InternalFieldList;
@@ -0,0 +1,9 @@
import type { FieldListSource } from "./field-list.js";
import type { FieldInfo } from "../field.js";
/**
* Convert a collection of field info to an array of normalized FieldInfo.
*
* The argument `packedByDefault` specifies whether fields that do not specify
* `packed` should be packed (proto3) or unpacked (proto2).
*/
export declare function normalizeFieldInfos(fieldInfos: FieldListSource, packedByDefault: boolean): FieldInfo[];
+69
View File
@@ -0,0 +1,69 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizeFieldInfos = void 0;
const field_js_1 = require("./field.js");
const names_js_1 = require("./names.js");
const scalar_js_1 = require("../scalar.js");
/**
* Convert a collection of field info to an array of normalized FieldInfo.
*
* The argument `packedByDefault` specifies whether fields that do not specify
* `packed` should be packed (proto3) or unpacked (proto2).
*/
function normalizeFieldInfos(fieldInfos, packedByDefault) {
var _a, _b, _c, _d, _e, _f;
const r = [];
let o;
for (const field of typeof fieldInfos == "function"
? fieldInfos()
: fieldInfos) {
const f = field;
f.localName = (0, names_js_1.localFieldName)(field.name, field.oneof !== undefined);
f.jsonName = (_a = field.jsonName) !== null && _a !== void 0 ? _a : (0, names_js_1.fieldJsonName)(field.name);
f.repeated = (_b = field.repeated) !== null && _b !== void 0 ? _b : false;
if (field.kind == "scalar") {
f.L = (_c = field.L) !== null && _c !== void 0 ? _c : scalar_js_1.LongType.BIGINT;
}
f.delimited = (_d = field.delimited) !== null && _d !== void 0 ? _d : false;
f.req = (_e = field.req) !== null && _e !== void 0 ? _e : false;
f.opt = (_f = field.opt) !== null && _f !== void 0 ? _f : false;
if (field.packed === undefined) {
if (packedByDefault) {
f.packed =
field.kind == "enum" ||
(field.kind == "scalar" &&
field.T != scalar_js_1.ScalarType.BYTES &&
field.T != scalar_js_1.ScalarType.STRING);
}
else {
f.packed = false;
}
}
// We do not surface options at this time
// f.options = field.options ?? emptyReadonlyObject;
if (field.oneof !== undefined) {
const ooname = typeof field.oneof == "string" ? field.oneof : field.oneof.name;
if (!o || o.name != ooname) {
o = new field_js_1.InternalOneofInfo(ooname);
}
f.oneof = o;
o.addField(f);
}
r.push(f);
}
return r;
}
exports.normalizeFieldInfos = normalizeFieldInfos;
+25
View File
@@ -0,0 +1,25 @@
import { Message } from "../message.js";
import type { MessageType } from "../message-type.js";
import type { DescExtension, DescField } from "../descriptor-set.js";
import { ScalarType } from "../scalar.js";
/**
* A field wrapper unwraps a message to a primitive value that is more
* ergonomic for use as a message field.
*
* Note that this feature exists for google/protobuf/wrappers.proto
* and cannot be used to arbitrarily modify types in generated code.
*/
export interface FieldWrapper<T extends Message<T> = any, U = any> {
wrapField(value: U): T;
unwrapField(value: T): U;
}
/**
* Wrap a primitive message field value in its corresponding wrapper
* message. This function is idempotent.
*/
export declare function wrapField<T extends Message<T>>(type: MessageType<T>, value: any): T;
/**
* If the given field uses one of the well-known wrapper types, return
* the primitive type it wraps.
*/
export declare function getUnwrappedFieldType(field: DescField | DescExtension): ScalarType | undefined;
+57
View File
@@ -0,0 +1,57 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.getUnwrappedFieldType = exports.wrapField = void 0;
const scalar_js_1 = require("../scalar.js");
const is_message_js_1 = require("../is-message.js");
/**
* Wrap a primitive message field value in its corresponding wrapper
* message. This function is idempotent.
*/
function wrapField(type, value) {
if ((0, is_message_js_1.isMessage)(value) || !type.fieldWrapper) {
return value;
}
return type.fieldWrapper.wrapField(value);
}
exports.wrapField = wrapField;
/**
* If the given field uses one of the well-known wrapper types, return
* the primitive type it wraps.
*/
function getUnwrappedFieldType(field) {
if (field.fieldKind !== "message") {
return undefined;
}
if (field.repeated) {
return undefined;
}
if (field.oneof != undefined) {
return undefined;
}
return wktWrapperToScalarType[field.message.typeName];
}
exports.getUnwrappedFieldType = getUnwrappedFieldType;
const wktWrapperToScalarType = {
"google.protobuf.DoubleValue": scalar_js_1.ScalarType.DOUBLE,
"google.protobuf.FloatValue": scalar_js_1.ScalarType.FLOAT,
"google.protobuf.Int64Value": scalar_js_1.ScalarType.INT64,
"google.protobuf.UInt64Value": scalar_js_1.ScalarType.UINT64,
"google.protobuf.Int32Value": scalar_js_1.ScalarType.INT32,
"google.protobuf.UInt32Value": scalar_js_1.ScalarType.UINT32,
"google.protobuf.BoolValue": scalar_js_1.ScalarType.BOOL,
"google.protobuf.StringValue": scalar_js_1.ScalarType.STRING,
"google.protobuf.BytesValue": scalar_js_1.ScalarType.BYTES,
};
+16
View File
@@ -0,0 +1,16 @@
import type { FieldInfo, OneofInfo } from "../field.js";
export declare class InternalOneofInfo implements OneofInfo {
readonly kind = "oneof";
readonly name: string;
readonly localName: string;
readonly repeated = false;
readonly packed = false;
readonly opt = false;
readonly req = false;
readonly default: undefined;
readonly fields: FieldInfo[];
private _lookup?;
constructor(name: string);
addField(field: FieldInfo): void;
findField(localName: string): FieldInfo | undefined;
}
+45
View File
@@ -0,0 +1,45 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.InternalOneofInfo = void 0;
const names_js_1 = require("./names.js");
const assert_js_1 = require("./assert.js");
class InternalOneofInfo {
constructor(name) {
this.kind = "oneof";
this.repeated = false;
this.packed = false;
this.opt = false;
this.req = false;
this.default = undefined;
this.fields = [];
this.name = name;
this.localName = (0, names_js_1.localOneofName)(name);
}
addField(field) {
(0, assert_js_1.assert)(field.oneof === this, `field ${field.name} not one of ${this.name}`);
this.fields.push(field);
}
findField(localName) {
if (!this._lookup) {
this._lookup = Object.create(null);
for (let i = 0; i < this.fields.length; i++) {
this._lookup[this.fields[i].localName] = this.fields[i];
}
}
return this._lookup[localName];
}
}
exports.InternalOneofInfo = InternalOneofInfo;
+2
View File
@@ -0,0 +1,2 @@
import type { JsonFormat } from "../json-format.js";
export declare function makeJsonFormat(): JsonFormat;
+626
View File
@@ -0,0 +1,626 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeJsonFormat = void 0;
const assert_js_1 = require("./assert.js");
const proto_int64_js_1 = require("../proto-int64.js");
const proto_base64_js_1 = require("../proto-base64.js");
const extensions_js_1 = require("./extensions.js");
const extension_accessor_js_1 = require("../extension-accessor.js");
const reflect_js_1 = require("./reflect.js");
const field_wrapper_js_1 = require("./field-wrapper.js");
const scalars_js_1 = require("./scalars.js");
const scalars_js_2 = require("./scalars.js");
const scalar_js_1 = require("../scalar.js");
const is_message_js_1 = require("../is-message.js");
/* eslint-disable no-case-declarations,@typescript-eslint/no-unsafe-argument,@typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-call */
// Default options for parsing JSON.
const jsonReadDefaults = {
ignoreUnknownFields: false,
};
// Default options for serializing to JSON.
const jsonWriteDefaults = {
emitDefaultValues: false,
enumAsInteger: false,
useProtoFieldName: false,
prettySpaces: 0,
};
function makeReadOptions(options) {
return options ? Object.assign(Object.assign({}, jsonReadDefaults), options) : jsonReadDefaults;
}
function makeWriteOptions(options) {
return options ? Object.assign(Object.assign({}, jsonWriteDefaults), options) : jsonWriteDefaults;
}
const tokenNull = Symbol();
const tokenIgnoredUnknownEnum = Symbol();
function makeJsonFormat() {
return {
makeReadOptions,
makeWriteOptions,
readMessage(type, json, options, message) {
if (json == null || Array.isArray(json) || typeof json != "object") {
throw new Error(`cannot decode message ${type.typeName} from JSON: ${debugJsonValue(json)}`);
}
message = message !== null && message !== void 0 ? message : new type();
const oneofSeen = new Map();
const registry = options.typeRegistry;
for (const [jsonKey, jsonValue] of Object.entries(json)) {
const field = type.fields.findJsonName(jsonKey);
if (field) {
if (field.oneof) {
if (jsonValue === null && field.kind == "scalar") {
// see conformance test Required.Proto3.JsonInput.OneofFieldNull{First,Second}
continue;
}
const seen = oneofSeen.get(field.oneof);
if (seen !== undefined) {
throw new Error(`cannot decode message ${type.typeName} from JSON: multiple keys for oneof "${field.oneof.name}" present: "${seen}", "${jsonKey}"`);
}
oneofSeen.set(field.oneof, jsonKey);
}
readField(message, jsonValue, field, options, type);
}
else {
let found = false;
if ((registry === null || registry === void 0 ? void 0 : registry.findExtension) &&
jsonKey.startsWith("[") &&
jsonKey.endsWith("]")) {
const ext = registry.findExtension(jsonKey.substring(1, jsonKey.length - 1));
if (ext && ext.extendee.typeName == type.typeName) {
found = true;
const [container, get] = (0, extensions_js_1.createExtensionContainer)(ext);
readField(container, jsonValue, ext.field, options, ext);
// We pass on the options as BinaryReadOptions/BinaryWriteOptions,
// so that users can bring their own binary reader and writer factories
// if necessary.
(0, extension_accessor_js_1.setExtension)(message, ext, get(), options);
}
}
if (!found && !options.ignoreUnknownFields) {
throw new Error(`cannot decode message ${type.typeName} from JSON: key "${jsonKey}" is unknown`);
}
}
}
return message;
},
writeMessage(message, options) {
const type = message.getType();
const json = {};
let field;
try {
for (field of type.fields.byNumber()) {
if (!(0, reflect_js_1.isFieldSet)(field, message)) {
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
if (field.req) {
throw `required field not set`;
}
if (!options.emitDefaultValues) {
continue;
}
if (!canEmitFieldDefaultValue(field)) {
continue;
}
}
const value = field.oneof
? message[field.oneof.localName].value
: message[field.localName];
const jsonValue = writeField(field, value, options);
if (jsonValue !== undefined) {
json[options.useProtoFieldName ? field.name : field.jsonName] =
jsonValue;
}
}
const registry = options.typeRegistry;
if (registry === null || registry === void 0 ? void 0 : registry.findExtensionFor) {
for (const uf of type.runtime.bin.listUnknownFields(message)) {
const ext = registry.findExtensionFor(type.typeName, uf.no);
if (ext && (0, extension_accessor_js_1.hasExtension)(message, ext)) {
// We pass on the options as BinaryReadOptions, so that users can bring their own
// binary reader factory if necessary.
const value = (0, extension_accessor_js_1.getExtension)(message, ext, options);
const jsonValue = writeField(ext.field, value, options);
if (jsonValue !== undefined) {
json[ext.field.jsonName] = jsonValue;
}
}
}
}
}
catch (e) {
const m = field
? `cannot encode field ${type.typeName}.${field.name} to JSON`
: `cannot encode message ${type.typeName} to JSON`;
const r = e instanceof Error ? e.message : String(e);
throw new Error(m + (r.length > 0 ? `: ${r}` : ""));
}
return json;
},
readScalar(type, json, longType) {
// The signature of our internal function has changed. For backwards-
// compatibility, we support the old form that is part of the public API
// through the interface JsonFormat.
return readScalar(type, json, longType !== null && longType !== void 0 ? longType : scalar_js_1.LongType.BIGINT, true);
},
writeScalar(type, value, emitDefaultValues) {
// The signature of our internal function has changed. For backwards-
// compatibility, we support the old form that is part of the public API
// through the interface JsonFormat.
if (value === undefined) {
return undefined;
}
if (emitDefaultValues || (0, scalars_js_2.isScalarZeroValue)(type, value)) {
return writeScalar(type, value);
}
return undefined;
},
debug: debugJsonValue,
};
}
exports.makeJsonFormat = makeJsonFormat;
function debugJsonValue(json) {
if (json === null) {
return "null";
}
switch (typeof json) {
case "object":
return Array.isArray(json) ? "array" : "object";
case "string":
return json.length > 100 ? "string" : `"${json.split('"').join('\\"')}"`;
default:
return String(json);
}
}
// Read a JSON value for a field.
// The "parentType" argument is only used to provide context in errors.
function readField(target, jsonValue, field, options, parentType) {
let localName = field.localName;
if (field.repeated) {
(0, assert_js_1.assert)(field.kind != "map");
if (jsonValue === null) {
return;
}
if (!Array.isArray(jsonValue)) {
throw new Error(`cannot decode field ${parentType.typeName}.${field.name} from JSON: ${debugJsonValue(jsonValue)}`);
}
const targetArray = target[localName];
for (const jsonItem of jsonValue) {
if (jsonItem === null) {
throw new Error(`cannot decode field ${parentType.typeName}.${field.name} from JSON: ${debugJsonValue(jsonItem)}`);
}
switch (field.kind) {
case "message":
targetArray.push(field.T.fromJson(jsonItem, options));
break;
case "enum":
const enumValue = readEnum(field.T, jsonItem, options.ignoreUnknownFields, true);
if (enumValue !== tokenIgnoredUnknownEnum) {
targetArray.push(enumValue);
}
break;
case "scalar":
try {
targetArray.push(readScalar(field.T, jsonItem, field.L, true));
}
catch (e) {
let m = `cannot decode field ${parentType.typeName}.${field.name} from JSON: ${debugJsonValue(jsonItem)}`;
if (e instanceof Error && e.message.length > 0) {
m += `: ${e.message}`;
}
throw new Error(m);
}
break;
}
}
}
else if (field.kind == "map") {
if (jsonValue === null) {
return;
}
if (typeof jsonValue != "object" || Array.isArray(jsonValue)) {
throw new Error(`cannot decode field ${parentType.typeName}.${field.name} from JSON: ${debugJsonValue(jsonValue)}`);
}
const targetMap = target[localName];
for (const [jsonMapKey, jsonMapValue] of Object.entries(jsonValue)) {
if (jsonMapValue === null) {
throw new Error(`cannot decode field ${parentType.typeName}.${field.name} from JSON: map value null`);
}
let key;
try {
key = readMapKey(field.K, jsonMapKey);
}
catch (e) {
let m = `cannot decode map key for field ${parentType.typeName}.${field.name} from JSON: ${debugJsonValue(jsonValue)}`;
if (e instanceof Error && e.message.length > 0) {
m += `: ${e.message}`;
}
throw new Error(m);
}
switch (field.V.kind) {
case "message":
targetMap[key] = field.V.T.fromJson(jsonMapValue, options);
break;
case "enum":
const enumValue = readEnum(field.V.T, jsonMapValue, options.ignoreUnknownFields, true);
if (enumValue !== tokenIgnoredUnknownEnum) {
targetMap[key] = enumValue;
}
break;
case "scalar":
try {
targetMap[key] = readScalar(field.V.T, jsonMapValue, scalar_js_1.LongType.BIGINT, true);
}
catch (e) {
let m = `cannot decode map value for field ${parentType.typeName}.${field.name} from JSON: ${debugJsonValue(jsonValue)}`;
if (e instanceof Error && e.message.length > 0) {
m += `: ${e.message}`;
}
throw new Error(m);
}
break;
}
}
}
else {
if (field.oneof) {
target = target[field.oneof.localName] = { case: localName };
localName = "value";
}
switch (field.kind) {
case "message":
const messageType = field.T;
if (jsonValue === null &&
messageType.typeName != "google.protobuf.Value") {
return;
}
let currentValue = target[localName];
if ((0, is_message_js_1.isMessage)(currentValue)) {
currentValue.fromJson(jsonValue, options);
}
else {
target[localName] = currentValue = messageType.fromJson(jsonValue, options);
if (messageType.fieldWrapper && !field.oneof) {
target[localName] =
messageType.fieldWrapper.unwrapField(currentValue);
}
}
break;
case "enum":
const enumValue = readEnum(field.T, jsonValue, options.ignoreUnknownFields, false);
switch (enumValue) {
case tokenNull:
(0, reflect_js_1.clearField)(field, target);
break;
case tokenIgnoredUnknownEnum:
break;
default:
target[localName] = enumValue;
break;
}
break;
case "scalar":
try {
const scalarValue = readScalar(field.T, jsonValue, field.L, false);
switch (scalarValue) {
case tokenNull:
(0, reflect_js_1.clearField)(field, target);
break;
default:
target[localName] = scalarValue;
break;
}
}
catch (e) {
let m = `cannot decode field ${parentType.typeName}.${field.name} from JSON: ${debugJsonValue(jsonValue)}`;
if (e instanceof Error && e.message.length > 0) {
m += `: ${e.message}`;
}
throw new Error(m);
}
break;
}
}
}
function readMapKey(type, json) {
if (type === scalar_js_1.ScalarType.BOOL) {
// eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check
switch (json) {
case "true":
json = true;
break;
case "false":
json = false;
break;
}
}
return readScalar(type, json, scalar_js_1.LongType.BIGINT, true).toString();
}
function readScalar(type, json, longType, nullAsZeroValue) {
if (json === null) {
if (nullAsZeroValue) {
return (0, scalars_js_1.scalarZeroValue)(type, longType);
}
return tokenNull;
}
// every valid case in the switch below returns, and every fall
// through is regarded as a failure.
switch (type) {
// float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity".
// Either numbers or strings are accepted. Exponent notation is also accepted.
case scalar_js_1.ScalarType.DOUBLE:
case scalar_js_1.ScalarType.FLOAT:
if (json === "NaN")
return Number.NaN;
if (json === "Infinity")
return Number.POSITIVE_INFINITY;
if (json === "-Infinity")
return Number.NEGATIVE_INFINITY;
if (json === "") {
// empty string is not a number
break;
}
if (typeof json == "string" && json.trim().length !== json.length) {
// extra whitespace
break;
}
if (typeof json != "string" && typeof json != "number") {
break;
}
const float = Number(json);
if (Number.isNaN(float)) {
// not a number
break;
}
if (!Number.isFinite(float)) {
// infinity and -infinity are handled by string representation above, so this is an error
break;
}
if (type == scalar_js_1.ScalarType.FLOAT)
(0, assert_js_1.assertFloat32)(float);
return float;
// int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted.
case scalar_js_1.ScalarType.INT32:
case scalar_js_1.ScalarType.FIXED32:
case scalar_js_1.ScalarType.SFIXED32:
case scalar_js_1.ScalarType.SINT32:
case scalar_js_1.ScalarType.UINT32:
let int32;
if (typeof json == "number")
int32 = json;
else if (typeof json == "string" && json.length > 0) {
if (json.trim().length === json.length)
int32 = Number(json);
}
if (int32 === undefined)
break;
if (type == scalar_js_1.ScalarType.UINT32 || type == scalar_js_1.ScalarType.FIXED32)
(0, assert_js_1.assertUInt32)(int32);
else
(0, assert_js_1.assertInt32)(int32);
return int32;
// int64, fixed64, uint64: JSON value will be a decimal string. Either numbers or strings are accepted.
case scalar_js_1.ScalarType.INT64:
case scalar_js_1.ScalarType.SFIXED64:
case scalar_js_1.ScalarType.SINT64:
if (typeof json != "number" && typeof json != "string")
break;
const long = proto_int64_js_1.protoInt64.parse(json);
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
return longType ? long.toString() : long;
case scalar_js_1.ScalarType.FIXED64:
case scalar_js_1.ScalarType.UINT64:
if (typeof json != "number" && typeof json != "string")
break;
const uLong = proto_int64_js_1.protoInt64.uParse(json);
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
return longType ? uLong.toString() : uLong;
// bool:
case scalar_js_1.ScalarType.BOOL:
if (typeof json !== "boolean")
break;
return json;
// string:
case scalar_js_1.ScalarType.STRING:
if (typeof json !== "string") {
break;
}
// A string must always contain UTF-8 encoded or 7-bit ASCII.
// We validate with encodeURIComponent, which appears to be the fastest widely available option.
try {
encodeURIComponent(json);
}
catch (e) {
throw new Error("invalid UTF8");
}
return json;
// bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings.
// Either standard or URL-safe base64 encoding with/without paddings are accepted.
case scalar_js_1.ScalarType.BYTES:
if (json === "")
return new Uint8Array(0);
if (typeof json !== "string")
break;
return proto_base64_js_1.protoBase64.dec(json);
}
throw new Error();
}
function readEnum(type, json, ignoreUnknownFields, nullAsZeroValue) {
if (json === null) {
if (type.typeName == "google.protobuf.NullValue") {
return 0; // google.protobuf.NullValue.NULL_VALUE = 0
}
return nullAsZeroValue ? type.values[0].no : tokenNull;
}
// eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check
switch (typeof json) {
case "number":
if (Number.isInteger(json)) {
return json;
}
break;
case "string":
const value = type.findName(json);
if (value !== undefined) {
return value.no;
}
if (ignoreUnknownFields) {
return tokenIgnoredUnknownEnum;
}
break;
}
throw new Error(`cannot decode enum ${type.typeName} from JSON: ${debugJsonValue(json)}`);
}
// Decide whether an unset field should be emitted with JSON write option `emitDefaultValues`
function canEmitFieldDefaultValue(field) {
if (field.repeated || field.kind == "map") {
// maps are {}, repeated fields are []
return true;
}
if (field.oneof) {
// oneof fields are never emitted
return false;
}
if (field.kind == "message") {
// singular message field are allowed to emit JSON null, but we do not
return false;
}
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
if (field.opt || field.req) {
// the field uses explicit presence, so we cannot emit a zero value
return false;
}
return true;
}
function writeField(field, value, options) {
if (field.kind == "map") {
(0, assert_js_1.assert)(typeof value == "object" && value != null);
const jsonObj = {};
const entries = Object.entries(value);
switch (field.V.kind) {
case "scalar":
for (const [entryKey, entryValue] of entries) {
jsonObj[entryKey.toString()] = writeScalar(field.V.T, entryValue); // JSON standard allows only (double quoted) string as property key
}
break;
case "message":
for (const [entryKey, entryValue] of entries) {
// JSON standard allows only (double quoted) string as property key
jsonObj[entryKey.toString()] = entryValue.toJson(options);
}
break;
case "enum":
const enumType = field.V.T;
for (const [entryKey, entryValue] of entries) {
// JSON standard allows only (double quoted) string as property key
jsonObj[entryKey.toString()] = writeEnum(enumType, entryValue, options.enumAsInteger);
}
break;
}
return options.emitDefaultValues || entries.length > 0
? jsonObj
: undefined;
}
if (field.repeated) {
(0, assert_js_1.assert)(Array.isArray(value));
const jsonArr = [];
switch (field.kind) {
case "scalar":
for (let i = 0; i < value.length; i++) {
jsonArr.push(writeScalar(field.T, value[i]));
}
break;
case "enum":
for (let i = 0; i < value.length; i++) {
jsonArr.push(writeEnum(field.T, value[i], options.enumAsInteger));
}
break;
case "message":
for (let i = 0; i < value.length; i++) {
jsonArr.push(value[i].toJson(options));
}
break;
}
return options.emitDefaultValues || jsonArr.length > 0
? jsonArr
: undefined;
}
switch (field.kind) {
case "scalar":
return writeScalar(field.T, value);
case "enum":
return writeEnum(field.T, value, options.enumAsInteger);
case "message":
return (0, field_wrapper_js_1.wrapField)(field.T, value).toJson(options);
}
}
function writeEnum(type, value, enumAsInteger) {
var _a;
(0, assert_js_1.assert)(typeof value == "number");
if (type.typeName == "google.protobuf.NullValue") {
return null;
}
if (enumAsInteger) {
return value;
}
const val = type.findNumber(value);
return (_a = val === null || val === void 0 ? void 0 : val.name) !== null && _a !== void 0 ? _a : value; // if we don't know the enum value, just return the number
}
function writeScalar(type, value) {
switch (type) {
// int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted.
case scalar_js_1.ScalarType.INT32:
case scalar_js_1.ScalarType.SFIXED32:
case scalar_js_1.ScalarType.SINT32:
case scalar_js_1.ScalarType.FIXED32:
case scalar_js_1.ScalarType.UINT32:
(0, assert_js_1.assert)(typeof value == "number");
return value;
// float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity".
// Either numbers or strings are accepted. Exponent notation is also accepted.
case scalar_js_1.ScalarType.FLOAT:
// assertFloat32(value);
case scalar_js_1.ScalarType.DOUBLE: // eslint-disable-line no-fallthrough
(0, assert_js_1.assert)(typeof value == "number");
if (Number.isNaN(value))
return "NaN";
if (value === Number.POSITIVE_INFINITY)
return "Infinity";
if (value === Number.NEGATIVE_INFINITY)
return "-Infinity";
return value;
// string:
case scalar_js_1.ScalarType.STRING:
(0, assert_js_1.assert)(typeof value == "string");
return value;
// bool:
case scalar_js_1.ScalarType.BOOL:
(0, assert_js_1.assert)(typeof value == "boolean");
return value;
// JSON value will be a decimal string. Either numbers or strings are accepted.
case scalar_js_1.ScalarType.UINT64:
case scalar_js_1.ScalarType.FIXED64:
case scalar_js_1.ScalarType.INT64:
case scalar_js_1.ScalarType.SFIXED64:
case scalar_js_1.ScalarType.SINT64:
(0, assert_js_1.assert)(typeof value == "bigint" ||
typeof value == "string" ||
typeof value == "number");
return value.toString();
// bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings.
// Either standard or URL-safe base64 encoding with/without paddings are accepted.
case scalar_js_1.ScalarType.BYTES:
(0, assert_js_1.assert)(value instanceof Uint8Array);
return proto_base64_js_1.protoBase64.enc(value);
}
}
+18
View File
@@ -0,0 +1,18 @@
import { Message } from "../message.js";
import type { AnyMessage } from "../message.js";
import type { FieldListSource } from "./field-list.js";
import type { MessageType } from "../message-type.js";
import type { ProtoRuntime } from "./proto-runtime.js";
/**
* Create a new message type using the given runtime.
*/
export declare function makeMessageType<T extends Message<T> = AnyMessage>(runtime: ProtoRuntime, typeName: string, fields: FieldListSource, opt?: {
/**
* localName is the "name" property of the constructed function.
* It is useful in stack traces, debuggers and test frameworks,
* but has no other implications.
*
* If omitted, the last part of the typeName is used.
*/
localName?: string;
}): MessageType<T>;
+50
View File
@@ -0,0 +1,50 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeMessageType = void 0;
const message_js_1 = require("../message.js");
/**
* Create a new message type using the given runtime.
*/
function makeMessageType(runtime, typeName, fields, opt) {
var _a;
const localName = (_a = opt === null || opt === void 0 ? void 0 : opt.localName) !== null && _a !== void 0 ? _a : typeName.substring(typeName.lastIndexOf(".") + 1);
const type = {
[localName]: function (data) {
runtime.util.initFields(this);
runtime.util.initPartial(data, this);
},
}[localName];
Object.setPrototypeOf(type.prototype, new message_js_1.Message());
Object.assign(type, {
runtime,
typeName,
fields: runtime.util.newFieldList(fields),
fromBinary(bytes, options) {
return new type().fromBinary(bytes, options);
},
fromJson(jsonValue, options) {
return new type().fromJson(jsonValue, options);
},
fromJsonString(jsonString, options) {
return new type().fromJsonString(jsonString, options);
},
equals(a, b) {
return runtime.util.equals(type, a, b);
},
});
return type;
}
exports.makeMessageType = makeMessageType;
+43
View File
@@ -0,0 +1,43 @@
import type { DescEnum, DescEnumValue, DescExtension, DescField, DescMessage, DescService } from "../descriptor-set.js";
import type { DescMethod, DescOneof } from "../descriptor-set.js";
/**
* Returns the name of a protobuf element in generated code.
*
* Field names - including oneofs - are converted to lowerCamelCase. For
* messages, enumerations and services, the package name is stripped from
* the type name. For nested messages and enumerations, the names are joined
* with an underscore. For methods, the first character is made lowercase.
*/
export declare function localName(desc: DescEnum | DescEnumValue | DescMessage | DescExtension | DescOneof | DescField | DescService | DescMethod): string;
/**
* Returns the name of a field in generated code.
*/
export declare function localFieldName(protoName: string, inOneof: boolean): string;
/**
* Returns the name of a oneof group in generated code.
*/
export declare function localOneofName(protoName: string): string;
/**
* Returns the JSON name for a protobuf field, exactly like protoc does.
*/
export declare const fieldJsonName: typeof protoCamelCase;
/**
* Finds a prefix shared by enum values, for example `MY_ENUM_` for
* `enum MyEnum {MY_ENUM_A=0; MY_ENUM_B=1;}`.
*/
export declare function findEnumSharedPrefix(enumName: string, valueNames: string[]): string | undefined;
/**
* Converts snake_case to protoCamelCase according to the convention
* used by protoc to convert a field name to a JSON name.
*/
declare function protoCamelCase(snakeCase: string): string;
/**
* Names that cannot be used for object properties because they are reserved
* by built-in JavaScript properties.
*/
export declare const safeObjectProperty: (name: string) => string;
/**
* Names that can be used for identifiers or class properties
*/
export declare const safeIdentifier: (name: string) => string;
export {};
+278
View File
@@ -0,0 +1,278 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.safeIdentifier = exports.safeObjectProperty = exports.findEnumSharedPrefix = exports.fieldJsonName = exports.localOneofName = exports.localFieldName = exports.localName = void 0;
/**
* Returns the name of a protobuf element in generated code.
*
* Field names - including oneofs - are converted to lowerCamelCase. For
* messages, enumerations and services, the package name is stripped from
* the type name. For nested messages and enumerations, the names are joined
* with an underscore. For methods, the first character is made lowercase.
*/
function localName(desc) {
switch (desc.kind) {
case "field":
return localFieldName(desc.name, desc.oneof !== undefined);
case "oneof":
return localOneofName(desc.name);
case "enum":
case "message":
case "service":
case "extension": {
const pkg = desc.file.proto.package;
const offset = pkg === undefined ? 0 : pkg.length + 1;
const name = desc.typeName.substring(offset).replace(/\./g, "_");
// For services, we only care about safe identifiers, not safe object properties,
// but we have shipped v1 with a bug that respected object properties, and we
// do not want to introduce a breaking change, so we continue to escape for
// safe object properties.
// See https://github.com/bufbuild/protobuf-es/pull/391
return (0, exports.safeObjectProperty)((0, exports.safeIdentifier)(name));
}
case "enum_value": {
let name = desc.name;
const sharedPrefix = desc.parent.sharedPrefix;
if (sharedPrefix !== undefined) {
name = name.substring(sharedPrefix.length);
}
return (0, exports.safeObjectProperty)(name);
}
case "rpc": {
let name = desc.name;
if (name.length == 0) {
return name;
}
name = name[0].toLowerCase() + name.substring(1);
return (0, exports.safeObjectProperty)(name);
}
}
}
exports.localName = localName;
/**
* Returns the name of a field in generated code.
*/
function localFieldName(protoName, inOneof) {
const name = protoCamelCase(protoName);
if (inOneof) {
// oneof member names are not properties, but values of the `case` property.
return name;
}
return (0, exports.safeObjectProperty)(safeMessageProperty(name));
}
exports.localFieldName = localFieldName;
/**
* Returns the name of a oneof group in generated code.
*/
function localOneofName(protoName) {
return localFieldName(protoName, false);
}
exports.localOneofName = localOneofName;
/**
* Returns the JSON name for a protobuf field, exactly like protoc does.
*/
exports.fieldJsonName = protoCamelCase;
/**
* Finds a prefix shared by enum values, for example `MY_ENUM_` for
* `enum MyEnum {MY_ENUM_A=0; MY_ENUM_B=1;}`.
*/
function findEnumSharedPrefix(enumName, valueNames) {
const prefix = camelToSnakeCase(enumName) + "_";
for (const name of valueNames) {
if (!name.toLowerCase().startsWith(prefix)) {
return undefined;
}
const shortName = name.substring(prefix.length);
if (shortName.length == 0) {
return undefined;
}
if (/^\d/.test(shortName)) {
// identifiers must not start with numbers
return undefined;
}
}
return prefix;
}
exports.findEnumSharedPrefix = findEnumSharedPrefix;
/**
* Converts lowerCamelCase or UpperCamelCase into lower_snake_case.
* This is used to find shared prefixes in an enum.
*/
function camelToSnakeCase(camel) {
return (camel.substring(0, 1) + camel.substring(1).replace(/[A-Z]/g, (c) => "_" + c)).toLowerCase();
}
/**
* Converts snake_case to protoCamelCase according to the convention
* used by protoc to convert a field name to a JSON name.
*/
function protoCamelCase(snakeCase) {
let capNext = false;
const b = [];
for (let i = 0; i < snakeCase.length; i++) {
let c = snakeCase.charAt(i);
switch (c) {
case "_":
capNext = true;
break;
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
b.push(c);
capNext = false;
break;
default:
if (capNext) {
capNext = false;
c = c.toUpperCase();
}
b.push(c);
break;
}
}
return b.join("");
}
/**
* Names that cannot be used for identifiers, such as class names,
* but _can_ be used for object properties.
*/
const reservedIdentifiers = new Set([
// ECMAScript 2015 keywords
"break",
"case",
"catch",
"class",
"const",
"continue",
"debugger",
"default",
"delete",
"do",
"else",
"export",
"extends",
"false",
"finally",
"for",
"function",
"if",
"import",
"in",
"instanceof",
"new",
"null",
"return",
"super",
"switch",
"this",
"throw",
"true",
"try",
"typeof",
"var",
"void",
"while",
"with",
"yield",
// ECMAScript 2015 future reserved keywords
"enum",
"implements",
"interface",
"let",
"package",
"private",
"protected",
"public",
"static",
// Class name cannot be 'Object' when targeting ES5 with module CommonJS
"Object",
// TypeScript keywords that cannot be used for types (as opposed to variables)
"bigint",
"number",
"boolean",
"string",
"object",
// Identifiers reserved for the runtime, so we can generate legible code
"globalThis",
"Uint8Array",
"Partial",
]);
/**
* Names that cannot be used for object properties because they are reserved
* by built-in JavaScript properties.
*/
const reservedObjectProperties = new Set([
// names reserved by JavaScript
"constructor",
"toString",
"toJSON",
"valueOf",
]);
/**
* Names that cannot be used for object properties because they are reserved
* by the runtime.
*/
const reservedMessageProperties = new Set([
// names reserved by the runtime
"getType",
"clone",
"equals",
"fromBinary",
"fromJson",
"fromJsonString",
"toBinary",
"toJson",
"toJsonString",
// names reserved by the runtime for the future
"toObject",
]);
const fallback = (name) => `${name}$`;
/**
* Will wrap names that are Object prototype properties or names reserved
* for `Message`s.
*/
const safeMessageProperty = (name) => {
if (reservedMessageProperties.has(name)) {
return fallback(name);
}
return name;
};
/**
* Names that cannot be used for object properties because they are reserved
* by built-in JavaScript properties.
*/
const safeObjectProperty = (name) => {
if (reservedObjectProperties.has(name)) {
return fallback(name);
}
return name;
};
exports.safeObjectProperty = safeObjectProperty;
/**
* Names that can be used for identifiers or class properties
*/
const safeIdentifier = (name) => {
if (reservedIdentifiers.has(name)) {
return fallback(name);
}
return name;
};
exports.safeIdentifier = safeIdentifier;
+7
View File
@@ -0,0 +1,7 @@
import type { JsonValue } from "../json-format.js";
/**
*
*/
export type OptionsMap = {
readonly [extensionName: string]: JsonValue;
};
+15
View File
@@ -0,0 +1,15 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
+53
View File
@@ -0,0 +1,53 @@
import type { JsonFormat } from "../json-format.js";
import type { BinaryFormat } from "../binary-format.js";
import type { AnyMessage } from "../message.js";
import type { Message } from "../message.js";
import type { EnumType, EnumValueInfo } from "../enum.js";
import type { MessageType } from "../message-type.js";
import type { FieldListSource } from "./field-list.js";
import type { EnumObject } from "./enum.js";
import type { Util } from "./util.js";
import type { Extension } from "../extension.js";
import type { ExtensionFieldSource } from "./extensions.js";
/**
* A facade that provides serialization and other internal functionality.
*/
export interface ProtoRuntime {
readonly syntax: string;
readonly json: JsonFormat;
readonly bin: BinaryFormat;
readonly util: Util;
/**
* Create a message type at runtime, without generating code.
*/
makeMessageType<T extends Message<T> = AnyMessage>(typeName: string, fields: FieldListSource, opt?: {
localName?: string;
}): MessageType<T>;
/**
* Create an enum object at runtime, without generating code.
*
* The object conforms to TypeScript enums, and comes with
* mapping from name to value, and from value to name.
*
* The type name and other reflection information is accessible
* via getEnumType().
*/
makeEnum(typeName: string, values: (EnumValueInfo | Omit<EnumValueInfo, "localName">)[], opt?: {}): EnumObject;
/**
* Create an enum type at runtime, without generating code.
* Note that this only creates the reflection information, not an
* actual enum object.
*/
makeEnumType(typeName: string, values: (EnumValueInfo | Omit<EnumValueInfo, "localName">)[], opt?: {}): EnumType;
/**
* Get reflection information - the EnumType - from an enum object.
* If this function is called on something other than a generated
* enum, or an enum constructed with makeEnum(), it raises an error.
*/
getEnumType(enumObject: EnumObject): EnumType;
/**
* Create an extension at runtime, without generating code.
*/
makeExtension<E extends Message<E> = AnyMessage, V = unknown>(typeName: string, extendee: MessageType<E>, field: ExtensionFieldSource): Extension<E, V>;
}
export declare function makeProtoRuntime(syntax: string, newFieldList: Util["newFieldList"], initFields: Util["initFields"]): ProtoRuntime;
+41
View File
@@ -0,0 +1,41 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeProtoRuntime = void 0;
const enum_js_1 = require("./enum.js");
const message_type_js_1 = require("./message-type.js");
const extensions_js_1 = require("./extensions.js");
const json_format_js_1 = require("./json-format.js");
const binary_format_js_1 = require("./binary-format.js");
const util_common_js_1 = require("./util-common.js");
function makeProtoRuntime(syntax, newFieldList, initFields) {
return {
syntax,
json: (0, json_format_js_1.makeJsonFormat)(),
bin: (0, binary_format_js_1.makeBinaryFormat)(),
util: Object.assign(Object.assign({}, (0, util_common_js_1.makeUtilCommon)()), { newFieldList,
initFields }),
makeMessageType(typeName, fields, opt) {
return (0, message_type_js_1.makeMessageType)(this, typeName, fields, opt);
},
makeEnum: enum_js_1.makeEnum,
makeEnumType: enum_js_1.makeEnumType,
getEnumType: enum_js_1.getEnumType,
makeExtension(typeName, extendee, field) {
return (0, extensions_js_1.makeExtension)(this, typeName, extendee, field);
},
};
}
exports.makeProtoRuntime = makeProtoRuntime;
+9
View File
@@ -0,0 +1,9 @@
import type { FieldInfo } from "../field.js";
/**
* Returns true if the field is set.
*/
export declare function isFieldSet(field: FieldInfo, target: Record<string, any>): boolean;
/**
* Resets the field, so that isFieldSet() will return false.
*/
export declare function clearField(field: FieldInfo, target: Record<string, any>): void;
+79
View File
@@ -0,0 +1,79 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.clearField = exports.isFieldSet = void 0;
const scalars_js_1 = require("./scalars.js");
/**
* Returns true if the field is set.
*/
function isFieldSet(field, target) {
const localName = field.localName;
if (field.repeated) {
return target[localName].length > 0;
}
if (field.oneof) {
return target[field.oneof.localName].case === localName; // eslint-disable-line @typescript-eslint/no-unsafe-member-access
}
switch (field.kind) {
case "enum":
case "scalar":
if (field.opt || field.req) {
// explicit presence
return target[localName] !== undefined;
}
// implicit presence
if (field.kind == "enum") {
return target[localName] !== field.T.values[0].no;
}
return !(0, scalars_js_1.isScalarZeroValue)(field.T, target[localName]);
case "message":
return target[localName] !== undefined;
case "map":
return Object.keys(target[localName]).length > 0; // eslint-disable-line @typescript-eslint/no-unsafe-argument
}
}
exports.isFieldSet = isFieldSet;
/**
* Resets the field, so that isFieldSet() will return false.
*/
function clearField(field, target) {
const localName = field.localName;
const implicitPresence = !field.opt && !field.req;
if (field.repeated) {
target[localName] = [];
}
else if (field.oneof) {
target[field.oneof.localName] = { case: undefined };
}
else {
switch (field.kind) {
case "map":
target[localName] = {};
break;
case "enum":
target[localName] = implicitPresence ? field.T.values[0].no : undefined;
break;
case "scalar":
target[localName] = implicitPresence
? (0, scalars_js_1.scalarZeroValue)(field.T, field.L)
: undefined;
break;
case "message":
target[localName] = undefined;
break;
}
}
}
exports.clearField = clearField;
+102
View File
@@ -0,0 +1,102 @@
import type { DescField, DescMessage, DescOneof } from "../descriptor-set.js";
type DescWkt = {
typeName: "google.protobuf.Any";
typeUrl: DescField;
value: DescField;
} | {
typeName: "google.protobuf.Timestamp";
seconds: DescField;
nanos: DescField;
} | {
typeName: "google.protobuf.Duration";
seconds: DescField;
nanos: DescField;
} | {
typeName: "google.protobuf.Struct";
fields: DescField & {
fieldKind: "map";
};
} | {
typeName: "google.protobuf.Value";
kind: DescOneof;
nullValue: DescField & {
fieldKind: "enum";
};
numberValue: DescField;
stringValue: DescField;
boolValue: DescField;
structValue: DescField & {
fieldKind: "message";
};
listValue: DescField & {
fieldKind: "message";
};
} | {
typeName: "google.protobuf.ListValue";
values: DescField & {
fieldKind: "message";
};
} | {
typeName: "google.protobuf.FieldMask";
paths: DescField;
} | {
typeName: "google.protobuf.DoubleValue";
value: DescField & {
fieldKind: "scalar";
};
} | {
typeName: "google.protobuf.FloatValue";
value: DescField & {
fieldKind: "scalar";
};
} | {
typeName: "google.protobuf.Int64Value";
value: DescField & {
fieldKind: "scalar";
};
} | {
typeName: "google.protobuf.UInt64Value";
value: DescField & {
fieldKind: "scalar";
};
} | {
typeName: "google.protobuf.Int32Value";
value: DescField & {
fieldKind: "scalar";
};
} | {
typeName: "google.protobuf.UInt32Value";
value: DescField & {
fieldKind: "scalar";
};
} | {
typeName: "google.protobuf.BoolValue";
value: DescField & {
fieldKind: "scalar";
};
} | {
typeName: "google.protobuf.StringValue";
value: DescField & {
fieldKind: "scalar";
};
} | {
typeName: "google.protobuf.BytesValue";
value: DescField & {
fieldKind: "scalar";
};
};
/**
* @deprecated please use reifyWkt from @bufbuild/protoplugin/ecmascript instead
*
* Reifies a given DescMessage into a more concrete object representing its
* respective well-known type. The returned object will contain properties
* representing the WKT's defined fields.
*
* Useful during code generation when immediate access to a particular field
* is needed without having to search the object's typename and DescField list.
*
* Returns undefined if the WKT cannot be completely constructed via the
* DescMessage.
*/
export declare function reifyWkt(message: DescMessage): DescWkt | undefined;
export {};
+172
View File
@@ -0,0 +1,172 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.reifyWkt = void 0;
const scalar_js_1 = require("../scalar.js");
/**
* @deprecated please use reifyWkt from @bufbuild/protoplugin/ecmascript instead
*
* Reifies a given DescMessage into a more concrete object representing its
* respective well-known type. The returned object will contain properties
* representing the WKT's defined fields.
*
* Useful during code generation when immediate access to a particular field
* is needed without having to search the object's typename and DescField list.
*
* Returns undefined if the WKT cannot be completely constructed via the
* DescMessage.
*/
function reifyWkt(message) {
switch (message.typeName) {
case "google.protobuf.Any": {
const typeUrl = message.fields.find((f) => f.number == 1 &&
f.fieldKind == "scalar" &&
f.scalar === scalar_js_1.ScalarType.STRING);
const value = message.fields.find((f) => f.number == 2 &&
f.fieldKind == "scalar" &&
f.scalar === scalar_js_1.ScalarType.BYTES);
if (typeUrl && value) {
return {
typeName: message.typeName,
typeUrl,
value,
};
}
break;
}
case "google.protobuf.Timestamp": {
const seconds = message.fields.find((f) => f.number == 1 &&
f.fieldKind == "scalar" &&
f.scalar === scalar_js_1.ScalarType.INT64);
const nanos = message.fields.find((f) => f.number == 2 &&
f.fieldKind == "scalar" &&
f.scalar === scalar_js_1.ScalarType.INT32);
if (seconds && nanos) {
return {
typeName: message.typeName,
seconds,
nanos,
};
}
break;
}
case "google.protobuf.Duration": {
const seconds = message.fields.find((f) => f.number == 1 &&
f.fieldKind == "scalar" &&
f.scalar === scalar_js_1.ScalarType.INT64);
const nanos = message.fields.find((f) => f.number == 2 &&
f.fieldKind == "scalar" &&
f.scalar === scalar_js_1.ScalarType.INT32);
if (seconds && nanos) {
return {
typeName: message.typeName,
seconds,
nanos,
};
}
break;
}
case "google.protobuf.Struct": {
const fields = message.fields.find((f) => f.number == 1 && !f.repeated);
if ((fields === null || fields === void 0 ? void 0 : fields.fieldKind) !== "map" ||
fields.mapValue.kind !== "message" ||
fields.mapValue.message.typeName !== "google.protobuf.Value") {
break;
}
return { typeName: message.typeName, fields };
}
case "google.protobuf.Value": {
const kind = message.oneofs.find((o) => o.name === "kind");
const nullValue = message.fields.find((f) => f.number == 1 && f.oneof === kind);
if ((nullValue === null || nullValue === void 0 ? void 0 : nullValue.fieldKind) !== "enum" ||
nullValue.enum.typeName !== "google.protobuf.NullValue") {
return undefined;
}
const numberValue = message.fields.find((f) => f.number == 2 &&
f.fieldKind == "scalar" &&
f.scalar === scalar_js_1.ScalarType.DOUBLE &&
f.oneof === kind);
const stringValue = message.fields.find((f) => f.number == 3 &&
f.fieldKind == "scalar" &&
f.scalar === scalar_js_1.ScalarType.STRING &&
f.oneof === kind);
const boolValue = message.fields.find((f) => f.number == 4 &&
f.fieldKind == "scalar" &&
f.scalar === scalar_js_1.ScalarType.BOOL &&
f.oneof === kind);
const structValue = message.fields.find((f) => f.number == 5 && f.oneof === kind);
if ((structValue === null || structValue === void 0 ? void 0 : structValue.fieldKind) !== "message" ||
structValue.message.typeName !== "google.protobuf.Struct") {
return undefined;
}
const listValue = message.fields.find((f) => f.number == 6 && f.oneof === kind);
if ((listValue === null || listValue === void 0 ? void 0 : listValue.fieldKind) !== "message" ||
listValue.message.typeName !== "google.protobuf.ListValue") {
return undefined;
}
if (kind && numberValue && stringValue && boolValue) {
return {
typeName: message.typeName,
kind,
nullValue,
numberValue,
stringValue,
boolValue,
structValue,
listValue,
};
}
break;
}
case "google.protobuf.ListValue": {
const values = message.fields.find((f) => f.number == 1 && f.repeated);
if ((values === null || values === void 0 ? void 0 : values.fieldKind) != "message" ||
values.message.typeName !== "google.protobuf.Value") {
break;
}
return { typeName: message.typeName, values };
}
case "google.protobuf.FieldMask": {
const paths = message.fields.find((f) => f.number == 1 &&
f.fieldKind == "scalar" &&
f.scalar === scalar_js_1.ScalarType.STRING &&
f.repeated);
if (paths) {
return { typeName: message.typeName, paths };
}
break;
}
case "google.protobuf.DoubleValue":
case "google.protobuf.FloatValue":
case "google.protobuf.Int64Value":
case "google.protobuf.UInt64Value":
case "google.protobuf.Int32Value":
case "google.protobuf.UInt32Value":
case "google.protobuf.BoolValue":
case "google.protobuf.StringValue":
case "google.protobuf.BytesValue": {
const value = message.fields.find((f) => f.number == 1 && f.name == "value");
if (!value) {
break;
}
if (value.fieldKind !== "scalar") {
break;
}
return { typeName: message.typeName, value };
}
}
return undefined;
}
exports.reifyWkt = reifyWkt;
+18
View File
@@ -0,0 +1,18 @@
import { LongType, ScalarType } from "../scalar.js";
import type { ScalarValue } from "../scalar.js";
/**
* Returns true if both scalar values are equal.
*/
export declare function scalarEquals(type: ScalarType, a: string | boolean | number | bigint | Uint8Array | undefined, b: string | boolean | number | bigint | Uint8Array | undefined): boolean;
/**
* Returns the zero value for the given scalar type.
*/
export declare function scalarZeroValue<T extends ScalarType, L extends LongType>(type: T, longType: L): ScalarValue<T, L>;
/**
* Returns true for a zero-value. For example, an integer has the zero-value `0`,
* a boolean is `false`, a string is `""`, and bytes is an empty Uint8Array.
*
* In proto3, zero-values are not written to the wire, unless the field is
* optional or repeated.
*/
export declare function isScalarZeroValue(type: ScalarType, value: unknown): boolean;
+105
View File
@@ -0,0 +1,105 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.isScalarZeroValue = exports.scalarZeroValue = exports.scalarEquals = void 0;
const proto_int64_js_1 = require("../proto-int64.js");
const scalar_js_1 = require("../scalar.js");
/**
* Returns true if both scalar values are equal.
*/
function scalarEquals(type, a, b) {
if (a === b) {
// This correctly matches equal values except BYTES and (possibly) 64-bit integers.
return true;
}
// Special case BYTES - we need to compare each byte individually
if (type == scalar_js_1.ScalarType.BYTES) {
if (!(a instanceof Uint8Array) || !(b instanceof Uint8Array)) {
return false;
}
if (a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
// Special case 64-bit integers - we support number, string and bigint representation.
// eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check
switch (type) {
case scalar_js_1.ScalarType.UINT64:
case scalar_js_1.ScalarType.FIXED64:
case scalar_js_1.ScalarType.INT64:
case scalar_js_1.ScalarType.SFIXED64:
case scalar_js_1.ScalarType.SINT64:
// Loose comparison will match between 0n, 0 and "0".
return a == b;
}
// Anything that hasn't been caught by strict comparison or special cased
// BYTES and 64-bit integers is not equal.
return false;
}
exports.scalarEquals = scalarEquals;
/**
* Returns the zero value for the given scalar type.
*/
function scalarZeroValue(type, longType) {
switch (type) {
case scalar_js_1.ScalarType.BOOL:
return false;
case scalar_js_1.ScalarType.UINT64:
case scalar_js_1.ScalarType.FIXED64:
case scalar_js_1.ScalarType.INT64:
case scalar_js_1.ScalarType.SFIXED64:
case scalar_js_1.ScalarType.SINT64:
// eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison -- acceptable since it's covered by tests
return (longType == 0 ? proto_int64_js_1.protoInt64.zero : "0");
case scalar_js_1.ScalarType.DOUBLE:
case scalar_js_1.ScalarType.FLOAT:
return 0.0;
case scalar_js_1.ScalarType.BYTES:
return new Uint8Array(0);
case scalar_js_1.ScalarType.STRING:
return "";
default:
// Handles INT32, UINT32, SINT32, FIXED32, SFIXED32.
// We do not use individual cases to save a few bytes code size.
return 0;
}
}
exports.scalarZeroValue = scalarZeroValue;
/**
* Returns true for a zero-value. For example, an integer has the zero-value `0`,
* a boolean is `false`, a string is `""`, and bytes is an empty Uint8Array.
*
* In proto3, zero-values are not written to the wire, unless the field is
* optional or repeated.
*/
function isScalarZeroValue(type, value) {
switch (type) {
case scalar_js_1.ScalarType.BOOL:
return value === false;
case scalar_js_1.ScalarType.STRING:
return value === "";
case scalar_js_1.ScalarType.BYTES:
return value instanceof Uint8Array && !value.byteLength;
default:
return value == 0; // Loose comparison matches 0n, 0 and "0"
}
}
exports.isScalarZeroValue = isScalarZeroValue;
+4
View File
@@ -0,0 +1,4 @@
import type { DescEnum } from "../descriptor-set.js";
import { ScalarType } from "../scalar.js";
export declare function parseTextFormatEnumValue(descEnum: DescEnum, value: string): number;
export declare function parseTextFormatScalarValue(type: ScalarType, value: string): number | boolean | string | bigint | Uint8Array;
+189
View File
@@ -0,0 +1,189 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseTextFormatScalarValue = exports.parseTextFormatEnumValue = void 0;
const assert_js_1 = require("./assert.js");
const proto_int64_js_1 = require("../proto-int64.js");
const scalar_js_1 = require("../scalar.js");
function parseTextFormatEnumValue(descEnum, value) {
const enumValue = descEnum.values.find((v) => v.name === value);
(0, assert_js_1.assert)(enumValue, `cannot parse ${descEnum.name} default value: ${value}`);
return enumValue.number;
}
exports.parseTextFormatEnumValue = parseTextFormatEnumValue;
function parseTextFormatScalarValue(type, value) {
switch (type) {
case scalar_js_1.ScalarType.STRING:
return value;
case scalar_js_1.ScalarType.BYTES: {
const u = unescapeBytesDefaultValue(value);
if (u === false) {
throw new Error(`cannot parse ${scalar_js_1.ScalarType[type]} default value: ${value}`);
}
return u;
}
case scalar_js_1.ScalarType.INT64:
case scalar_js_1.ScalarType.SFIXED64:
case scalar_js_1.ScalarType.SINT64:
return proto_int64_js_1.protoInt64.parse(value);
case scalar_js_1.ScalarType.UINT64:
case scalar_js_1.ScalarType.FIXED64:
return proto_int64_js_1.protoInt64.uParse(value);
case scalar_js_1.ScalarType.DOUBLE:
case scalar_js_1.ScalarType.FLOAT:
switch (value) {
case "inf":
return Number.POSITIVE_INFINITY;
case "-inf":
return Number.NEGATIVE_INFINITY;
case "nan":
return Number.NaN;
default:
return parseFloat(value);
}
case scalar_js_1.ScalarType.BOOL:
return value === "true";
case scalar_js_1.ScalarType.INT32:
case scalar_js_1.ScalarType.UINT32:
case scalar_js_1.ScalarType.SINT32:
case scalar_js_1.ScalarType.FIXED32:
case scalar_js_1.ScalarType.SFIXED32:
return parseInt(value, 10);
}
}
exports.parseTextFormatScalarValue = parseTextFormatScalarValue;
/**
* Parses a text-encoded default value (proto2) of a BYTES field.
*/
function unescapeBytesDefaultValue(str) {
const b = [];
const input = {
tail: str,
c: "",
next() {
if (this.tail.length == 0) {
return false;
}
this.c = this.tail[0];
this.tail = this.tail.substring(1);
return true;
},
take(n) {
if (this.tail.length >= n) {
const r = this.tail.substring(0, n);
this.tail = this.tail.substring(n);
return r;
}
return false;
},
};
while (input.next()) {
switch (input.c) {
case "\\":
if (input.next()) {
switch (input.c) {
case "\\":
b.push(input.c.charCodeAt(0));
break;
case "b":
b.push(0x08);
break;
case "f":
b.push(0x0c);
break;
case "n":
b.push(0x0a);
break;
case "r":
b.push(0x0d);
break;
case "t":
b.push(0x09);
break;
case "v":
b.push(0x0b);
break;
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7": {
const s = input.c;
const t = input.take(2);
if (t === false) {
return false;
}
const n = parseInt(s + t, 8);
if (isNaN(n)) {
return false;
}
b.push(n);
break;
}
case "x": {
const s = input.c;
const t = input.take(2);
if (t === false) {
return false;
}
const n = parseInt(s + t, 16);
if (isNaN(n)) {
return false;
}
b.push(n);
break;
}
case "u": {
const s = input.c;
const t = input.take(4);
if (t === false) {
return false;
}
const n = parseInt(s + t, 16);
if (isNaN(n)) {
return false;
}
const chunk = new Uint8Array(4);
const view = new DataView(chunk.buffer);
view.setInt32(0, n, true);
b.push(chunk[0], chunk[1], chunk[2], chunk[3]);
break;
}
case "U": {
const s = input.c;
const t = input.take(8);
if (t === false) {
return false;
}
const tc = proto_int64_js_1.protoInt64.uEnc(s + t);
const chunk = new Uint8Array(8);
const view = new DataView(chunk.buffer);
view.setInt32(0, tc.lo, true);
view.setInt32(4, tc.hi, true);
b.push(chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5], chunk[6], chunk[7]);
break;
}
}
}
break;
default:
b.push(input.c.charCodeAt(0));
}
}
return new Uint8Array(b);
}
+2
View File
@@ -0,0 +1,2 @@
import type { Util } from "./util.js";
export declare function makeUtilCommon(): Omit<Util, "newFieldList" | "initFields">;
+247
View File
@@ -0,0 +1,247 @@
"use strict";
// Copyright 2021-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeUtilCommon = void 0;
const enum_js_1 = require("./enum.js");
const scalars_js_1 = require("./scalars.js");
const scalar_js_1 = require("../scalar.js");
const is_message_js_1 = require("../is-message.js");
/* eslint-disable @typescript-eslint/no-explicit-any,@typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-return,@typescript-eslint/no-unsafe-argument,no-case-declarations */
function makeUtilCommon() {
return {
setEnumType: enum_js_1.setEnumType,
initPartial(source, target) {
if (source === undefined) {
return;
}
const type = target.getType();
for (const member of type.fields.byMember()) {
const localName = member.localName, t = target, s = source;
if (s[localName] == null) {
// TODO if source is a Message instance, we should use isFieldSet() here to support future field presence
continue;
}
switch (member.kind) {
case "oneof":
const sk = s[localName].case;
if (sk === undefined) {
continue;
}
const sourceField = member.findField(sk);
let val = s[localName].value;
if (sourceField &&
sourceField.kind == "message" &&
!(0, is_message_js_1.isMessage)(val, sourceField.T)) {
val = new sourceField.T(val);
}
else if (sourceField &&
sourceField.kind === "scalar" &&
sourceField.T === scalar_js_1.ScalarType.BYTES) {
val = toU8Arr(val);
}
t[localName] = { case: sk, value: val };
break;
case "scalar":
case "enum":
let copy = s[localName];
if (member.T === scalar_js_1.ScalarType.BYTES) {
copy = member.repeated
? copy.map(toU8Arr)
: toU8Arr(copy);
}
t[localName] = copy;
break;
case "map":
switch (member.V.kind) {
case "scalar":
case "enum":
if (member.V.T === scalar_js_1.ScalarType.BYTES) {
for (const [k, v] of Object.entries(s[localName])) {
t[localName][k] = toU8Arr(v);
}
}
else {
Object.assign(t[localName], s[localName]);
}
break;
case "message":
const messageType = member.V.T;
for (const k of Object.keys(s[localName])) {
let val = s[localName][k];
if (!messageType.fieldWrapper) {
// We only take partial input for messages that are not a wrapper type.
// For those messages, we recursively normalize the partial input.
val = new messageType(val);
}
t[localName][k] = val;
}
break;
}
break;
case "message":
const mt = member.T;
if (member.repeated) {
t[localName] = s[localName].map((val) => (0, is_message_js_1.isMessage)(val, mt) ? val : new mt(val));
}
else {
const val = s[localName];
if (mt.fieldWrapper) {
if (
// We can't use BytesValue.typeName as that will create a circular import
mt.typeName === "google.protobuf.BytesValue") {
t[localName] = toU8Arr(val);
}
else {
t[localName] = val;
}
}
else {
t[localName] = (0, is_message_js_1.isMessage)(val, mt) ? val : new mt(val);
}
}
break;
}
}
},
// TODO use isFieldSet() here to support future field presence
equals(type, a, b) {
if (a === b) {
return true;
}
if (!a || !b) {
return false;
}
return type.fields.byMember().every((m) => {
const va = a[m.localName];
const vb = b[m.localName];
if (m.repeated) {
if (va.length !== vb.length) {
return false;
}
// eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check -- repeated fields are never "map"
switch (m.kind) {
case "message":
return va.every((a, i) => m.T.equals(a, vb[i]));
case "scalar":
return va.every((a, i) => (0, scalars_js_1.scalarEquals)(m.T, a, vb[i]));
case "enum":
return va.every((a, i) => (0, scalars_js_1.scalarEquals)(scalar_js_1.ScalarType.INT32, a, vb[i]));
}
throw new Error(`repeated cannot contain ${m.kind}`);
}
switch (m.kind) {
case "message":
let a = va;
let b = vb;
if (m.T.fieldWrapper) {
if (a !== undefined && !(0, is_message_js_1.isMessage)(a)) {
a = m.T.fieldWrapper.wrapField(a);
}
if (b !== undefined && !(0, is_message_js_1.isMessage)(b)) {
b = m.T.fieldWrapper.wrapField(b);
}
}
return m.T.equals(a, b);
case "enum":
return (0, scalars_js_1.scalarEquals)(scalar_js_1.ScalarType.INT32, va, vb);
case "scalar":
return (0, scalars_js_1.scalarEquals)(m.T, va, vb);
case "oneof":
if (va.case !== vb.case) {
return false;
}
const s = m.findField(va.case);
if (s === undefined) {
return true;
}
// eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check -- oneof fields are never "map"
switch (s.kind) {
case "message":
return s.T.equals(va.value, vb.value);
case "enum":
return (0, scalars_js_1.scalarEquals)(scalar_js_1.ScalarType.INT32, va.value, vb.value);
case "scalar":
return (0, scalars_js_1.scalarEquals)(s.T, va.value, vb.value);
}
throw new Error(`oneof cannot contain ${s.kind}`);
case "map":
const keys = Object.keys(va).concat(Object.keys(vb));
switch (m.V.kind) {
case "message":
const messageType = m.V.T;
return keys.every((k) => messageType.equals(va[k], vb[k]));
case "enum":
return keys.every((k) => (0, scalars_js_1.scalarEquals)(scalar_js_1.ScalarType.INT32, va[k], vb[k]));
case "scalar":
const scalarType = m.V.T;
return keys.every((k) => (0, scalars_js_1.scalarEquals)(scalarType, va[k], vb[k]));
}
break;
}
});
},
// TODO use isFieldSet() here to support future field presence
clone(message) {
const type = message.getType(), target = new type(), any = target;
for (const member of type.fields.byMember()) {
const source = message[member.localName];
let copy;
if (member.repeated) {
copy = source.map(cloneSingularField);
}
else if (member.kind == "map") {
copy = any[member.localName];
for (const [key, v] of Object.entries(source)) {
copy[key] = cloneSingularField(v);
}
}
else if (member.kind == "oneof") {
const f = member.findField(source.case);
copy = f
? { case: source.case, value: cloneSingularField(source.value) }
: { case: undefined };
}
else {
copy = cloneSingularField(source);
}
any[member.localName] = copy;
}
for (const uf of type.runtime.bin.listUnknownFields(message)) {
type.runtime.bin.onUnknownField(any, uf.no, uf.wireType, uf.data);
}
return target;
},
};
}
exports.makeUtilCommon = makeUtilCommon;
// clone a single field value - i.e. the element type of repeated fields, the value type of maps
function cloneSingularField(value) {
if (value === undefined) {
return value;
}
if ((0, is_message_js_1.isMessage)(value)) {
return value.clone();
}
if (value instanceof Uint8Array) {
const c = new Uint8Array(value.byteLength);
c.set(value);
return c;
}
return value;
}
// converts any ArrayLike<number> to Uint8Array if necessary.
function toU8Arr(input) {
return input instanceof Uint8Array ? input : new Uint8Array(input);
}

Some files were not shown because too many files have changed in this diff Show More