@waku/core
Version:
TypeScript implementation of the Waku v2 protocol
1,829 lines (1,794 loc) โข 222 kB
JavaScript
/**
* Returns a `Uint8Array` of the requested size. Referenced memory will
* be initialized to 0.
*/
function alloc$1(size = 0) {
return new Uint8Array(size);
}
/**
* Where possible returns a Uint8Array of the requested size that references
* uninitialized memory. Only use if you are certain you will immediately
* overwrite every value in the returned `Uint8Array`.
*/
function allocUnsafe(size = 0) {
return new Uint8Array(size);
}
/* eslint-disable no-fallthrough */
const N1 = Math.pow(2, 7);
const N2 = Math.pow(2, 14);
const N3 = Math.pow(2, 21);
const N4 = Math.pow(2, 28);
const N5 = Math.pow(2, 35);
const N6 = Math.pow(2, 42);
const N7 = Math.pow(2, 49);
/** Most significant bit of a byte */
const MSB = 0x80;
/** Rest of the bits in a byte */
const REST = 0x7f;
function encodingLength(value) {
if (value < N1) {
return 1;
}
if (value < N2) {
return 2;
}
if (value < N3) {
return 3;
}
if (value < N4) {
return 4;
}
if (value < N5) {
return 5;
}
if (value < N6) {
return 6;
}
if (value < N7) {
return 7;
}
if (Number.MAX_SAFE_INTEGER != null && value > Number.MAX_SAFE_INTEGER) {
throw new RangeError('Could not encode varint');
}
return 8;
}
function encodeUint8Array(value, buf, offset = 0) {
switch (encodingLength(value)) {
case 8: {
buf[offset++] = (value & 0xFF) | MSB;
value /= 128;
}
case 7: {
buf[offset++] = (value & 0xFF) | MSB;
value /= 128;
}
case 6: {
buf[offset++] = (value & 0xFF) | MSB;
value /= 128;
}
case 5: {
buf[offset++] = (value & 0xFF) | MSB;
value /= 128;
}
case 4: {
buf[offset++] = (value & 0xFF) | MSB;
value >>>= 7;
}
case 3: {
buf[offset++] = (value & 0xFF) | MSB;
value >>>= 7;
}
case 2: {
buf[offset++] = (value & 0xFF) | MSB;
value >>>= 7;
}
case 1: {
buf[offset++] = (value & 0xFF);
value >>>= 7;
break;
}
default: throw new Error('unreachable');
}
return buf;
}
function encodeUint8ArrayList(value, buf, offset = 0) {
switch (encodingLength(value)) {
case 8: {
buf.set(offset++, (value & 0xFF) | MSB);
value /= 128;
}
case 7: {
buf.set(offset++, (value & 0xFF) | MSB);
value /= 128;
}
case 6: {
buf.set(offset++, (value & 0xFF) | MSB);
value /= 128;
}
case 5: {
buf.set(offset++, (value & 0xFF) | MSB);
value /= 128;
}
case 4: {
buf.set(offset++, (value & 0xFF) | MSB);
value >>>= 7;
}
case 3: {
buf.set(offset++, (value & 0xFF) | MSB);
value >>>= 7;
}
case 2: {
buf.set(offset++, (value & 0xFF) | MSB);
value >>>= 7;
}
case 1: {
buf.set(offset++, (value & 0xFF));
value >>>= 7;
break;
}
default: throw new Error('unreachable');
}
return buf;
}
function decodeUint8Array(buf, offset) {
let b = buf[offset];
let res = 0;
res += b & REST;
if (b < MSB) {
return res;
}
b = buf[offset + 1];
res += (b & REST) << 7;
if (b < MSB) {
return res;
}
b = buf[offset + 2];
res += (b & REST) << 14;
if (b < MSB) {
return res;
}
b = buf[offset + 3];
res += (b & REST) << 21;
if (b < MSB) {
return res;
}
b = buf[offset + 4];
res += (b & REST) * N4;
if (b < MSB) {
return res;
}
b = buf[offset + 5];
res += (b & REST) * N5;
if (b < MSB) {
return res;
}
b = buf[offset + 6];
res += (b & REST) * N6;
if (b < MSB) {
return res;
}
b = buf[offset + 7];
res += (b & REST) * N7;
if (b < MSB) {
return res;
}
throw new RangeError('Could not decode varint');
}
function decodeUint8ArrayList(buf, offset) {
let b = buf.get(offset);
let res = 0;
res += b & REST;
if (b < MSB) {
return res;
}
b = buf.get(offset + 1);
res += (b & REST) << 7;
if (b < MSB) {
return res;
}
b = buf.get(offset + 2);
res += (b & REST) << 14;
if (b < MSB) {
return res;
}
b = buf.get(offset + 3);
res += (b & REST) << 21;
if (b < MSB) {
return res;
}
b = buf.get(offset + 4);
res += (b & REST) * N4;
if (b < MSB) {
return res;
}
b = buf.get(offset + 5);
res += (b & REST) * N5;
if (b < MSB) {
return res;
}
b = buf.get(offset + 6);
res += (b & REST) * N6;
if (b < MSB) {
return res;
}
b = buf.get(offset + 7);
res += (b & REST) * N7;
if (b < MSB) {
return res;
}
throw new RangeError('Could not decode varint');
}
function encode$2(value, buf, offset = 0) {
if (buf == null) {
buf = allocUnsafe(encodingLength(value));
}
if (buf instanceof Uint8Array) {
return encodeUint8Array(value, buf, offset);
}
else {
return encodeUint8ArrayList(value, buf, offset);
}
}
function decode$2(buf, offset = 0) {
if (buf instanceof Uint8Array) {
return decodeUint8Array(buf, offset);
}
else {
return decodeUint8ArrayList(buf, offset);
}
}
const f32 = new Float32Array([-0]);
const f8b = new Uint8Array(f32.buffer);
/**
* Writes a 32 bit float to a buffer using little endian byte order
*/
function writeFloatLE(val, buf, pos) {
f32[0] = val;
buf[pos] = f8b[0];
buf[pos + 1] = f8b[1];
buf[pos + 2] = f8b[2];
buf[pos + 3] = f8b[3];
}
/**
* Reads a 32 bit float from a buffer using little endian byte order
*/
function readFloatLE(buf, pos) {
f8b[0] = buf[pos];
f8b[1] = buf[pos + 1];
f8b[2] = buf[pos + 2];
f8b[3] = buf[pos + 3];
return f32[0];
}
const f64 = new Float64Array([-0]);
const d8b = new Uint8Array(f64.buffer);
/**
* Writes a 64 bit double to a buffer using little endian byte order
*/
function writeDoubleLE(val, buf, pos) {
f64[0] = val;
buf[pos] = d8b[0];
buf[pos + 1] = d8b[1];
buf[pos + 2] = d8b[2];
buf[pos + 3] = d8b[3];
buf[pos + 4] = d8b[4];
buf[pos + 5] = d8b[5];
buf[pos + 6] = d8b[6];
buf[pos + 7] = d8b[7];
}
/**
* Reads a 64 bit double from a buffer using little endian byte order
*/
function readDoubleLE(buf, pos) {
d8b[0] = buf[pos];
d8b[1] = buf[pos + 1];
d8b[2] = buf[pos + 2];
d8b[3] = buf[pos + 3];
d8b[4] = buf[pos + 4];
d8b[5] = buf[pos + 5];
d8b[6] = buf[pos + 6];
d8b[7] = buf[pos + 7];
return f64[0];
}
// the largest BigInt we can safely downcast to a Number
const MAX_SAFE_NUMBER_INTEGER = BigInt(Number.MAX_SAFE_INTEGER);
const MIN_SAFE_NUMBER_INTEGER = BigInt(Number.MIN_SAFE_INTEGER);
/**
* Constructs new long bits.
*
* @classdesc Helper class for working with the low and high bits of a 64 bit value.
* @memberof util
* @function Object() { [native code] }
* @param {number} lo - Low 32 bits, unsigned
* @param {number} hi - High 32 bits, unsigned
*/
class LongBits {
lo;
hi;
constructor(lo, hi) {
// note that the casts below are theoretically unnecessary as of today, but older statically
// generated converter code might still call the ctor with signed 32bits. kept for compat.
/**
* Low bits
*/
this.lo = lo | 0;
/**
* High bits
*/
this.hi = hi | 0;
}
/**
* Converts this long bits to a possibly unsafe JavaScript number
*/
toNumber(unsigned = false) {
if (!unsigned && (this.hi >>> 31) > 0) {
const lo = ~this.lo + 1 >>> 0;
let hi = ~this.hi >>> 0;
if (lo === 0) {
hi = hi + 1 >>> 0;
}
return -(lo + hi * 4294967296);
}
return this.lo + this.hi * 4294967296;
}
/**
* Converts this long bits to a bigint
*/
toBigInt(unsigned = false) {
if (unsigned) {
return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n);
}
if ((this.hi >>> 31) !== 0) {
const lo = ~this.lo + 1 >>> 0;
let hi = ~this.hi >>> 0;
if (lo === 0) {
hi = hi + 1 >>> 0;
}
return -(BigInt(lo) + (BigInt(hi) << 32n));
}
return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n);
}
/**
* Converts this long bits to a string
*/
toString(unsigned = false) {
return this.toBigInt(unsigned).toString();
}
/**
* Zig-zag encodes this long bits
*/
zzEncode() {
const mask = this.hi >> 31;
this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;
this.lo = (this.lo << 1 ^ mask) >>> 0;
return this;
}
/**
* Zig-zag decodes this long bits
*/
zzDecode() {
const mask = -(this.lo & 1);
this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;
this.hi = (this.hi >>> 1 ^ mask) >>> 0;
return this;
}
/**
* Calculates the length of this longbits when encoded as a varint.
*/
length() {
const part0 = this.lo;
const part1 = (this.lo >>> 28 | this.hi << 4) >>> 0;
const part2 = this.hi >>> 24;
return part2 === 0
? part1 === 0
? part0 < 16384
? part0 < 128 ? 1 : 2
: part0 < 2097152 ? 3 : 4
: part1 < 16384
? part1 < 128 ? 5 : 6
: part1 < 2097152 ? 7 : 8
: part2 < 128 ? 9 : 10;
}
/**
* Constructs new long bits from the specified number
*/
static fromBigInt(value) {
if (value === 0n) {
return zero;
}
if (value < MAX_SAFE_NUMBER_INTEGER && value > MIN_SAFE_NUMBER_INTEGER) {
return this.fromNumber(Number(value));
}
const negative = value < 0n;
if (negative) {
value = -value;
}
let hi = value >> 32n;
let lo = value - (hi << 32n);
if (negative) {
hi = ~hi | 0n;
lo = ~lo | 0n;
if (++lo > TWO_32) {
lo = 0n;
if (++hi > TWO_32) {
hi = 0n;
}
}
}
return new LongBits(Number(lo), Number(hi));
}
/**
* Constructs new long bits from the specified number
*/
static fromNumber(value) {
if (value === 0) {
return zero;
}
const sign = value < 0;
if (sign) {
value = -value;
}
let lo = value >>> 0;
let hi = (value - lo) / 4294967296 >>> 0;
if (sign) {
hi = ~hi >>> 0;
lo = ~lo >>> 0;
if (++lo > 4294967295) {
lo = 0;
if (++hi > 4294967295) {
hi = 0;
}
}
}
return new LongBits(lo, hi);
}
/**
* Constructs new long bits from a number, long or string
*/
static from(value) {
if (typeof value === 'number') {
return LongBits.fromNumber(value);
}
if (typeof value === 'bigint') {
return LongBits.fromBigInt(value);
}
if (typeof value === 'string') {
return LongBits.fromBigInt(BigInt(value));
}
return value.low != null || value.high != null ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;
}
}
const zero = new LongBits(0, 0);
zero.toBigInt = function () { return 0n; };
zero.zzEncode = zero.zzDecode = function () { return this; };
zero.length = function () { return 1; };
const TWO_32 = 4294967296n;
/**
* Calculates the UTF8 byte length of a string
*/
function length(string) {
let len = 0;
let c = 0;
for (let i = 0; i < string.length; ++i) {
c = string.charCodeAt(i);
if (c < 128) {
len += 1;
}
else if (c < 2048) {
len += 2;
}
else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {
++i;
len += 4;
}
else {
len += 3;
}
}
return len;
}
/**
* Reads UTF8 bytes as a string
*/
function read(buffer, start, end) {
const len = end - start;
if (len < 1) {
return '';
}
let parts;
const chunk = [];
let i = 0; // char offset
let t; // temporary
while (start < end) {
t = buffer[start++];
if (t < 128) {
chunk[i++] = t;
}
else if (t > 191 && t < 224) {
chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;
}
else if (t > 239 && t < 365) {
t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;
chunk[i++] = 0xD800 + (t >> 10);
chunk[i++] = 0xDC00 + (t & 1023);
}
else {
chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;
}
if (i > 8191) {
(parts ?? (parts = [])).push(String.fromCharCode.apply(String, chunk));
i = 0;
}
}
if (parts != null) {
if (i > 0) {
parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));
}
return parts.join('');
}
return String.fromCharCode.apply(String, chunk.slice(0, i));
}
/**
* Writes a string as UTF8 bytes
*/
function write(string, buffer, offset) {
const start = offset;
let c1; // character 1
let c2; // character 2
for (let i = 0; i < string.length; ++i) {
c1 = string.charCodeAt(i);
if (c1 < 128) {
buffer[offset++] = c1;
}
else if (c1 < 2048) {
buffer[offset++] = c1 >> 6 | 192;
buffer[offset++] = c1 & 63 | 128;
}
else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {
c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);
++i;
buffer[offset++] = c1 >> 18 | 240;
buffer[offset++] = c1 >> 12 & 63 | 128;
buffer[offset++] = c1 >> 6 & 63 | 128;
buffer[offset++] = c1 & 63 | 128;
}
else {
buffer[offset++] = c1 >> 12 | 224;
buffer[offset++] = c1 >> 6 & 63 | 128;
buffer[offset++] = c1 & 63 | 128;
}
}
return offset - start;
}
/* istanbul ignore next */
function indexOutOfRange(reader, writeLength) {
return RangeError(`index out of range: ${reader.pos} + ${writeLength ?? 1} > ${reader.len}`);
}
function readFixed32End(buf, end) {
return (buf[end - 4] |
buf[end - 3] << 8 |
buf[end - 2] << 16 |
buf[end - 1] << 24) >>> 0;
}
/**
* Constructs a new reader instance using the specified buffer.
*/
class Uint8ArrayReader {
buf;
pos;
len;
_slice = Uint8Array.prototype.subarray;
constructor(buffer) {
/**
* Read buffer
*/
this.buf = buffer;
/**
* Read buffer position
*/
this.pos = 0;
/**
* Read buffer length
*/
this.len = buffer.length;
}
/**
* Reads a varint as an unsigned 32 bit value
*/
uint32() {
let value = 4294967295;
value = (this.buf[this.pos] & 127) >>> 0;
if (this.buf[this.pos++] < 128)
return value;
value = (value | (this.buf[this.pos] & 127) << 7) >>> 0;
if (this.buf[this.pos++] < 128)
return value;
value = (value | (this.buf[this.pos] & 127) << 14) >>> 0;
if (this.buf[this.pos++] < 128)
return value;
value = (value | (this.buf[this.pos] & 127) << 21) >>> 0;
if (this.buf[this.pos++] < 128)
return value;
value = (value | (this.buf[this.pos] & 15) << 28) >>> 0;
if (this.buf[this.pos++] < 128)
return value;
if ((this.pos += 5) > this.len) {
this.pos = this.len;
throw indexOutOfRange(this, 10);
}
return value;
}
/**
* Reads a varint as a signed 32 bit value
*/
int32() {
return this.uint32() | 0;
}
/**
* Reads a zig-zag encoded varint as a signed 32 bit value
*/
sint32() {
const value = this.uint32();
return value >>> 1 ^ -(value & 1) | 0;
}
/**
* Reads a varint as a boolean
*/
bool() {
return this.uint32() !== 0;
}
/**
* Reads fixed 32 bits as an unsigned 32 bit integer
*/
fixed32() {
if (this.pos + 4 > this.len) {
throw indexOutOfRange(this, 4);
}
const res = readFixed32End(this.buf, this.pos += 4);
return res;
}
/**
* Reads fixed 32 bits as a signed 32 bit integer
*/
sfixed32() {
if (this.pos + 4 > this.len) {
throw indexOutOfRange(this, 4);
}
const res = readFixed32End(this.buf, this.pos += 4) | 0;
return res;
}
/**
* Reads a float (32 bit) as a number
*/
float() {
if (this.pos + 4 > this.len) {
throw indexOutOfRange(this, 4);
}
const value = readFloatLE(this.buf, this.pos);
this.pos += 4;
return value;
}
/**
* Reads a double (64 bit float) as a number
*/
double() {
/* istanbul ignore if */
if (this.pos + 8 > this.len) {
throw indexOutOfRange(this, 4);
}
const value = readDoubleLE(this.buf, this.pos);
this.pos += 8;
return value;
}
/**
* Reads a sequence of bytes preceded by its length as a varint
*/
bytes() {
const length = this.uint32();
const start = this.pos;
const end = this.pos + length;
/* istanbul ignore if */
if (end > this.len) {
throw indexOutOfRange(this, length);
}
this.pos += length;
return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1
? new Uint8Array(0)
: this.buf.subarray(start, end);
}
/**
* Reads a string preceded by its byte length as a varint
*/
string() {
const bytes = this.bytes();
return read(bytes, 0, bytes.length);
}
/**
* Skips the specified number of bytes if specified, otherwise skips a varint
*/
skip(length) {
if (typeof length === 'number') {
/* istanbul ignore if */
if (this.pos + length > this.len) {
throw indexOutOfRange(this, length);
}
this.pos += length;
}
else {
do {
/* istanbul ignore if */
if (this.pos >= this.len) {
throw indexOutOfRange(this);
}
} while ((this.buf[this.pos++] & 128) !== 0);
}
return this;
}
/**
* Skips the next element of the specified wire type
*/
skipType(wireType) {
switch (wireType) {
case 0:
this.skip();
break;
case 1:
this.skip(8);
break;
case 2:
this.skip(this.uint32());
break;
case 3:
while ((wireType = this.uint32() & 7) !== 4) {
this.skipType(wireType);
}
break;
case 5:
this.skip(4);
break;
/* istanbul ignore next */
default:
throw Error(`invalid wire type ${wireType} at offset ${this.pos}`);
}
return this;
}
readLongVarint() {
// tends to deopt with local vars for octet etc.
const bits = new LongBits(0, 0);
let i = 0;
if (this.len - this.pos > 4) { // fast route (lo)
for (; i < 4; ++i) {
// 1st..4th
bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
if (this.buf[this.pos++] < 128) {
return bits;
}
}
// 5th
bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;
bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;
if (this.buf[this.pos++] < 128) {
return bits;
}
i = 0;
}
else {
for (; i < 3; ++i) {
/* istanbul ignore if */
if (this.pos >= this.len) {
throw indexOutOfRange(this);
}
// 1st..3th
bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
if (this.buf[this.pos++] < 128) {
return bits;
}
}
// 4th
bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;
return bits;
}
if (this.len - this.pos > 4) { // fast route (hi)
for (; i < 5; ++i) {
// 6th..10th
bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
if (this.buf[this.pos++] < 128) {
return bits;
}
}
}
else {
for (; i < 5; ++i) {
if (this.pos >= this.len) {
throw indexOutOfRange(this);
}
// 6th..10th
bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
if (this.buf[this.pos++] < 128) {
return bits;
}
}
}
throw Error('invalid varint encoding');
}
readFixed64() {
if (this.pos + 8 > this.len) {
throw indexOutOfRange(this, 8);
}
const lo = readFixed32End(this.buf, this.pos += 4);
const hi = readFixed32End(this.buf, this.pos += 4);
return new LongBits(lo, hi);
}
/**
* Reads a varint as a signed 64 bit value
*/
int64() {
return this.readLongVarint().toBigInt();
}
/**
* Reads a varint as a signed 64 bit value returned as a possibly unsafe
* JavaScript number
*/
int64Number() {
return this.readLongVarint().toNumber();
}
/**
* Reads a varint as a signed 64 bit value returned as a string
*/
int64String() {
return this.readLongVarint().toString();
}
/**
* Reads a varint as an unsigned 64 bit value
*/
uint64() {
return this.readLongVarint().toBigInt(true);
}
/**
* Reads a varint as an unsigned 64 bit value returned as a possibly unsafe
* JavaScript number
*/
uint64Number() {
const value = decodeUint8Array(this.buf, this.pos);
this.pos += encodingLength(value);
return value;
}
/**
* Reads a varint as an unsigned 64 bit value returned as a string
*/
uint64String() {
return this.readLongVarint().toString(true);
}
/**
* Reads a zig-zag encoded varint as a signed 64 bit value
*/
sint64() {
return this.readLongVarint().zzDecode().toBigInt();
}
/**
* Reads a zig-zag encoded varint as a signed 64 bit value returned as a
* possibly unsafe JavaScript number
*/
sint64Number() {
return this.readLongVarint().zzDecode().toNumber();
}
/**
* Reads a zig-zag encoded varint as a signed 64 bit value returned as a
* string
*/
sint64String() {
return this.readLongVarint().zzDecode().toString();
}
/**
* Reads fixed 64 bits
*/
fixed64() {
return this.readFixed64().toBigInt();
}
/**
* Reads fixed 64 bits returned as a possibly unsafe JavaScript number
*/
fixed64Number() {
return this.readFixed64().toNumber();
}
/**
* Reads fixed 64 bits returned as a string
*/
fixed64String() {
return this.readFixed64().toString();
}
/**
* Reads zig-zag encoded fixed 64 bits
*/
sfixed64() {
return this.readFixed64().toBigInt();
}
/**
* Reads zig-zag encoded fixed 64 bits returned as a possibly unsafe
* JavaScript number
*/
sfixed64Number() {
return this.readFixed64().toNumber();
}
/**
* Reads zig-zag encoded fixed 64 bits returned as a string
*/
sfixed64String() {
return this.readFixed64().toString();
}
}
function createReader(buf) {
return new Uint8ArrayReader(buf instanceof Uint8Array ? buf : buf.subarray());
}
function decodeMessage(buf, codec, opts) {
const reader = createReader(buf);
return codec.decode(reader, undefined, opts);
}
function equals(aa, bb) {
if (aa === bb) {
return true;
}
if (aa.byteLength !== bb.byteLength) {
return false;
}
for (let ii = 0; ii < aa.byteLength; ii++) {
if (aa[ii] !== bb[ii]) {
return false;
}
}
return true;
}
function coerce(o) {
if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') {
return o;
}
if (o instanceof ArrayBuffer) {
return new Uint8Array(o);
}
if (ArrayBuffer.isView(o)) {
return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
}
throw new Error('Unknown type, must be binary type');
}
function fromString$1(str) {
return new TextEncoder().encode(str);
}
function toString$1(b) {
return new TextDecoder().decode(b);
}
/* eslint-disable */
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
/**
* @param {string} ALPHABET
* @param {any} name
*/
function base(ALPHABET, name) {
if (ALPHABET.length >= 255) {
throw new TypeError('Alphabet too long');
}
var BASE_MAP = new Uint8Array(256);
for (var j = 0; j < BASE_MAP.length; j++) {
BASE_MAP[j] = 255;
}
for (var i = 0; i < ALPHABET.length; i++) {
var x = ALPHABET.charAt(i);
var xc = x.charCodeAt(0);
if (BASE_MAP[xc] !== 255) {
throw new TypeError(x + ' is ambiguous');
}
BASE_MAP[xc] = i;
}
var BASE = ALPHABET.length;
var LEADER = ALPHABET.charAt(0);
var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
/**
* @param {any[] | Iterable<number>} source
*/
function encode(source) {
// @ts-ignore
if (source instanceof Uint8Array)
;
else if (ArrayBuffer.isView(source)) {
source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
}
else if (Array.isArray(source)) {
source = Uint8Array.from(source);
}
if (!(source instanceof Uint8Array)) {
throw new TypeError('Expected Uint8Array');
}
if (source.length === 0) {
return '';
}
// Skip & count leading zeroes.
var zeroes = 0;
var length = 0;
var pbegin = 0;
var pend = source.length;
while (pbegin !== pend && source[pbegin] === 0) {
pbegin++;
zeroes++;
}
// Allocate enough space in big-endian base58 representation.
var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
var b58 = new Uint8Array(size);
// Process the bytes.
while (pbegin !== pend) {
var carry = source[pbegin];
// Apply "b58 = b58 * 256 + ch".
var i = 0;
for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
carry += (256 * b58[it1]) >>> 0;
b58[it1] = (carry % BASE) >>> 0;
carry = (carry / BASE) >>> 0;
}
if (carry !== 0) {
throw new Error('Non-zero carry');
}
length = i;
pbegin++;
}
// Skip leading zeroes in base58 result.
var it2 = size - length;
while (it2 !== size && b58[it2] === 0) {
it2++;
}
// Translate the result into a string.
var str = LEADER.repeat(zeroes);
for (; it2 < size; ++it2) {
str += ALPHABET.charAt(b58[it2]);
}
return str;
}
/**
* @param {string | string[]} source
*/
function decodeUnsafe(source) {
if (typeof source !== 'string') {
throw new TypeError('Expected String');
}
if (source.length === 0) {
return new Uint8Array();
}
var psz = 0;
// Skip leading spaces.
if (source[psz] === ' ') {
return;
}
// Skip and count leading '1's.
var zeroes = 0;
var length = 0;
while (source[psz] === LEADER) {
zeroes++;
psz++;
}
// Allocate enough space in big-endian base256 representation.
var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
var b256 = new Uint8Array(size);
// Process the characters.
while (source[psz]) {
// Decode character
var carry = BASE_MAP[source.charCodeAt(psz)];
// Invalid character
if (carry === 255) {
return;
}
var i = 0;
for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
carry += (BASE * b256[it3]) >>> 0;
b256[it3] = (carry % 256) >>> 0;
carry = (carry / 256) >>> 0;
}
if (carry !== 0) {
throw new Error('Non-zero carry');
}
length = i;
psz++;
}
// Skip trailing spaces.
if (source[psz] === ' ') {
return;
}
// Skip leading zeroes in b256.
var it4 = size - length;
while (it4 !== size && b256[it4] === 0) {
it4++;
}
var vch = new Uint8Array(zeroes + (size - it4));
var j = zeroes;
while (it4 !== size) {
vch[j++] = b256[it4++];
}
return vch;
}
/**
* @param {string | string[]} string
*/
function decode(string) {
var buffer = decodeUnsafe(string);
if (buffer) {
return buffer;
}
throw new Error(`Non-${name} character`);
}
return {
encode: encode,
decodeUnsafe: decodeUnsafe,
decode: decode
};
}
var src = base;
var _brrp__multiformats_scope_baseX = src;
/**
* Class represents both BaseEncoder and MultibaseEncoder meaning it
* can be used to encode to multibase or base encode without multibase
* prefix.
*/
let Encoder$1 = class Encoder {
name;
prefix;
baseEncode;
constructor(name, prefix, baseEncode) {
this.name = name;
this.prefix = prefix;
this.baseEncode = baseEncode;
}
encode(bytes) {
if (bytes instanceof Uint8Array) {
return `${this.prefix}${this.baseEncode(bytes)}`;
}
else {
throw Error('Unknown type, must be binary type');
}
}
};
/**
* Class represents both BaseDecoder and MultibaseDecoder so it could be used
* to decode multibases (with matching prefix) or just base decode strings
* with corresponding base encoding.
*/
let Decoder$1 = class Decoder {
name;
prefix;
baseDecode;
prefixCodePoint;
constructor(name, prefix, baseDecode) {
this.name = name;
this.prefix = prefix;
const prefixCodePoint = prefix.codePointAt(0);
/* c8 ignore next 3 */
if (prefixCodePoint === undefined) {
throw new Error('Invalid prefix character');
}
this.prefixCodePoint = prefixCodePoint;
this.baseDecode = baseDecode;
}
decode(text) {
if (typeof text === 'string') {
if (text.codePointAt(0) !== this.prefixCodePoint) {
throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
}
return this.baseDecode(text.slice(this.prefix.length));
}
else {
throw Error('Can only multibase decode strings');
}
}
or(decoder) {
return or(this, decoder);
}
};
class ComposedDecoder {
decoders;
constructor(decoders) {
this.decoders = decoders;
}
or(decoder) {
return or(this, decoder);
}
decode(input) {
const prefix = input[0];
const decoder = this.decoders[prefix];
if (decoder != null) {
return decoder.decode(input);
}
else {
throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
}
}
}
function or(left, right) {
return new ComposedDecoder({
...(left.decoders ?? { [left.prefix]: left }),
...(right.decoders ?? { [right.prefix]: right })
});
}
class Codec {
name;
prefix;
baseEncode;
baseDecode;
encoder;
decoder;
constructor(name, prefix, baseEncode, baseDecode) {
this.name = name;
this.prefix = prefix;
this.baseEncode = baseEncode;
this.baseDecode = baseDecode;
this.encoder = new Encoder$1(name, prefix, baseEncode);
this.decoder = new Decoder$1(name, prefix, baseDecode);
}
encode(input) {
return this.encoder.encode(input);
}
decode(input) {
return this.decoder.decode(input);
}
}
function from({ name, prefix, encode, decode }) {
return new Codec(name, prefix, encode, decode);
}
function baseX({ name, prefix, alphabet }) {
const { encode, decode } = _brrp__multiformats_scope_baseX(alphabet, name);
return from({
prefix,
name,
encode,
decode: (text) => coerce(decode(text))
});
}
function decode$1(string, alphabetIdx, bitsPerChar, name) {
// Count the padding bytes:
let end = string.length;
while (string[end - 1] === '=') {
--end;
}
// Allocate the output:
const out = new Uint8Array((end * bitsPerChar / 8) | 0);
// Parse the data:
let bits = 0; // Number of bits currently in the buffer
let buffer = 0; // Bits waiting to be written out, MSB first
let written = 0; // Next byte to write
for (let i = 0; i < end; ++i) {
// Read one character from the string:
const value = alphabetIdx[string[i]];
if (value === undefined) {
throw new SyntaxError(`Non-${name} character`);
}
// Append the bits to the buffer:
buffer = (buffer << bitsPerChar) | value;
bits += bitsPerChar;
// Write out some bits if the buffer has a byte's worth:
if (bits >= 8) {
bits -= 8;
out[written++] = 0xff & (buffer >> bits);
}
}
// Verify that we have received just enough bits:
if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {
throw new SyntaxError('Unexpected end of data');
}
return out;
}
function encode$1(data, alphabet, bitsPerChar) {
const pad = alphabet[alphabet.length - 1] === '=';
const mask = (1 << bitsPerChar) - 1;
let out = '';
let bits = 0; // Number of bits currently in the buffer
let buffer = 0; // Bits waiting to be written out, MSB first
for (let i = 0; i < data.length; ++i) {
// Slurp data into the buffer:
buffer = (buffer << 8) | data[i];
bits += 8;
// Write out as much as we can:
while (bits > bitsPerChar) {
bits -= bitsPerChar;
out += alphabet[mask & (buffer >> bits)];
}
}
// Partial character:
if (bits !== 0) {
out += alphabet[mask & (buffer << (bitsPerChar - bits))];
}
// Add padding characters until we hit a byte boundary:
if (pad) {
while (((out.length * bitsPerChar) & 7) !== 0) {
out += '=';
}
}
return out;
}
function createAlphabetIdx(alphabet) {
// Build the character lookup table:
const alphabetIdx = {};
for (let i = 0; i < alphabet.length; ++i) {
alphabetIdx[alphabet[i]] = i;
}
return alphabetIdx;
}
/**
* RFC4648 Factory
*/
function rfc4648({ name, prefix, bitsPerChar, alphabet }) {
const alphabetIdx = createAlphabetIdx(alphabet);
return from({
prefix,
name,
encode(input) {
return encode$1(input, alphabet, bitsPerChar);
},
decode(input) {
return decode$1(input, alphabetIdx, bitsPerChar, name);
}
});
}
const base10 = baseX({
prefix: '9',
name: 'base10',
alphabet: '0123456789'
});
var base10$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
base10: base10
});
const base16 = rfc4648({
prefix: 'f',
name: 'base16',
alphabet: '0123456789abcdef',
bitsPerChar: 4
});
const base16upper = rfc4648({
prefix: 'F',
name: 'base16upper',
alphabet: '0123456789ABCDEF',
bitsPerChar: 4
});
var base16$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
base16: base16,
base16upper: base16upper
});
const base2 = rfc4648({
prefix: '0',
name: 'base2',
alphabet: '01',
bitsPerChar: 1
});
var base2$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
base2: base2
});
const alphabet = Array.from('๐๐ชโ๐ฐ๐๐๐๐๐๐๐๐๐๐๐๐๐โ๐ป๐ฅ๐พ๐ฟ๐โค๐๐คฃ๐๐๐๐ญ๐๐๐
๐๐๐ฅ๐ฅฐ๐๐๐๐ข๐ค๐๐๐ช๐โบ๐๐ค๐๐๐๐๐น๐คฆ๐๐โโจ๐คท๐ฑ๐๐ธ๐๐๐๐๐๐๐๐๐คฉ๐๐๐ค๐๐ฏ๐๐๐ถ๐๐คญโฃ๐๐๐๐ช๐๐ฅ๐๐๐ฉ๐ก๐คช๐๐ฅณ๐ฅ๐คค๐๐๐ณโ๐๐๐ด๐๐ฌ๐๐๐ท๐ป๐โญโ
๐ฅบ๐๐๐ค๐ฆโ๐ฃ๐๐โน๐๐๐ โ๐๐บ๐๐ป๐๐๐๐๐น๐ฃ๐ซ๐๐๐ต๐ค๐๐ด๐ค๐ผ๐ซโฝ๐คโ๐๐คซ๐๐ฎ๐๐ป๐๐ถ๐๐ฒ๐ฟ๐งก๐โก๐๐โโ๐๐ฐ๐คจ๐ถ๐ค๐ถ๐ฐ๐๐ข๐ค๐๐จ๐จ๐คฌโ๐๐บ๐ค๐๐๐ฑ๐๐ถ๐ฅดโถโกโ๐๐ธโฌ๐จ๐๐ฆ๐ท๐บโ ๐
๐๐ต๐๐คฒ๐ค ๐คง๐๐ต๐
๐ง๐พ๐๐๐ค๐๐คฏ๐ทโ๐ง๐ฏ๐๐๐ค๐๐โ๐ด๐ฃ๐ธ๐๐๐ฅ๐คข๐
๐ก๐ฉ๐๐ธ๐ป๐ค๐คฎ๐ผ๐ฅต๐ฉ๐๐๐ผ๐๐ฃ๐ฅ');
const alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));
const alphabetCharsToBytes = (alphabet.reduce((p, c, i) => {
const codePoint = c.codePointAt(0);
if (codePoint == null) {
throw new Error(`Invalid character: ${c}`);
}
p[codePoint] = i;
return p;
}, ([])));
function encode(data) {
return data.reduce((p, c) => {
p += alphabetBytesToChars[c];
return p;
}, '');
}
function decode(str) {
const byts = [];
for (const char of str) {
const codePoint = char.codePointAt(0);
if (codePoint == null) {
throw new Error(`Invalid character: ${char}`);
}
const byt = alphabetCharsToBytes[codePoint];
if (byt == null) {
throw new Error(`Non-base256emoji character: ${char}`);
}
byts.push(byt);
}
return new Uint8Array(byts);
}
const base256emoji = from({
prefix: '๐',
name: 'base256emoji',
encode,
decode
});
var base256emoji$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
base256emoji: base256emoji
});
const base32 = rfc4648({
prefix: 'b',
name: 'base32',
alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
bitsPerChar: 5
});
const base32upper = rfc4648({
prefix: 'B',
name: 'base32upper',
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
bitsPerChar: 5
});
const base32pad = rfc4648({
prefix: 'c',
name: 'base32pad',
alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
bitsPerChar: 5
});
const base32padupper = rfc4648({
prefix: 'C',
name: 'base32padupper',
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
bitsPerChar: 5
});
const base32hex = rfc4648({
prefix: 'v',
name: 'base32hex',
alphabet: '0123456789abcdefghijklmnopqrstuv',
bitsPerChar: 5
});
const base32hexupper = rfc4648({
prefix: 'V',
name: 'base32hexupper',
alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
bitsPerChar: 5
});
const base32hexpad = rfc4648({
prefix: 't',
name: 'base32hexpad',
alphabet: '0123456789abcdefghijklmnopqrstuv=',
bitsPerChar: 5
});
const base32hexpadupper = rfc4648({
prefix: 'T',
name: 'base32hexpadupper',
alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
bitsPerChar: 5
});
const base32z = rfc4648({
prefix: 'h',
name: 'base32z',
alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
bitsPerChar: 5
});
var base32$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
base32: base32,
base32hex: base32hex,
base32hexpad: base32hexpad,
base32hexpadupper: base32hexpadupper,
base32hexupper: base32hexupper,
base32pad: base32pad,
base32padupper: base32padupper,
base32upper: base32upper,
base32z: base32z
});
const base36 = baseX({
prefix: 'k',
name: 'base36',
alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'
});
const base36upper = baseX({
prefix: 'K',
name: 'base36upper',
alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
});
var base36$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
base36: base36,
base36upper: base36upper
});
const base58btc = baseX({
name: 'base58btc',
prefix: 'z',
alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
});
const base58flickr = baseX({
name: 'base58flickr',
prefix: 'Z',
alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
});
var base58 = /*#__PURE__*/Object.freeze({
__proto__: null,
base58btc: base58btc,
base58flickr: base58flickr
});
const base64 = rfc4648({
prefix: 'm',
name: 'base64',
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
bitsPerChar: 6
});
const base64pad = rfc4648({
prefix: 'M',
name: 'base64pad',
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
bitsPerChar: 6
});
const base64url = rfc4648({
prefix: 'u',
name: 'base64url',
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
bitsPerChar: 6
});
const base64urlpad = rfc4648({
prefix: 'U',
name: 'base64urlpad',
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',
bitsPerChar: 6
});
var base64$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
base64: base64,
base64pad: base64pad,
base64url: base64url,
base64urlpad: base64urlpad
});
const base8 = rfc4648({
prefix: '7',
name: 'base8',
alphabet: '01234567',
bitsPerChar: 3
});
var base8$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
base8: base8
});
const identity = from({
prefix: '\x00',
name: 'identity',
encode: (buf) => toString$1(buf),
decode: (str) => fromString$1(str)
});
var identityBase = /*#__PURE__*/Object.freeze({
__proto__: null,
identity: identity
});
new TextEncoder();
new TextDecoder();
const bases = { ...identityBase, ...base2$1, ...base8$1, ...base10$1, ...base16$1, ...base32$1, ...base36$1, ...base58, ...base64$1, ...base256emoji$1 };
function createCodec$1(name, prefix, encode, decode) {
return {
name,
prefix,
encoder: {
name,
prefix,
encode
},
decoder: {
decode
}
};
}
const string = createCodec$1('utf8', 'u', (buf) => {
const decoder = new TextDecoder('utf8');
return 'u' + decoder.decode(buf);
}, (str) => {
const encoder = new TextEncoder();
return encoder.encode(str.substring(1));
});
const ascii = createCodec$1('ascii', 'a', (buf) => {
let string = 'a';
for (let i = 0; i < buf.length; i++) {
string += String.fromCharCode(buf[i]);
}
return string;
}, (str) => {
str = str.substring(1);
const buf = allocUnsafe(str.length);
for (let i = 0; i < str.length; i++) {
buf[i] = str.charCodeAt(i);
}
return buf;
});
const BASES = {
utf8: string,
'utf-8': string,
hex: bases.base16,
latin1: ascii,
ascii,
binary: ascii,
...bases
};
/**
* Create a `Uint8Array` from the passed string
*
* Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.
*
* Also `ascii` which is similar to node's 'binary' encoding.
*/
function fromString(string, encoding = 'utf8') {
const base = BASES[encoding];
if (base == null) {
throw new Error(`Unsupported encoding "${encoding}"`);
}
// add multibase prefix
return base.decoder.decode(`${base.prefix}${string}`); // eslint-disable-line @typescript-eslint/restrict-template-expressions
}
/**
* A general purpose buffer pool
*/
function pool(size) {
const SIZE = 8192;
const MAX = SIZE >>> 1;
let slab;
let offset = SIZE;
return function poolAlloc(size) {
if (size < 1 || size > MAX) {
return allocUnsafe(size);
}
if (offset + size > SIZE) {
slab = allocUnsafe(SIZE);
offset = 0;
}
const buf = slab.subarray(offset, offset += size);
if ((offset & 7) !== 0) {
// align to 32 bit
offset = (offset | 7) + 1;
}
return buf;
};
}
/**
* Constructs a new writer operation instance.
*
* @classdesc Scheduled writer operation
*/
class Op {
/**
* Function to call
*/
fn;
/**
* Value byte length
*/
len;
/**
* Next operation
*/
next;
/**
* Value to write
*/
val;
constructor(fn, len, val) {
this.fn = fn;
this.len = len;
this.next = undefined;
this.val = val; // type varies
}
}
/* istanbul ignore next */
function noop() { } // eslint-disable-line no-empty-function
/**
* Constructs a new writer state instance
*/
class State {
/**
* Current head
*/
head;
/**
* Current tail
*/
tail;
/**
* Current buffer length
*/
len;
/**
* Next state
*/
next;
constructor(writer) {
this.head = writer.head;
this.tail = writer.tail;
this.len = writer.len;
this.next = writer.states;
}
}
const bufferPool = pool();
/**
* Allocates a buffer of the specified size
*/
function alloc(size) {
if (globalThis.Buffer != null) {
return allocUnsafe(size);
}
return bufferPool(size);
}
/**
* When a value is written, the writer calculates its byte length and puts it into a linked
* list of operations to perform when finish() is called. This both allows us to allocate
* buffers of the exact required size and reduces the amount of work we have to do compared
* to first calculating over objects and then encoding over objects. In our case, the encoding
* part is just a linked list walk calling operations with already prepared values.
*/
class Uint8ArrayWriter {
/**
* Current length
*/
len;
/**
* Operations head
*/
head;
/**
* Operations tail
*/
tail;
/**
* Linked forked states
*/
states;
constructor() {
this.len = 0;
this.head = new Op(noop, 0, 0);
this.tail = this.head;
this.states = null;
}
/**
* Pushes a new operation to the queue
*/
_push(fn, len, val) {
this.tail = this.tail.next = new Op(fn, len, val);
this.len += len;
return this;
}
/**
* Writes an unsigned 32 bit value as a varint
*/
uint32(value) {
// here, the call to this.push has been inlined and a varint specific Op subclass is used.
// uint32 is by far the most frequently used operation and benefits significantly from this.
this.len += (this.tail = this.tail.next = new VarintOp((value = value >>> 0) <
128
? 1
: value < 16384
? 2
: value < 2097152
? 3
: value < 268435456
? 4
: 5, value)).len;
return this;
}
/**
* Writes a signed 32 bit value as a varint`
*/
int32(value) {
return value < 0
? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec
: this.uint32(value);
}
/**
* Writes a 32 bit value as a varint, zig-zag encoded
*/
sint32(value) {
return this.uint32((value << 1 ^ value >> 31) >>> 0);
}
/**
* Writes an unsigned 64 bit value as a varint
*/
uint64(value) {
const bits = LongBits.fromBigInt(value);
return this._push(writeVarint64, bits.length(), bits);
}
/**
* Writes an unsigned 64 bit value as a varint
*/
uint64Number(value) {
return this._push(encodeUint8Array, encodingLength(value), value);
}
/**
* Writes an unsigned 64 bit value as a varint
*/
uint64String(value) {
retu