UNPKG

livekit-client

Version:

JavaScript/TypeScript client SDK for LiveKit

1,508 lines 1.13 MB
function _mergeNamespaces(n, m){m.forEach(function(e){e&&typeof e!=='string'&&!Array.isArray(e)&&Object.keys(e).forEach(function(k){if(k!=='default'&&!(k in n)){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})});return Object.freeze(n);}var e = Object.defineProperty; var h = (i, s, t) => s in i ? e(i, s, { enumerable: true, configurable: true, writable: true, value: t }) : i[s] = t; var o = (i, s, t) => h(i, typeof s != "symbol" ? s + "" : s, t); class _ { constructor() { o(this, "_locking"); o(this, "_locks"); this._locking = Promise.resolve(), this._locks = 0; } isLocked() { return this._locks > 0; } lock() { this._locks += 1; let s; const t = new Promise(l => s = () => { this._locks -= 1, l(); }), c = this._locking.then(() => s); return this._locking = this._locking.then(() => t), c; } }// 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. /** * 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); } } const FLOAT32_MAX = 3.4028234663852886e38, FLOAT32_MIN = -34028234663852886e22, UINT32_MAX = 0xffffffff, INT32_MAX = 0x7fffffff, INT32_MIN = -2147483648; /** * 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 } /** * 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 } /** * 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 }// 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. 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]; assert(t, "missing enum type on enum object"); return t; // eslint-disable-line @typescript-eslint/no-unsafe-return } /** * 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] }))); } /** * 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]; } }; } /** * 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); return enumObject; } function normalizeEnumValue(value) { if ("localName" in value) { return value; } return Object.assign(Object.assign({}, value), { localName: value.name }); }// 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. /** * 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 ".concat(this.getType().typeName, " from JSON: ").concat(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; } }// 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. /** * 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()); 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; }// 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. /* 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"); } /** * 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; }// 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. function makeInt64Support() { const dv = new DataView(new ArrayBuffer(8)); // note that Safari 14 implements BigInt, but not the DataView methods const ok = typeof BigInt === "function" && typeof dv.getBigInt64 === "function" && typeof dv.getBigUint64 === "function" && typeof dv.setBigInt64 === "function" && typeof dv.setBigUint64 === "function" && (typeof process != "object" || typeof process.env != "object" || process.env.BUF_BIGINT_DISABLE !== "1"); if (ok) { const MIN = BigInt("-9223372036854775808"), MAX = BigInt("9223372036854775807"), UMIN = BigInt("0"), UMAX = BigInt("18446744073709551615"); return { zero: BigInt(0), supported: true, parse(value) { const bi = typeof value == "bigint" ? value : BigInt(value); if (bi > MAX || bi < MIN) { throw new Error("int64 invalid: ".concat(value)); } return bi; }, uParse(value) { const bi = typeof value == "bigint" ? value : BigInt(value); if (bi > UMAX || bi < UMIN) { throw new Error("uint64 invalid: ".concat(value)); } return bi; }, enc(value) { dv.setBigInt64(0, this.parse(value), true); return { lo: dv.getInt32(0, true), hi: dv.getInt32(4, true) }; }, uEnc(value) { dv.setBigInt64(0, this.uParse(value), true); return { lo: dv.getInt32(0, true), hi: dv.getInt32(4, true) }; }, dec(lo, hi) { dv.setInt32(0, lo, true); dv.setInt32(4, hi, true); return dv.getBigInt64(0, true); }, uDec(lo, hi) { dv.setInt32(0, lo, true); dv.setInt32(4, hi, true); return dv.getBigUint64(0, true); } }; } const assertInt64String = value => assert(/^-?[0-9]+$/.test(value), "int64 invalid: ".concat(value)); const assertUInt64String = value => assert(/^[0-9]+$/.test(value), "uint64 invalid: ".concat(value)); return { zero: "0", supported: false, parse(value) { if (typeof value != "string") { value = value.toString(); } assertInt64String(value); return value; }, uParse(value) { if (typeof value != "string") { value = value.toString(); } assertUInt64String(value); return value; }, enc(value) { if (typeof value != "string") { value = value.toString(); } assertInt64String(value); return int64FromString(value); }, uEnc(value) { if (typeof value != "string") { value = value.toString(); } assertUInt64String(value); return int64FromString(value); }, dec(lo, hi) { return int64ToString(lo, hi); }, uDec(lo, hi) { return uInt64ToString(lo, hi); } }; } const protoInt64 = makeInt64Support();// 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. /** * Scalar value types. This is a subset of field types declared by protobuf * enum google.protobuf.FieldDescriptorProto.Type The types GROUP and MESSAGE * are omitted, but the numerical values are identical. */ var ScalarType; (function (ScalarType) { // 0 is reserved for errors. // Order is weird for historical reasons. ScalarType[ScalarType["DOUBLE"] = 1] = "DOUBLE"; ScalarType[ScalarType["FLOAT"] = 2] = "FLOAT"; // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if // negative values are likely. ScalarType[ScalarType["INT64"] = 3] = "INT64"; ScalarType[ScalarType["UINT64"] = 4] = "UINT64"; // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if // negative values are likely. ScalarType[ScalarType["INT32"] = 5] = "INT32"; ScalarType[ScalarType["FIXED64"] = 6] = "FIXED64"; ScalarType[ScalarType["FIXED32"] = 7] = "FIXED32"; ScalarType[ScalarType["BOOL"] = 8] = "BOOL"; ScalarType[ScalarType["STRING"] = 9] = "STRING"; // Tag-delimited aggregate. // Group type is deprecated and not supported in proto3. However, Proto3 // implementations should still be able to parse the group wire format and // treat group fields as unknown fields. // TYPE_GROUP = 10, // TYPE_MESSAGE = 11, // Length-delimited aggregate. // New in version 2. ScalarType[ScalarType["BYTES"] = 12] = "BYTES"; ScalarType[ScalarType["UINT32"] = 13] = "UINT32"; // TYPE_ENUM = 14, ScalarType[ScalarType["SFIXED32"] = 15] = "SFIXED32"; ScalarType[ScalarType["SFIXED64"] = 16] = "SFIXED64"; ScalarType[ScalarType["SINT32"] = 17] = "SINT32"; ScalarType[ScalarType["SINT64"] = 18] = "SINT64"; })(ScalarType || (ScalarType = {})); /** * JavaScript representation of fields with 64 bit integral types (int64, uint64, * sint64, fixed64, sfixed64). * * This is a subset of google.protobuf.FieldOptions.JSType, which defines JS_NORMAL, * JS_STRING, and JS_NUMBER. Protobuf-ES uses BigInt by default, but will use * String if `[jstype = JS_STRING]` is specified. * * ```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 * ``` */ var LongType; (function (LongType) { /** * Use JavaScript BigInt. */ LongType[LongType["BIGINT"] = 0] = "BIGINT"; /** * Use JavaScript String. * * Field option `[jstype = JS_STRING]`. */ LongType[LongType["STRING"] = 1] = "STRING"; })(LongType || (LongType = {}));// 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. /** * 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 == 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 ScalarType.UINT64: case ScalarType.FIXED64: case ScalarType.INT64: case ScalarType.SFIXED64: case 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; } /** * Returns the zero value for the given scalar type. */ function scalarZeroValue(type, longType) { switch (type) { case ScalarType.BOOL: return false; case ScalarType.UINT64: case ScalarType.FIXED64: case ScalarType.INT64: case ScalarType.SFIXED64: case ScalarType.SINT64: // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison -- acceptable since it's covered by tests return longType == 0 ? protoInt64.zero : "0"; case ScalarType.DOUBLE: case ScalarType.FLOAT: return 0.0; case ScalarType.BYTES: return new Uint8Array(0); case 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; } } /** * 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 ScalarType.BOOL: return value === false; case ScalarType.STRING: return value === ""; case ScalarType.BYTES: return value instanceof Uint8Array && !value.byteLength; default: return value == 0; // Loose comparison matches 0n, 0 and "0" } }// 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. /* 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 || (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) { 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); 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) { 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; 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 = 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 = 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 = protoInt64.enc(value); 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 = protoInt64.enc(value), // zigzag encode sign = tc.hi >> 31, lo = tc.lo << 1 ^ sign, hi = (tc.hi << 1 | tc.lo >>> 31) ^ sign; varint64write(lo, hi, this.buf); return this; } /** * Write a `uint64` value, an unsigned 64-bit varint. */ uint64(value) { let tc = protoInt64.uEnc(value); varint64write(tc.lo, tc.hi, this.buf); return this; } } class BinaryReader { constructor(buf, textDecoder) { this.varint64 = varint64read; // dirty cast for `this` /** * Read a `uint32` field, an unsigned 32 bit varint. */ this.uint32 = 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 protoInt64.dec(...this.varint64()); } /** * Read a `uint64` field, an unsigned 64-bit varint. */ uint64() { return 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 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 protoInt64.uDec(this.sfixed32(), this.sfixed32()); } /** * Read a `fixed64` field, a signed, fixed-length 64-bit integer. */ sfixed64() { return 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()); } }// 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. /** * 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 = "[".concat(typeName, "]"); fi = runtime.util.newFieldList([i]).list()[0]; } return fi; }, runtime }; } /** * 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]]; } 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 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); }// 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. /* eslint-disable @typescript-eslint/ban-ts-comment, @typescript-eslint/no-unnecessary-condition, prefer-const */ // lookup table from base64 character to byte let encTable = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""); // lookup table from base64 character *code* to byte because lookup by number is fast let decTable = []; for (let i = 0; i < encTable.length; i++) decTable[encTable[i].charCodeAt(0)] = i; // support base64url variants decTable["-".charCodeAt(0)] = encTable.indexOf("+"); decTable["_".charCodeAt(0)] = encTable.indexOf("/"); const protoBase64 = { /** * 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 */ dec(base64Str) { // 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 = decTable[base64Str.charCodeAt(i)]; if (b === undefined) { switch (base64Str[i]) { // @ts-ignore TS7029: Fallthrough case in switch case "=": groupP