rearrage_stuff

This commit is contained in:
Kim Ravn Hansen
2025-09-16 11:26:40 +02:00
parent 40e8c5e0ab
commit 3f11ebe6dc
4937 changed files with 1146031 additions and 134 deletions

View File

@@ -0,0 +1,23 @@
/**
* Decodes a base64 string to a byte array.
*
* - ignores white-space, including line breaks and tabs
* - allows inner padding (can decode concatenated base64 strings)
* - does not require padding
* - understands base64url encoding:
* "-" instead of "+",
* "_" instead of "/",
* no padding
*/
export declare function base64Decode(base64Str: string): Uint8Array<ArrayBuffer>;
/**
* Encode a byte array to a base64 string.
*
* By default, this function uses the standard base64 encoding with padding.
*
* To encode without padding, use encoding = "std_raw".
*
* To encode with the URL encoding, use encoding = "url", which replaces the
* characters +/ by their URL-safe counterparts -_, and omits padding.
*/
export declare function base64Encode(bytes: Uint8Array, encoding?: "std" | "std_raw" | "url"): string;

View File

@@ -0,0 +1,156 @@
"use strict";
// Copyright 2021-2025 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.base64Decode = base64Decode;
exports.base64Encode = base64Encode;
/**
* Decodes a base64 string to a byte array.
*
* - ignores white-space, including line breaks and tabs
* - allows inner padding (can decode concatenated base64 strings)
* - does not require padding
* - understands base64url encoding:
* "-" instead of "+",
* "_" instead of "/",
* no padding
*/
function base64Decode(base64Str) {
const table = getDecodeTable();
// estimate byte size, not accounting for inner padding and whitespace
let es = (base64Str.length * 3) / 4;
if (base64Str[base64Str.length - 2] == "=")
es -= 2;
else if (base64Str[base64Str.length - 1] == "=")
es -= 1;
let bytes = new Uint8Array(es), bytePos = 0, // position in byte array
groupPos = 0, // position in base64 group
b, // current byte
p = 0; // previous byte
for (let i = 0; i < base64Str.length; i++) {
b = table[base64Str.charCodeAt(i)];
if (b === undefined) {
switch (base64Str[i]) {
// @ts-ignore TS7029: Fallthrough case in switch -- ignore instead of expect-error for compiler settings without noFallthroughCasesInSwitch: true
case "=":
groupPos = 0; // reset state when padding found
case "\n":
case "\r":
case "\t":
case " ":
continue; // skip white-space, and padding
default:
throw Error("invalid base64 string");
}
}
switch (groupPos) {
case 0:
p = b;
groupPos = 1;
break;
case 1:
bytes[bytePos++] = (p << 2) | ((b & 48) >> 4);
p = b;
groupPos = 2;
break;
case 2:
bytes[bytePos++] = ((p & 15) << 4) | ((b & 60) >> 2);
p = b;
groupPos = 3;
break;
case 3:
bytes[bytePos++] = ((p & 3) << 6) | b;
groupPos = 0;
break;
}
}
if (groupPos == 1)
throw Error("invalid base64 string");
return bytes.subarray(0, bytePos);
}
/**
* Encode a byte array to a base64 string.
*
* By default, this function uses the standard base64 encoding with padding.
*
* To encode without padding, use encoding = "std_raw".
*
* To encode with the URL encoding, use encoding = "url", which replaces the
* characters +/ by their URL-safe counterparts -_, and omits padding.
*/
function base64Encode(bytes, encoding = "std") {
const table = getEncodeTable(encoding);
const pad = encoding == "std";
let base64 = "", groupPos = 0, // position in base64 group
b, // current byte
p = 0; // carry over from previous byte
for (let i = 0; i < bytes.length; i++) {
b = bytes[i];
switch (groupPos) {
case 0:
base64 += table[b >> 2];
p = (b & 3) << 4;
groupPos = 1;
break;
case 1:
base64 += table[p | (b >> 4)];
p = (b & 15) << 2;
groupPos = 2;
break;
case 2:
base64 += table[p | (b >> 6)];
base64 += table[b & 63];
groupPos = 0;
break;
}
}
// add output padding
if (groupPos) {
base64 += table[p];
if (pad) {
base64 += "=";
if (groupPos == 1)
base64 += "=";
}
}
return base64;
}
// lookup table from base64 character to byte
let encodeTableStd;
let encodeTableUrl;
// lookup table from base64 character *code* to byte because lookup by number is fast
let decodeTable;
function getEncodeTable(encoding) {
if (!encodeTableStd) {
encodeTableStd =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
encodeTableUrl = encodeTableStd.slice(0, -2).concat("-", "_");
}
return encoding == "url"
? // biome-ignore lint/style/noNonNullAssertion: TS fails to narrow down
encodeTableUrl
: encodeTableStd;
}
function getDecodeTable() {
if (!decodeTable) {
decodeTable = [];
const encodeTable = getEncodeTable("std");
for (let i = 0; i < encodeTable.length; i++)
decodeTable[encodeTable[i].charCodeAt(0)] = i;
// support base64url variants
decodeTable["-".charCodeAt(0)] = encodeTable.indexOf("+");
decodeTable["_".charCodeAt(0)] = encodeTable.indexOf("/");
}
return decodeTable;
}

View File

@@ -0,0 +1,264 @@
/**
* 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
}
/**
* Maximum value for a 32-bit floating point value (Protobuf FLOAT).
*/
export declare const FLOAT32_MAX = 3.4028234663852886e+38;
/**
* Minimum value for a 32-bit floating point value (Protobuf FLOAT).
*/
export declare const FLOAT32_MIN = -3.4028234663852886e+38;
/**
* Maximum value for an unsigned 32-bit integer (Protobuf UINT32, FIXED32).
*/
export declare const UINT32_MAX = 4294967295;
/**
* Maximum value for a signed 32-bit integer (Protobuf INT32, SFIXED32, SINT32).
*/
export declare const INT32_MAX = 2147483647;
/**
* Minimum value for a signed 32-bit integer (Protobuf INT32, SFIXED32, SINT32).
*/
export declare const INT32_MIN = -2147483648;
export declare class BinaryWriter {
private readonly encodeUtf8;
/**
* 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;
constructor(encodeUtf8?: (text: string) => Uint8Array);
/**
* Return all bytes written and reset this writer.
*/
finish(): Uint8Array<ArrayBuffer>;
/**
* Start a new fork for length-delimited data like a message
* or a packed repeated field.
*
* Must be joined later with `join()`.
*/
fork(): this;
/**
* Join the last fork. Write its length and bytes, then
* return to the previous state.
*/
join(): this;
/**
* 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): this;
/**
* Write a chunk of raw bytes.
*/
raw(chunk: Uint8Array): this;
/**
* Write a `uint32` value, an unsigned 32 bit varint.
*/
uint32(value: number): this;
/**
* Write a `int32` value, a signed 32 bit varint.
*/
int32(value: number): this;
/**
* Write a `bool` value, a variant.
*/
bool(value: boolean): this;
/**
* Write a `bytes` value, length-delimited arbitrary data.
*/
bytes(value: Uint8Array): this;
/**
* Write a `string` value, length-delimited data converted to UTF-8 text.
*/
string(value: string): this;
/**
* Write a `float` value, 32-bit floating point number.
*/
float(value: number): this;
/**
* Write a `double` value, a 64-bit floating point number.
*/
double(value: number): this;
/**
* Write a `fixed32` value, an unsigned, fixed-length 32-bit integer.
*/
fixed32(value: number): this;
/**
* Write a `sfixed32` value, a signed, fixed-length 32-bit integer.
*/
sfixed32(value: number): this;
/**
* Write a `sint32` value, a signed, zigzag-encoded 32-bit varint.
*/
sint32(value: number): this;
/**
* Write a `fixed64` value, a signed, fixed-length 64-bit integer.
*/
sfixed64(value: string | number | bigint): this;
/**
* Write a `fixed64` value, an unsigned, fixed-length 64 bit integer.
*/
fixed64(value: string | number | bigint): this;
/**
* Write a `int64` value, a signed 64-bit varint.
*/
int64(value: string | number | bigint): this;
/**
* Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint.
*/
sint64(value: string | number | bigint): this;
/**
* Write a `uint64` value, an unsigned 64-bit varint.
*/
uint64(value: string | number | bigint): this;
}
export declare class BinaryReader {
private readonly decodeUtf8;
/**
* Current position.
*/
pos: number;
/**
* Number of bytes available in this reader.
*/
readonly len: number;
protected readonly buf: Uint8Array;
private readonly view;
constructor(buf: Uint8Array, decodeUtf8?: (bytes: Uint8Array) => string);
/**
* 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;
}

View File

@@ -0,0 +1,515 @@
"use strict";
// Copyright 2021-2025 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.INT32_MIN = exports.INT32_MAX = exports.UINT32_MAX = exports.FLOAT32_MIN = exports.FLOAT32_MAX = exports.WireType = void 0;
const varint_js_1 = require("./varint.js");
const proto_int64_js_1 = require("../proto-int64.js");
const text_encoding_js_1 = require("./text-encoding.js");
/**
* 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 = {}));
/**
* Maximum value for a 32-bit floating point value (Protobuf FLOAT).
*/
exports.FLOAT32_MAX = 3.4028234663852886e38;
/**
* Minimum value for a 32-bit floating point value (Protobuf FLOAT).
*/
exports.FLOAT32_MIN = -3.4028234663852886e38;
/**
* Maximum value for an unsigned 32-bit integer (Protobuf UINT32, FIXED32).
*/
exports.UINT32_MAX = 0xffffffff;
/**
* Maximum value for a signed 32-bit integer (Protobuf INT32, SFIXED32, SINT32).
*/
exports.INT32_MAX = 0x7fffffff;
/**
* Minimum value for a signed 32-bit integer (Protobuf INT32, SFIXED32, SINT32).
*/
exports.INT32_MIN = -0x80000000;
class BinaryWriter {
constructor(encodeUtf8 = (0, text_encoding_js_1.getTextEncoding)().encodeUtf8) {
this.encodeUtf8 = encodeUtf8;
/**
* Previous fork states.
*/
this.stack = [];
this.chunks = [];
this.buf = [];
}
/**
* Return all bytes written and reset this writer.
*/
finish() {
if (this.buf.length) {
this.chunks.push(new Uint8Array(this.buf)); // flush the buffer
this.buf = [];
}
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) {
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) {
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.encodeUtf8(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) {
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) {
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) {
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) {
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) {
const 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) {
const 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, decodeUtf8 = (0, text_encoding_js_1.getTextEncoding)().decodeUtf8) {
this.decodeUtf8 = decodeUtf8;
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;
this.buf = buf;
this.len = buf.length;
this.pos = 0;
this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
}
/**
* 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;
// @ts-ignore TS7029: Fallthrough case in switch -- ignore instead of expect-error for compiler settings without noFallthroughCasesInSwitch: true
case WireType.Bit64:
this.pos += 4;
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() {
// biome-ignore lint/suspicious/noAssignInExpressions: no
return this.view.getUint32((this.pos += 4) - 4, true);
}
/**
* Read a `sfixed32` field, a signed, fixed-length 32-bit integer.
*/
sfixed32() {
// biome-ignore lint/suspicious/noAssignInExpressions: no
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() {
// biome-ignore lint/suspicious/noAssignInExpressions: no
return this.view.getFloat32((this.pos += 4) - 4, true);
}
/**
* Read a `double` field, a 64-bit floating point number.
*/
double() {
// biome-ignore lint/suspicious/noAssignInExpressions: no
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.decodeUtf8(this.bytes());
}
}
exports.BinaryReader = BinaryReader;
/**
* Assert a valid signed protobuf 32-bit integer as a number or string.
*/
function assertInt32(arg) {
if (typeof arg == "string") {
arg = Number(arg);
}
else if (typeof arg != "number") {
throw new Error("invalid int32: " + typeof arg);
}
if (!Number.isInteger(arg) ||
arg > exports.INT32_MAX ||
arg < exports.INT32_MIN)
throw new Error("invalid int32: " + arg);
}
/**
* Assert a valid unsigned protobuf 32-bit integer as a number or string.
*/
function assertUInt32(arg) {
if (typeof arg == "string") {
arg = Number(arg);
}
else if (typeof arg != "number") {
throw new Error("invalid uint32: " + typeof arg);
}
if (!Number.isInteger(arg) ||
arg > exports.UINT32_MAX ||
arg < 0)
throw new Error("invalid uint32: " + arg);
}
/**
* Assert a valid protobuf float value as a number or string.
*/
function assertFloat32(arg) {
if (typeof arg == "string") {
const o = arg;
arg = Number(arg);
if (Number.isNaN(arg) && o !== "NaN") {
throw new Error("invalid float32: " + o);
}
}
else if (typeof arg != "number") {
throw new Error("invalid float32: " + typeof arg);
}
if (Number.isFinite(arg) &&
(arg > exports.FLOAT32_MAX || arg < exports.FLOAT32_MIN))
throw new Error("invalid float32: " + arg);
}

View File

@@ -0,0 +1,5 @@
export * from "./binary-encoding.js";
export * from "./base64-encoding.js";
export * from "./text-encoding.js";
export * from "./text-format.js";
export * from "./size-delimited.js";

34
node_modules/@bufbuild/protobuf/dist/cjs/wire/index.js generated vendored Normal file
View File

@@ -0,0 +1,34 @@
"use strict";
// Copyright 2021-2025 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 });
__exportStar(require("./binary-encoding.js"), exports);
__exportStar(require("./base64-encoding.js"), exports);
__exportStar(require("./text-encoding.js"), exports);
__exportStar(require("./text-format.js"), exports);
__exportStar(require("./size-delimited.js"), exports);

View File

@@ -0,0 +1,51 @@
import type { DescMessage } from "../descriptors.js";
import type { BinaryWriteOptions } from "../to-binary.js";
import type { MessageShape } from "../types.js";
import type { BinaryReadOptions } from "../from-binary.js";
/**
* Serialize a message, prefixing it with its size.
*
* A size-delimited message is a varint size in bytes, followed by exactly
* that many bytes of a message serialized with the binary format.
*
* This size-delimited format is compatible with other implementations.
* For details, see https://github.com/protocolbuffers/protobuf/issues/10229
*/
export declare function sizeDelimitedEncode<Desc extends DescMessage>(messageDesc: Desc, message: MessageShape<Desc>, options?: BinaryWriteOptions): Uint8Array;
/**
* Parse a stream of size-delimited messages.
*
* A size-delimited message is a varint size in bytes, followed by exactly
* that many bytes of a message serialized with the binary format.
*
* This size-delimited format is compatible with other implementations.
* For details, see https://github.com/protocolbuffers/protobuf/issues/10229
*/
export declare function sizeDelimitedDecodeStream<Desc extends DescMessage>(messageDesc: Desc, iterable: AsyncIterable<Uint8Array>, options?: BinaryReadOptions): AsyncIterableIterator<MessageShape<Desc>>;
/**
* Decodes the size from the given size-delimited message, which may be
* incomplete.
*
* Returns an object with the following properties:
* - size: The size of the delimited message in bytes
* - offset: The offset in the given byte array where the message starts
* - eof: true
*
* If the size-delimited data does not include all bytes of the varint size,
* the following object is returned:
* - size: null
* - offset: null
* - eof: false
*
* This function can be used to implement parsing of size-delimited messages
* from a stream.
*/
export declare function sizeDelimitedPeek(data: Uint8Array): {
readonly eof: false;
readonly size: number;
readonly offset: number;
} | {
readonly eof: true;
readonly size: null;
readonly offset: null;
};

View File

@@ -0,0 +1,153 @@
"use strict";
// Copyright 2021-2025 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 __asyncValues = (this && this.__asyncValues) || function (o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sizeDelimitedEncode = sizeDelimitedEncode;
exports.sizeDelimitedDecodeStream = sizeDelimitedDecodeStream;
exports.sizeDelimitedPeek = sizeDelimitedPeek;
const to_binary_js_1 = require("../to-binary.js");
const binary_encoding_js_1 = require("./binary-encoding.js");
const from_binary_js_1 = require("../from-binary.js");
/**
* Serialize a message, prefixing it with its size.
*
* A size-delimited message is a varint size in bytes, followed by exactly
* that many bytes of a message serialized with the binary format.
*
* This size-delimited format is compatible with other implementations.
* For details, see https://github.com/protocolbuffers/protobuf/issues/10229
*/
function sizeDelimitedEncode(messageDesc, message, options) {
const writer = new binary_encoding_js_1.BinaryWriter();
writer.bytes((0, to_binary_js_1.toBinary)(messageDesc, message, options));
return writer.finish();
}
/**
* Parse a stream of size-delimited messages.
*
* A size-delimited message is a varint size in bytes, followed by exactly
* that many bytes of a message serialized with the binary format.
*
* This size-delimited format is compatible with other implementations.
* For details, see https://github.com/protocolbuffers/protobuf/issues/10229
*/
function sizeDelimitedDecodeStream(messageDesc, iterable, options) {
return __asyncGenerator(this, arguments, function* sizeDelimitedDecodeStream_1() {
var _a, e_1, _b, _c;
// append chunk to buffer, returning updated buffer
function append(buffer, chunk) {
const n = new Uint8Array(buffer.byteLength + chunk.byteLength);
n.set(buffer);
n.set(chunk, buffer.length);
return n;
}
let buffer = new Uint8Array(0);
try {
for (var _d = true, iterable_1 = __asyncValues(iterable), iterable_1_1; iterable_1_1 = yield __await(iterable_1.next()), _a = iterable_1_1.done, !_a; _d = true) {
_c = iterable_1_1.value;
_d = false;
const chunk = _c;
buffer = append(buffer, chunk);
for (;;) {
const size = sizeDelimitedPeek(buffer);
if (size.eof) {
// size is incomplete, buffer more data
break;
}
if (size.offset + size.size > buffer.byteLength) {
// message is incomplete, buffer more data
break;
}
yield yield __await((0, from_binary_js_1.fromBinary)(messageDesc, buffer.subarray(size.offset, size.offset + size.size), options));
buffer = buffer.subarray(size.offset + size.size);
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (!_d && !_a && (_b = iterable_1.return)) yield __await(_b.call(iterable_1));
}
finally { if (e_1) throw e_1.error; }
}
if (buffer.byteLength > 0) {
throw new Error("incomplete data");
}
});
}
/**
* Decodes the size from the given size-delimited message, which may be
* incomplete.
*
* Returns an object with the following properties:
* - size: The size of the delimited message in bytes
* - offset: The offset in the given byte array where the message starts
* - eof: true
*
* If the size-delimited data does not include all bytes of the varint size,
* the following object is returned:
* - size: null
* - offset: null
* - eof: false
*
* This function can be used to implement parsing of size-delimited messages
* from a stream.
*/
function sizeDelimitedPeek(data) {
const sizeEof = { eof: true, size: null, offset: null };
for (let i = 0; i < 10; i++) {
if (i > data.byteLength) {
return sizeEof;
}
if ((data[i] & 0x80) == 0) {
const reader = new binary_encoding_js_1.BinaryReader(data);
let size;
try {
size = reader.uint32();
}
catch (e) {
if (e instanceof RangeError) {
return sizeEof;
}
throw e;
}
return {
eof: false,
size,
offset: reader.pos,
};
}
}
throw new Error("invalid varint");
}

View File

@@ -0,0 +1,26 @@
interface TextEncoding {
/**
* Verify that the given text is valid UTF-8.
*/
checkUtf8: (text: string) => boolean;
/**
* Encode UTF-8 text to binary.
*/
encodeUtf8: (text: string) => Uint8Array<ArrayBuffer>;
/**
* Decode UTF-8 text from binary.
*/
decodeUtf8: (bytes: Uint8Array) => string;
}
/**
* Protobuf-ES requires the Text Encoding API to convert UTF-8 from and to
* binary. This WHATWG API is widely available, but it is not part of the
* ECMAScript standard. On runtimes where it is not available, use this
* function to provide your own implementation.
*
* Note that the Text Encoding API does not provide a way to validate UTF-8.
* Our implementation falls back to use encodeURIComponent().
*/
export declare function configureTextEncoding(textEncoding: TextEncoding): void;
export declare function getTextEncoding(): TextEncoding;
export {};

View File

@@ -0,0 +1,54 @@
"use strict";
// Copyright 2021-2025 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.configureTextEncoding = configureTextEncoding;
exports.getTextEncoding = getTextEncoding;
const symbol = Symbol.for("@bufbuild/protobuf/text-encoding");
/**
* Protobuf-ES requires the Text Encoding API to convert UTF-8 from and to
* binary. This WHATWG API is widely available, but it is not part of the
* ECMAScript standard. On runtimes where it is not available, use this
* function to provide your own implementation.
*
* Note that the Text Encoding API does not provide a way to validate UTF-8.
* Our implementation falls back to use encodeURIComponent().
*/
function configureTextEncoding(textEncoding) {
globalThis[symbol] = textEncoding;
}
function getTextEncoding() {
if (globalThis[symbol] == undefined) {
const te = new globalThis.TextEncoder();
const td = new globalThis.TextDecoder();
globalThis[symbol] = {
encodeUtf8(text) {
return te.encode(text);
},
decodeUtf8(bytes) {
return td.decode(bytes);
},
checkUtf8(text) {
try {
encodeURIComponent(text);
return true;
}
catch (_) {
return false;
}
},
};
}
return globalThis[symbol];
}

View File

@@ -0,0 +1,13 @@
import { type DescEnum, ScalarType } from "../descriptors.js";
/**
* Parse an enum value from the Protobuf text format.
*
* @private
*/
export declare function parseTextFormatEnumValue(descEnum: DescEnum, value: string): number;
/**
* Parse a scalar value from the Protobuf text format.
*
* @private
*/
export declare function parseTextFormatScalarValue(type: ScalarType, value: string): number | boolean | string | bigint | Uint8Array;

View File

@@ -0,0 +1,199 @@
"use strict";
// Copyright 2021-2025 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.parseTextFormatEnumValue = parseTextFormatEnumValue;
exports.parseTextFormatScalarValue = parseTextFormatScalarValue;
const descriptors_js_1 = require("../descriptors.js");
const proto_int64_js_1 = require("../proto-int64.js");
/**
* Parse an enum value from the Protobuf text format.
*
* @private
*/
function parseTextFormatEnumValue(descEnum, value) {
const enumValue = descEnum.values.find((v) => v.name === value);
if (!enumValue) {
throw new Error(`cannot parse ${descEnum} default value: ${value}`);
}
return enumValue.number;
}
/**
* Parse a scalar value from the Protobuf text format.
*
* @private
*/
function parseTextFormatScalarValue(type, value) {
switch (type) {
case descriptors_js_1.ScalarType.STRING:
return value;
case descriptors_js_1.ScalarType.BYTES: {
const u = unescapeBytesDefaultValue(value);
if (u === false) {
throw new Error(`cannot parse ${descriptors_js_1.ScalarType[type]} default value: ${value}`);
}
return u;
}
case descriptors_js_1.ScalarType.INT64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.SINT64:
return proto_int64_js_1.protoInt64.parse(value);
case descriptors_js_1.ScalarType.UINT64:
case descriptors_js_1.ScalarType.FIXED64:
return proto_int64_js_1.protoInt64.uParse(value);
case descriptors_js_1.ScalarType.DOUBLE:
case descriptors_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 descriptors_js_1.ScalarType.BOOL:
return value === "true";
case descriptors_js_1.ScalarType.INT32:
case descriptors_js_1.ScalarType.UINT32:
case descriptors_js_1.ScalarType.SINT32:
case descriptors_js_1.ScalarType.FIXED32:
case descriptors_js_1.ScalarType.SFIXED32:
return parseInt(value, 10);
}
}
/**
* 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 (Number.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 (Number.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 (Number.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);
}

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<T extends ReaderLike>(this: T): [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<T extends ReaderLike>(this: T): number;
type ReaderLike = {
buf: Uint8Array;
pos: number;
len: number;
assertBounds(): void;
};
export {};

322
node_modules/@bufbuild/protobuf/dist/cjs/wire/varint.js generated vendored Normal file
View File

@@ -0,0 +1,322 @@
"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.varint64read = varint64read;
exports.varint64write = varint64write;
exports.int64FromString = int64FromString;
exports.int64ToString = int64ToString;
exports.uInt64ToString = uInt64ToString;
exports.varint32write = varint32write;
exports.varint32read = varint32read;
/**
* 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");
}
/**
* 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);
}
// 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);
}
/**
* 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;
}
/**
* 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));
}
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);
}
}
/**
* 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;
}