Skip to content

Instantly share code, notes, and snippets.

@serefyarar
Created May 23, 2023 21:47
Show Gist options
  • Save serefyarar/4c93ae20b84b4393f3a5d5ae8c204cac to your computer and use it in GitHub Desktop.
Save serefyarar/4c93ae20b84b4393f3a5d5ae8c204cac to your computer and use it in GitHub Desktop.
/**
*
* NAME: main
*
*/
"use strict";
(() => {
var __defProp = Object.defineProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __esm = (fn, res) => function __init() {
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
for (var name2 in all)
__defProp(target, name2, { get: all[name2], enumerable: true });
};
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// ../../node_modules/cborg/esm/lib/is.js
function is(value) {
if (value === null) {
return "null";
}
if (value === void 0) {
return "undefined";
}
if (value === true || value === false) {
return "boolean";
}
const typeOf = typeof value;
if (typeofs.includes(typeOf)) {
return typeOf;
}
if (typeOf === "function") {
return "Function";
}
if (Array.isArray(value)) {
return "Array";
}
if (isBuffer(value)) {
return "Buffer";
}
const objectType = getObjectType(value);
if (objectType) {
return objectType;
}
return "Object";
}
function isBuffer(value) {
return value && value.constructor && value.constructor.isBuffer && value.constructor.isBuffer.call(null, value);
}
function getObjectType(value) {
const objectTypeName = Object.prototype.toString.call(value).slice(8, -1);
if (objectTypeNames.includes(objectTypeName)) {
return objectTypeName;
}
return void 0;
}
var typeofs, objectTypeNames;
var init_is = __esm({
"../../node_modules/cborg/esm/lib/is.js"() {
typeofs = [
"string",
"number",
"bigint",
"symbol"
];
objectTypeNames = [
"Function",
"Generator",
"AsyncGenerator",
"GeneratorFunction",
"AsyncGeneratorFunction",
"AsyncFunction",
"Observable",
"Array",
"Buffer",
"Object",
"RegExp",
"Date",
"Error",
"Map",
"Set",
"WeakMap",
"WeakSet",
"ArrayBuffer",
"SharedArrayBuffer",
"DataView",
"Promise",
"URL",
"HTMLElement",
"Int8Array",
"Uint8Array",
"Uint8ClampedArray",
"Int16Array",
"Uint16Array",
"Int32Array",
"Uint32Array",
"Float32Array",
"Float64Array",
"BigInt64Array",
"BigUint64Array"
];
}
});
// ../../node_modules/cborg/esm/lib/token.js
var Type, Token;
var init_token = __esm({
"../../node_modules/cborg/esm/lib/token.js"() {
Type = class {
constructor(major, name2, terminal) {
this.major = major;
this.majorEncoded = major << 5;
this.name = name2;
this.terminal = terminal;
}
toString() {
return `Type[${this.major}].${this.name}`;
}
compare(typ) {
return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0;
}
};
Type.uint = new Type(0, "uint", true);
Type.negint = new Type(1, "negint", true);
Type.bytes = new Type(2, "bytes", true);
Type.string = new Type(3, "string", true);
Type.array = new Type(4, "array", false);
Type.map = new Type(5, "map", false);
Type.tag = new Type(6, "tag", false);
Type.float = new Type(7, "float", true);
Type.false = new Type(7, "false", true);
Type.true = new Type(7, "true", true);
Type.null = new Type(7, "null", true);
Type.undefined = new Type(7, "undefined", true);
Type.break = new Type(7, "break", true);
Token = class {
constructor(type, value, encodedLength) {
this.type = type;
this.value = value;
this.encodedLength = encodedLength;
this.encodedBytes = void 0;
this.byteValue = void 0;
}
toString() {
return `Token[${this.type}].${this.value}`;
}
};
}
});
// ../../node_modules/cborg/esm/lib/byte-utils.js
function isBuffer2(buf2) {
return useBuffer && globalThis.Buffer.isBuffer(buf2);
}
function asU8A(buf2) {
if (!(buf2 instanceof Uint8Array)) {
return Uint8Array.from(buf2);
}
return isBuffer2(buf2) ? new Uint8Array(buf2.buffer, buf2.byteOffset, buf2.byteLength) : buf2;
}
function compare(b1, b2) {
if (isBuffer2(b1) && isBuffer2(b2)) {
return b1.compare(b2);
}
for (let i = 0; i < b1.length; i++) {
if (b1[i] === b2[i]) {
continue;
}
return b1[i] < b2[i] ? -1 : 1;
}
return 0;
}
function utf8ToBytes(string, units = Infinity) {
let codePoint;
const length2 = string.length;
let leadSurrogate = null;
const bytes = [];
for (let i = 0; i < length2; ++i) {
codePoint = string.charCodeAt(i);
if (codePoint > 55295 && codePoint < 57344) {
if (!leadSurrogate) {
if (codePoint > 56319) {
if ((units -= 3) > -1)
bytes.push(239, 191, 189);
continue;
} else if (i + 1 === length2) {
if ((units -= 3) > -1)
bytes.push(239, 191, 189);
continue;
}
leadSurrogate = codePoint;
continue;
}
if (codePoint < 56320) {
if ((units -= 3) > -1)
bytes.push(239, 191, 189);
leadSurrogate = codePoint;
continue;
}
codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536;
} else if (leadSurrogate) {
if ((units -= 3) > -1)
bytes.push(239, 191, 189);
}
leadSurrogate = null;
if (codePoint < 128) {
if ((units -= 1) < 0)
break;
bytes.push(codePoint);
} else if (codePoint < 2048) {
if ((units -= 2) < 0)
break;
bytes.push(codePoint >> 6 | 192, codePoint & 63 | 128);
} else if (codePoint < 65536) {
if ((units -= 3) < 0)
break;
bytes.push(codePoint >> 12 | 224, codePoint >> 6 & 63 | 128, codePoint & 63 | 128);
} else if (codePoint < 1114112) {
if ((units -= 4) < 0)
break;
bytes.push(codePoint >> 18 | 240, codePoint >> 12 & 63 | 128, codePoint >> 6 & 63 | 128, codePoint & 63 | 128);
} else {
throw new Error("Invalid code point");
}
}
return bytes;
}
function utf8Slice(buf2, offset, end) {
const res = [];
while (offset < end) {
const firstByte = buf2[offset];
let codePoint = null;
let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;
if (offset + bytesPerSequence <= end) {
let secondByte, thirdByte, fourthByte, tempCodePoint;
switch (bytesPerSequence) {
case 1:
if (firstByte < 128) {
codePoint = firstByte;
}
break;
case 2:
secondByte = buf2[offset + 1];
if ((secondByte & 192) === 128) {
tempCodePoint = (firstByte & 31) << 6 | secondByte & 63;
if (tempCodePoint > 127) {
codePoint = tempCodePoint;
}
}
break;
case 3:
secondByte = buf2[offset + 1];
thirdByte = buf2[offset + 2];
if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) {
tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63;
if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) {
codePoint = tempCodePoint;
}
}
break;
case 4:
secondByte = buf2[offset + 1];
thirdByte = buf2[offset + 2];
fourthByte = buf2[offset + 3];
if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) {
tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63;
if (tempCodePoint > 65535 && tempCodePoint < 1114112) {
codePoint = tempCodePoint;
}
}
}
}
if (codePoint === null) {
codePoint = 65533;
bytesPerSequence = 1;
} else if (codePoint > 65535) {
codePoint -= 65536;
res.push(codePoint >>> 10 & 1023 | 55296);
codePoint = 56320 | codePoint & 1023;
}
res.push(codePoint);
offset += bytesPerSequence;
}
return decodeCodePointsArray(res);
}
function decodeCodePointsArray(codePoints) {
const len = codePoints.length;
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints);
}
let res = "";
let i = 0;
while (i < len) {
res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH));
}
return res;
}
var useBuffer, textDecoder, textEncoder, toString2, fromString, fromArray, slice, concat, alloc, MAX_ARGUMENTS_LENGTH;
var init_byte_utils = __esm({
"../../node_modules/cborg/esm/lib/byte-utils.js"() {
useBuffer = globalThis.process && !globalThis.process.browser && globalThis.Buffer && typeof globalThis.Buffer.isBuffer === "function";
textDecoder = new TextDecoder();
textEncoder = new TextEncoder();
toString2 = useBuffer ? (bytes, start, end) => {
return end - start > 64 ? globalThis.Buffer.from(bytes.subarray(start, end)).toString("utf8") : utf8Slice(bytes, start, end);
} : (bytes, start, end) => {
return end - start > 64 ? textDecoder.decode(bytes.subarray(start, end)) : utf8Slice(bytes, start, end);
};
fromString = useBuffer ? (string) => {
return string.length > 64 ? globalThis.Buffer.from(string) : utf8ToBytes(string);
} : (string) => {
return string.length > 64 ? textEncoder.encode(string) : utf8ToBytes(string);
};
fromArray = (arr) => {
return Uint8Array.from(arr);
};
slice = useBuffer ? (bytes, start, end) => {
if (isBuffer2(bytes)) {
return new Uint8Array(bytes.subarray(start, end));
}
return bytes.slice(start, end);
} : (bytes, start, end) => {
return bytes.slice(start, end);
};
concat = useBuffer ? (chunks, length2) => {
chunks = chunks.map((c) => c instanceof Uint8Array ? c : globalThis.Buffer.from(c));
return asU8A(globalThis.Buffer.concat(chunks, length2));
} : (chunks, length2) => {
const out = new Uint8Array(length2);
let off = 0;
for (let b of chunks) {
if (off + b.length > out.length) {
b = b.subarray(0, out.length - off);
}
out.set(b, off);
off += b.length;
}
return out;
};
alloc = useBuffer ? (size) => {
return globalThis.Buffer.allocUnsafe(size);
} : (size) => {
return new Uint8Array(size);
};
MAX_ARGUMENTS_LENGTH = 4096;
}
});
// ../../node_modules/cborg/esm/lib/bl.js
var defaultChunkSize, Bl;
var init_bl = __esm({
"../../node_modules/cborg/esm/lib/bl.js"() {
init_byte_utils();
defaultChunkSize = 256;
Bl = class {
constructor(chunkSize = defaultChunkSize) {
this.chunkSize = chunkSize;
this.cursor = 0;
this.maxCursor = -1;
this.chunks = [];
this._initReuseChunk = null;
}
reset() {
this.cursor = 0;
this.maxCursor = -1;
if (this.chunks.length) {
this.chunks = [];
}
if (this._initReuseChunk !== null) {
this.chunks.push(this._initReuseChunk);
this.maxCursor = this._initReuseChunk.length - 1;
}
}
push(bytes) {
let topChunk = this.chunks[this.chunks.length - 1];
const newMax = this.cursor + bytes.length;
if (newMax <= this.maxCursor + 1) {
const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1;
topChunk.set(bytes, chunkPos);
} else {
if (topChunk) {
const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1;
if (chunkPos < topChunk.length) {
this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos);
this.maxCursor = this.cursor - 1;
}
}
if (bytes.length < 64 && bytes.length < this.chunkSize) {
topChunk = alloc(this.chunkSize);
this.chunks.push(topChunk);
this.maxCursor += topChunk.length;
if (this._initReuseChunk === null) {
this._initReuseChunk = topChunk;
}
topChunk.set(bytes, 0);
} else {
this.chunks.push(bytes);
this.maxCursor += bytes.length;
}
}
this.cursor += bytes.length;
}
toBytes(reset = false) {
let byts;
if (this.chunks.length === 1) {
const chunk = this.chunks[0];
if (reset && this.cursor > chunk.length / 2) {
byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor);
this._initReuseChunk = null;
this.chunks = [];
} else {
byts = slice(chunk, 0, this.cursor);
}
} else {
byts = concat(this.chunks, this.cursor);
}
if (reset) {
this.reset();
}
return byts;
}
};
}
});
// ../../node_modules/cborg/esm/lib/common.js
function assertEnoughData(data, pos, need) {
if (data.length - pos < need) {
throw new Error(`${decodeErrPrefix} not enough data for type`);
}
}
var decodeErrPrefix, encodeErrPrefix, uintMinorPrefixBytes;
var init_common = __esm({
"../../node_modules/cborg/esm/lib/common.js"() {
decodeErrPrefix = "CBOR decode error:";
encodeErrPrefix = "CBOR encode error:";
uintMinorPrefixBytes = [];
uintMinorPrefixBytes[23] = 1;
uintMinorPrefixBytes[24] = 2;
uintMinorPrefixBytes[25] = 3;
uintMinorPrefixBytes[26] = 5;
uintMinorPrefixBytes[27] = 9;
}
});
// ../../node_modules/cborg/esm/lib/0uint.js
function readUint8(data, offset, options) {
assertEnoughData(data, offset, 1);
const value = data[offset];
if (options.strict === true && value < uintBoundaries[0]) {
throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
}
return value;
}
function readUint16(data, offset, options) {
assertEnoughData(data, offset, 2);
const value = data[offset] << 8 | data[offset + 1];
if (options.strict === true && value < uintBoundaries[1]) {
throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
}
return value;
}
function readUint32(data, offset, options) {
assertEnoughData(data, offset, 4);
const value = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3];
if (options.strict === true && value < uintBoundaries[2]) {
throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
}
return value;
}
function readUint64(data, offset, options) {
assertEnoughData(data, offset, 8);
const hi = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3];
const lo = data[offset + 4] * 16777216 + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7];
const value = (BigInt(hi) << BigInt(32)) + BigInt(lo);
if (options.strict === true && value < uintBoundaries[3]) {
throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
}
if (value <= Number.MAX_SAFE_INTEGER) {
return Number(value);
}
if (options.allowBigInt === true) {
return value;
}
throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`);
}
function decodeUint8(data, pos, _minor, options) {
return new Token(Type.uint, readUint8(data, pos + 1, options), 2);
}
function decodeUint16(data, pos, _minor, options) {
return new Token(Type.uint, readUint16(data, pos + 1, options), 3);
}
function decodeUint32(data, pos, _minor, options) {
return new Token(Type.uint, readUint32(data, pos + 1, options), 5);
}
function decodeUint64(data, pos, _minor, options) {
return new Token(Type.uint, readUint64(data, pos + 1, options), 9);
}
function encodeUint(buf2, token) {
return encodeUintValue(buf2, 0, token.value);
}
function encodeUintValue(buf2, major, uint) {
if (uint < uintBoundaries[0]) {
const nuint = Number(uint);
buf2.push([major | nuint]);
} else if (uint < uintBoundaries[1]) {
const nuint = Number(uint);
buf2.push([
major | 24,
nuint
]);
} else if (uint < uintBoundaries[2]) {
const nuint = Number(uint);
buf2.push([
major | 25,
nuint >>> 8,
nuint & 255
]);
} else if (uint < uintBoundaries[3]) {
const nuint = Number(uint);
buf2.push([
major | 26,
nuint >>> 24 & 255,
nuint >>> 16 & 255,
nuint >>> 8 & 255,
nuint & 255
]);
} else {
const buint = BigInt(uint);
if (buint < uintBoundaries[4]) {
const set = [
major | 27,
0,
0,
0,
0,
0,
0,
0
];
let lo = Number(buint & BigInt(4294967295));
let hi = Number(buint >> BigInt(32) & BigInt(4294967295));
set[8] = lo & 255;
lo = lo >> 8;
set[7] = lo & 255;
lo = lo >> 8;
set[6] = lo & 255;
lo = lo >> 8;
set[5] = lo & 255;
set[4] = hi & 255;
hi = hi >> 8;
set[3] = hi & 255;
hi = hi >> 8;
set[2] = hi & 255;
hi = hi >> 8;
set[1] = hi & 255;
buf2.push(set);
} else {
throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`);
}
}
}
var uintBoundaries;
var init_uint = __esm({
"../../node_modules/cborg/esm/lib/0uint.js"() {
init_token();
init_common();
uintBoundaries = [
24,
256,
65536,
4294967296,
BigInt("18446744073709551616")
];
encodeUint.encodedSize = function encodedSize(token) {
return encodeUintValue.encodedSize(token.value);
};
encodeUintValue.encodedSize = function encodedSize2(uint) {
if (uint < uintBoundaries[0]) {
return 1;
}
if (uint < uintBoundaries[1]) {
return 2;
}
if (uint < uintBoundaries[2]) {
return 3;
}
if (uint < uintBoundaries[3]) {
return 5;
}
return 9;
};
encodeUint.compareTokens = function compareTokens(tok1, tok2) {
return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0;
};
}
});
// ../../node_modules/cborg/esm/lib/1negint.js
function decodeNegint8(data, pos, _minor, options) {
return new Token(Type.negint, -1 - readUint8(data, pos + 1, options), 2);
}
function decodeNegint16(data, pos, _minor, options) {
return new Token(Type.negint, -1 - readUint16(data, pos + 1, options), 3);
}
function decodeNegint32(data, pos, _minor, options) {
return new Token(Type.negint, -1 - readUint32(data, pos + 1, options), 5);
}
function decodeNegint64(data, pos, _minor, options) {
const int = readUint64(data, pos + 1, options);
if (typeof int !== "bigint") {
const value = -1 - int;
if (value >= Number.MIN_SAFE_INTEGER) {
return new Token(Type.negint, value, 9);
}
}
if (options.allowBigInt !== true) {
throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`);
}
return new Token(Type.negint, neg1b - BigInt(int), 9);
}
function encodeNegint(buf2, token) {
const negint = token.value;
const unsigned = typeof negint === "bigint" ? negint * neg1b - pos1b : negint * -1 - 1;
encodeUintValue(buf2, token.type.majorEncoded, unsigned);
}
var neg1b, pos1b;
var init_negint = __esm({
"../../node_modules/cborg/esm/lib/1negint.js"() {
init_token();
init_uint();
init_common();
neg1b = BigInt(-1);
pos1b = BigInt(1);
encodeNegint.encodedSize = function encodedSize3(token) {
const negint = token.value;
const unsigned = typeof negint === "bigint" ? negint * neg1b - pos1b : negint * -1 - 1;
if (unsigned < uintBoundaries[0]) {
return 1;
}
if (unsigned < uintBoundaries[1]) {
return 2;
}
if (unsigned < uintBoundaries[2]) {
return 3;
}
if (unsigned < uintBoundaries[3]) {
return 5;
}
return 9;
};
encodeNegint.compareTokens = function compareTokens2(tok1, tok2) {
return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0;
};
}
});
// ../../node_modules/cborg/esm/lib/2bytes.js
function toToken(data, pos, prefix, length2) {
assertEnoughData(data, pos, prefix + length2);
const buf2 = slice(data, pos + prefix, pos + prefix + length2);
return new Token(Type.bytes, buf2, prefix + length2);
}
function decodeBytesCompact(data, pos, minor, _options) {
return toToken(data, pos, 1, minor);
}
function decodeBytes8(data, pos, _minor, options) {
return toToken(data, pos, 2, readUint8(data, pos + 1, options));
}
function decodeBytes16(data, pos, _minor, options) {
return toToken(data, pos, 3, readUint16(data, pos + 1, options));
}
function decodeBytes32(data, pos, _minor, options) {
return toToken(data, pos, 5, readUint32(data, pos + 1, options));
}
function decodeBytes64(data, pos, _minor, options) {
const l = readUint64(data, pos + 1, options);
if (typeof l === "bigint") {
throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`);
}
return toToken(data, pos, 9, l);
}
function tokenBytes(token) {
if (token.encodedBytes === void 0) {
token.encodedBytes = token.type === Type.string ? fromString(token.value) : token.value;
}
return token.encodedBytes;
}
function encodeBytes(buf2, token) {
const bytes = tokenBytes(token);
encodeUintValue(buf2, token.type.majorEncoded, bytes.length);
buf2.push(bytes);
}
function compareBytes(b1, b2) {
return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2);
}
var init_bytes = __esm({
"../../node_modules/cborg/esm/lib/2bytes.js"() {
init_token();
init_common();
init_uint();
init_byte_utils();
encodeBytes.encodedSize = function encodedSize4(token) {
const bytes = tokenBytes(token);
return encodeUintValue.encodedSize(bytes.length) + bytes.length;
};
encodeBytes.compareTokens = function compareTokens3(tok1, tok2) {
return compareBytes(tokenBytes(tok1), tokenBytes(tok2));
};
}
});
// ../../node_modules/cborg/esm/lib/3string.js
function toToken2(data, pos, prefix, length2, options) {
const totLength = prefix + length2;
assertEnoughData(data, pos, totLength);
const tok = new Token(Type.string, toString2(data, pos + prefix, pos + totLength), totLength);
if (options.retainStringBytes === true) {
tok.byteValue = slice(data, pos + prefix, pos + totLength);
}
return tok;
}
function decodeStringCompact(data, pos, minor, options) {
return toToken2(data, pos, 1, minor, options);
}
function decodeString8(data, pos, _minor, options) {
return toToken2(data, pos, 2, readUint8(data, pos + 1, options), options);
}
function decodeString16(data, pos, _minor, options) {
return toToken2(data, pos, 3, readUint16(data, pos + 1, options), options);
}
function decodeString32(data, pos, _minor, options) {
return toToken2(data, pos, 5, readUint32(data, pos + 1, options), options);
}
function decodeString64(data, pos, _minor, options) {
const l = readUint64(data, pos + 1, options);
if (typeof l === "bigint") {
throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`);
}
return toToken2(data, pos, 9, l, options);
}
var encodeString;
var init_string = __esm({
"../../node_modules/cborg/esm/lib/3string.js"() {
init_token();
init_common();
init_uint();
init_bytes();
init_byte_utils();
encodeString = encodeBytes;
}
});
// ../../node_modules/cborg/esm/lib/4array.js
function toToken3(_data, _pos, prefix, length2) {
return new Token(Type.array, length2, prefix);
}
function decodeArrayCompact(data, pos, minor, _options) {
return toToken3(data, pos, 1, minor);
}
function decodeArray8(data, pos, _minor, options) {
return toToken3(data, pos, 2, readUint8(data, pos + 1, options));
}
function decodeArray16(data, pos, _minor, options) {
return toToken3(data, pos, 3, readUint16(data, pos + 1, options));
}
function decodeArray32(data, pos, _minor, options) {
return toToken3(data, pos, 5, readUint32(data, pos + 1, options));
}
function decodeArray64(data, pos, _minor, options) {
const l = readUint64(data, pos + 1, options);
if (typeof l === "bigint") {
throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`);
}
return toToken3(data, pos, 9, l);
}
function decodeArrayIndefinite(data, pos, _minor, options) {
if (options.allowIndefinite === false) {
throw new Error(`${decodeErrPrefix} indefinite length items not allowed`);
}
return toToken3(data, pos, 1, Infinity);
}
function encodeArray(buf2, token) {
encodeUintValue(buf2, Type.array.majorEncoded, token.value);
}
var init_array = __esm({
"../../node_modules/cborg/esm/lib/4array.js"() {
init_token();
init_uint();
init_common();
encodeArray.compareTokens = encodeUint.compareTokens;
encodeArray.encodedSize = function encodedSize5(token) {
return encodeUintValue.encodedSize(token.value);
};
}
});
// ../../node_modules/cborg/esm/lib/5map.js
function toToken4(_data, _pos, prefix, length2) {
return new Token(Type.map, length2, prefix);
}
function decodeMapCompact(data, pos, minor, _options) {
return toToken4(data, pos, 1, minor);
}
function decodeMap8(data, pos, _minor, options) {
return toToken4(data, pos, 2, readUint8(data, pos + 1, options));
}
function decodeMap16(data, pos, _minor, options) {
return toToken4(data, pos, 3, readUint16(data, pos + 1, options));
}
function decodeMap32(data, pos, _minor, options) {
return toToken4(data, pos, 5, readUint32(data, pos + 1, options));
}
function decodeMap64(data, pos, _minor, options) {
const l = readUint64(data, pos + 1, options);
if (typeof l === "bigint") {
throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`);
}
return toToken4(data, pos, 9, l);
}
function decodeMapIndefinite(data, pos, _minor, options) {
if (options.allowIndefinite === false) {
throw new Error(`${decodeErrPrefix} indefinite length items not allowed`);
}
return toToken4(data, pos, 1, Infinity);
}
function encodeMap(buf2, token) {
encodeUintValue(buf2, Type.map.majorEncoded, token.value);
}
var init_map = __esm({
"../../node_modules/cborg/esm/lib/5map.js"() {
init_token();
init_uint();
init_common();
encodeMap.compareTokens = encodeUint.compareTokens;
encodeMap.encodedSize = function encodedSize6(token) {
return encodeUintValue.encodedSize(token.value);
};
}
});
// ../../node_modules/cborg/esm/lib/6tag.js
function decodeTagCompact(_data, _pos, minor, _options) {
return new Token(Type.tag, minor, 1);
}
function decodeTag8(data, pos, _minor, options) {
return new Token(Type.tag, readUint8(data, pos + 1, options), 2);
}
function decodeTag16(data, pos, _minor, options) {
return new Token(Type.tag, readUint16(data, pos + 1, options), 3);
}
function decodeTag32(data, pos, _minor, options) {
return new Token(Type.tag, readUint32(data, pos + 1, options), 5);
}
function decodeTag64(data, pos, _minor, options) {
return new Token(Type.tag, readUint64(data, pos + 1, options), 9);
}
function encodeTag(buf2, token) {
encodeUintValue(buf2, Type.tag.majorEncoded, token.value);
}
var init_tag = __esm({
"../../node_modules/cborg/esm/lib/6tag.js"() {
init_token();
init_uint();
encodeTag.compareTokens = encodeUint.compareTokens;
encodeTag.encodedSize = function encodedSize7(token) {
return encodeUintValue.encodedSize(token.value);
};
}
});
// ../../node_modules/cborg/esm/lib/7float.js
function decodeUndefined(_data, _pos, _minor, options) {
if (options.allowUndefined === false) {
throw new Error(`${decodeErrPrefix} undefined values are not supported`);
} else if (options.coerceUndefinedToNull === true) {
return new Token(Type.null, null, 1);
}
return new Token(Type.undefined, void 0, 1);
}
function decodeBreak(_data, _pos, _minor, options) {
if (options.allowIndefinite === false) {
throw new Error(`${decodeErrPrefix} indefinite length items not allowed`);
}
return new Token(Type.break, void 0, 1);
}
function createToken(value, bytes, options) {
if (options) {
if (options.allowNaN === false && Number.isNaN(value)) {
throw new Error(`${decodeErrPrefix} NaN values are not supported`);
}
if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {
throw new Error(`${decodeErrPrefix} Infinity values are not supported`);
}
}
return new Token(Type.float, value, bytes);
}
function decodeFloat16(data, pos, _minor, options) {
return createToken(readFloat16(data, pos + 1), 3, options);
}
function decodeFloat32(data, pos, _minor, options) {
return createToken(readFloat32(data, pos + 1), 5, options);
}
function decodeFloat64(data, pos, _minor, options) {
return createToken(readFloat64(data, pos + 1), 9, options);
}
function encodeFloat(buf2, token, options) {
const float = token.value;
if (float === false) {
buf2.push([Type.float.majorEncoded | MINOR_FALSE]);
} else if (float === true) {
buf2.push([Type.float.majorEncoded | MINOR_TRUE]);
} else if (float === null) {
buf2.push([Type.float.majorEncoded | MINOR_NULL]);
} else if (float === void 0) {
buf2.push([Type.float.majorEncoded | MINOR_UNDEFINED]);
} else {
let decoded;
let success = false;
if (!options || options.float64 !== true) {
encodeFloat16(float);
decoded = readFloat16(ui8a, 1);
if (float === decoded || Number.isNaN(float)) {
ui8a[0] = 249;
buf2.push(ui8a.slice(0, 3));
success = true;
} else {
encodeFloat32(float);
decoded = readFloat32(ui8a, 1);
if (float === decoded) {
ui8a[0] = 250;
buf2.push(ui8a.slice(0, 5));
success = true;
}
}
}
if (!success) {
encodeFloat64(float);
decoded = readFloat64(ui8a, 1);
ui8a[0] = 251;
buf2.push(ui8a.slice(0, 9));
}
}
}
function encodeFloat16(inp) {
if (inp === Infinity) {
dataView.setUint16(0, 31744, false);
} else if (inp === -Infinity) {
dataView.setUint16(0, 64512, false);
} else if (Number.isNaN(inp)) {
dataView.setUint16(0, 32256, false);
} else {
dataView.setFloat32(0, inp);
const valu32 = dataView.getUint32(0);
const exponent = (valu32 & 2139095040) >> 23;
const mantissa = valu32 & 8388607;
if (exponent === 255) {
dataView.setUint16(0, 31744, false);
} else if (exponent === 0) {
dataView.setUint16(0, (inp & 2147483648) >> 16 | mantissa >> 13, false);
} else {
const logicalExponent = exponent - 127;
if (logicalExponent < -24) {
dataView.setUint16(0, 0);
} else if (logicalExponent < -14) {
dataView.setUint16(0, (valu32 & 2147483648) >> 16 | 1 << 24 + logicalExponent, false);
} else {
dataView.setUint16(0, (valu32 & 2147483648) >> 16 | logicalExponent + 15 << 10 | mantissa >> 13, false);
}
}
}
}
function readFloat16(ui8a2, pos) {
if (ui8a2.length - pos < 2) {
throw new Error(`${decodeErrPrefix} not enough data for float16`);
}
const half = (ui8a2[pos] << 8) + ui8a2[pos + 1];
if (half === 31744) {
return Infinity;
}
if (half === 64512) {
return -Infinity;
}
if (half === 32256) {
return NaN;
}
const exp = half >> 10 & 31;
const mant = half & 1023;
let val;
if (exp === 0) {
val = mant * 2 ** -24;
} else if (exp !== 31) {
val = (mant + 1024) * 2 ** (exp - 25);
} else {
val = mant === 0 ? Infinity : NaN;
}
return half & 32768 ? -val : val;
}
function encodeFloat32(inp) {
dataView.setFloat32(0, inp, false);
}
function readFloat32(ui8a2, pos) {
if (ui8a2.length - pos < 4) {
throw new Error(`${decodeErrPrefix} not enough data for float32`);
}
const offset = (ui8a2.byteOffset || 0) + pos;
return new DataView(ui8a2.buffer, offset, 4).getFloat32(0, false);
}
function encodeFloat64(inp) {
dataView.setFloat64(0, inp, false);
}
function readFloat64(ui8a2, pos) {
if (ui8a2.length - pos < 8) {
throw new Error(`${decodeErrPrefix} not enough data for float64`);
}
const offset = (ui8a2.byteOffset || 0) + pos;
return new DataView(ui8a2.buffer, offset, 8).getFloat64(0, false);
}
var MINOR_FALSE, MINOR_TRUE, MINOR_NULL, MINOR_UNDEFINED, buffer, dataView, ui8a;
var init_float = __esm({
"../../node_modules/cborg/esm/lib/7float.js"() {
init_token();
init_common();
init_uint();
MINOR_FALSE = 20;
MINOR_TRUE = 21;
MINOR_NULL = 22;
MINOR_UNDEFINED = 23;
encodeFloat.encodedSize = function encodedSize8(token, options) {
const float = token.value;
if (float === false || float === true || float === null || float === void 0) {
return 1;
}
if (!options || options.float64 !== true) {
encodeFloat16(float);
let decoded = readFloat16(ui8a, 1);
if (float === decoded || Number.isNaN(float)) {
return 3;
}
encodeFloat32(float);
decoded = readFloat32(ui8a, 1);
if (float === decoded) {
return 5;
}
}
return 9;
};
buffer = new ArrayBuffer(9);
dataView = new DataView(buffer, 1);
ui8a = new Uint8Array(buffer, 0);
encodeFloat.compareTokens = encodeUint.compareTokens;
}
});
// ../../node_modules/cborg/esm/lib/jump.js
function invalidMinor(data, pos, minor) {
throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`);
}
function errorer(msg) {
return () => {
throw new Error(`${decodeErrPrefix} ${msg}`);
};
}
function quickEncodeToken(token) {
switch (token.type) {
case Type.false:
return fromArray([244]);
case Type.true:
return fromArray([245]);
case Type.null:
return fromArray([246]);
case Type.bytes:
if (!token.value.length) {
return fromArray([64]);
}
return;
case Type.string:
if (token.value === "") {
return fromArray([96]);
}
return;
case Type.array:
if (token.value === 0) {
return fromArray([128]);
}
return;
case Type.map:
if (token.value === 0) {
return fromArray([160]);
}
return;
case Type.uint:
if (token.value < 24) {
return fromArray([Number(token.value)]);
}
return;
case Type.negint:
if (token.value >= -24) {
return fromArray([31 - Number(token.value)]);
}
}
}
var jump, quick;
var init_jump = __esm({
"../../node_modules/cborg/esm/lib/jump.js"() {
init_token();
init_uint();
init_negint();
init_bytes();
init_string();
init_array();
init_map();
init_tag();
init_float();
init_common();
init_byte_utils();
jump = [];
for (let i = 0; i <= 23; i++) {
jump[i] = invalidMinor;
}
jump[24] = decodeUint8;
jump[25] = decodeUint16;
jump[26] = decodeUint32;
jump[27] = decodeUint64;
jump[28] = invalidMinor;
jump[29] = invalidMinor;
jump[30] = invalidMinor;
jump[31] = invalidMinor;
for (let i = 32; i <= 55; i++) {
jump[i] = invalidMinor;
}
jump[56] = decodeNegint8;
jump[57] = decodeNegint16;
jump[58] = decodeNegint32;
jump[59] = decodeNegint64;
jump[60] = invalidMinor;
jump[61] = invalidMinor;
jump[62] = invalidMinor;
jump[63] = invalidMinor;
for (let i = 64; i <= 87; i++) {
jump[i] = decodeBytesCompact;
}
jump[88] = decodeBytes8;
jump[89] = decodeBytes16;
jump[90] = decodeBytes32;
jump[91] = decodeBytes64;
jump[92] = invalidMinor;
jump[93] = invalidMinor;
jump[94] = invalidMinor;
jump[95] = errorer("indefinite length bytes/strings are not supported");
for (let i = 96; i <= 119; i++) {
jump[i] = decodeStringCompact;
}
jump[120] = decodeString8;
jump[121] = decodeString16;
jump[122] = decodeString32;
jump[123] = decodeString64;
jump[124] = invalidMinor;
jump[125] = invalidMinor;
jump[126] = invalidMinor;
jump[127] = errorer("indefinite length bytes/strings are not supported");
for (let i = 128; i <= 151; i++) {
jump[i] = decodeArrayCompact;
}
jump[152] = decodeArray8;
jump[153] = decodeArray16;
jump[154] = decodeArray32;
jump[155] = decodeArray64;
jump[156] = invalidMinor;
jump[157] = invalidMinor;
jump[158] = invalidMinor;
jump[159] = decodeArrayIndefinite;
for (let i = 160; i <= 183; i++) {
jump[i] = decodeMapCompact;
}
jump[184] = decodeMap8;
jump[185] = decodeMap16;
jump[186] = decodeMap32;
jump[187] = decodeMap64;
jump[188] = invalidMinor;
jump[189] = invalidMinor;
jump[190] = invalidMinor;
jump[191] = decodeMapIndefinite;
for (let i = 192; i <= 215; i++) {
jump[i] = decodeTagCompact;
}
jump[216] = decodeTag8;
jump[217] = decodeTag16;
jump[218] = decodeTag32;
jump[219] = decodeTag64;
jump[220] = invalidMinor;
jump[221] = invalidMinor;
jump[222] = invalidMinor;
jump[223] = invalidMinor;
for (let i = 224; i <= 243; i++) {
jump[i] = errorer("simple values are not supported");
}
jump[244] = invalidMinor;
jump[245] = invalidMinor;
jump[246] = invalidMinor;
jump[247] = decodeUndefined;
jump[248] = errorer("simple values are not supported");
jump[249] = decodeFloat16;
jump[250] = decodeFloat32;
jump[251] = decodeFloat64;
jump[252] = invalidMinor;
jump[253] = invalidMinor;
jump[254] = invalidMinor;
jump[255] = decodeBreak;
quick = [];
for (let i = 0; i < 24; i++) {
quick[i] = new Token(Type.uint, i, 1);
}
for (let i = -1; i >= -24; i--) {
quick[31 - i] = new Token(Type.negint, i, 1);
}
quick[64] = new Token(Type.bytes, new Uint8Array(0), 1);
quick[96] = new Token(Type.string, "", 1);
quick[128] = new Token(Type.array, 0, 1);
quick[160] = new Token(Type.map, 0, 1);
quick[244] = new Token(Type.false, false, 1);
quick[245] = new Token(Type.true, true, 1);
quick[246] = new Token(Type.null, null, 1);
}
});
// ../../node_modules/cborg/esm/lib/encode.js
function makeCborEncoders() {
const encoders = [];
encoders[Type.uint.major] = encodeUint;
encoders[Type.negint.major] = encodeNegint;
encoders[Type.bytes.major] = encodeBytes;
encoders[Type.string.major] = encodeString;
encoders[Type.array.major] = encodeArray;
encoders[Type.map.major] = encodeMap;
encoders[Type.tag.major] = encodeTag;
encoders[Type.float.major] = encodeFloat;
return encoders;
}
function objectToTokens(obj, options = {}, refStack) {
const typ = is(obj);
const customTypeEncoder = options && options.typeEncoders && options.typeEncoders[typ] || typeEncoders[typ];
if (typeof customTypeEncoder === "function") {
const tokens = customTypeEncoder(obj, typ, options, refStack);
if (tokens != null) {
return tokens;
}
}
const typeEncoder = typeEncoders[typ];
if (!typeEncoder) {
throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`);
}
return typeEncoder(obj, typ, options, refStack);
}
function sortMapEntries(entries, options) {
if (options.mapSorter) {
entries.sort(options.mapSorter);
}
}
function mapSorter(e1, e2) {
const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0];
const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0];
if (keyToken1.type !== keyToken2.type) {
return keyToken1.type.compare(keyToken2.type);
}
const major = keyToken1.type.major;
const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2);
if (tcmp === 0) {
console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone");
}
return tcmp;
}
function tokensToEncoded(buf2, tokens, encoders, options) {
if (Array.isArray(tokens)) {
for (const token of tokens) {
tokensToEncoded(buf2, token, encoders, options);
}
} else {
encoders[tokens.type.major](buf2, tokens, options);
}
}
function encodeCustom(data, encoders, options) {
const tokens = objectToTokens(data, options);
if (!Array.isArray(tokens) && options.quickEncodeToken) {
const quickBytes = options.quickEncodeToken(tokens);
if (quickBytes) {
return quickBytes;
}
const encoder = encoders[tokens.type.major];
if (encoder.encodedSize) {
const size = encoder.encodedSize(tokens, options);
const buf2 = new Bl(size);
encoder(buf2, tokens, options);
if (buf2.chunks.length !== 1) {
throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`);
}
return asU8A(buf2.chunks[0]);
}
}
buf.reset();
tokensToEncoded(buf, tokens, encoders, options);
return buf.toBytes(true);
}
function encode(data, options) {
options = Object.assign({}, defaultEncodeOptions, options);
return encodeCustom(data, cborEncoders, options);
}
var defaultEncodeOptions, cborEncoders, buf, Ref, simpleTokens, typeEncoders;
var init_encode = __esm({
"../../node_modules/cborg/esm/lib/encode.js"() {
init_is();
init_token();
init_bl();
init_common();
init_jump();
init_byte_utils();
init_uint();
init_negint();
init_bytes();
init_string();
init_array();
init_map();
init_tag();
init_float();
defaultEncodeOptions = {
float64: false,
mapSorter,
quickEncodeToken
};
cborEncoders = makeCborEncoders();
buf = new Bl();
Ref = class {
constructor(obj, parent) {
this.obj = obj;
this.parent = parent;
}
includes(obj) {
let p = this;
do {
if (p.obj === obj) {
return true;
}
} while (p = p.parent);
return false;
}
static createCheck(stack, obj) {
if (stack && stack.includes(obj)) {
throw new Error(`${encodeErrPrefix} object contains circular references`);
}
return new Ref(obj, stack);
}
};
simpleTokens = {
null: new Token(Type.null, null),
undefined: new Token(Type.undefined, void 0),
true: new Token(Type.true, true),
false: new Token(Type.false, false),
emptyArray: new Token(Type.array, 0),
emptyMap: new Token(Type.map, 0)
};
typeEncoders = {
number(obj, _typ, _options, _refStack) {
if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {
return new Token(Type.float, obj);
} else if (obj >= 0) {
return new Token(Type.uint, obj);
} else {
return new Token(Type.negint, obj);
}
},
bigint(obj, _typ, _options, _refStack) {
if (obj >= BigInt(0)) {
return new Token(Type.uint, obj);
} else {
return new Token(Type.negint, obj);
}
},
Uint8Array(obj, _typ, _options, _refStack) {
return new Token(Type.bytes, obj);
},
string(obj, _typ, _options, _refStack) {
return new Token(Type.string, obj);
},
boolean(obj, _typ, _options, _refStack) {
return obj ? simpleTokens.true : simpleTokens.false;
},
null(_obj, _typ, _options, _refStack) {
return simpleTokens.null;
},
undefined(_obj, _typ, _options, _refStack) {
return simpleTokens.undefined;
},
ArrayBuffer(obj, _typ, _options, _refStack) {
return new Token(Type.bytes, new Uint8Array(obj));
},
DataView(obj, _typ, _options, _refStack) {
return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength));
},
Array(obj, _typ, options, refStack) {
if (!obj.length) {
if (options.addBreakTokens === true) {
return [
simpleTokens.emptyArray,
new Token(Type.break)
];
}
return simpleTokens.emptyArray;
}
refStack = Ref.createCheck(refStack, obj);
const entries = [];
let i = 0;
for (const e of obj) {
entries[i++] = objectToTokens(e, options, refStack);
}
if (options.addBreakTokens) {
return [
new Token(Type.array, obj.length),
entries,
new Token(Type.break)
];
}
return [
new Token(Type.array, obj.length),
entries
];
},
Object(obj, typ, options, refStack) {
const isMap = typ !== "Object";
const keys = isMap ? obj.keys() : Object.keys(obj);
const length2 = isMap ? obj.size : keys.length;
if (!length2) {
if (options.addBreakTokens === true) {
return [
simpleTokens.emptyMap,
new Token(Type.break)
];
}
return simpleTokens.emptyMap;
}
refStack = Ref.createCheck(refStack, obj);
const entries = [];
let i = 0;
for (const key of keys) {
entries[i++] = [
objectToTokens(key, options, refStack),
objectToTokens(isMap ? obj.get(key) : obj[key], options, refStack)
];
}
sortMapEntries(entries, options);
if (options.addBreakTokens) {
return [
new Token(Type.map, length2),
entries,
new Token(Type.break)
];
}
return [
new Token(Type.map, length2),
entries
];
}
};
typeEncoders.Map = typeEncoders.Object;
typeEncoders.Buffer = typeEncoders.Uint8Array;
for (const typ of "Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" ")) {
typeEncoders[`${typ}Array`] = typeEncoders.DataView;
}
}
});
// ../../node_modules/cborg/esm/lib/decode.js
function tokenToArray(token, tokeniser, options) {
const arr = [];
for (let i = 0; i < token.value; i++) {
const value = tokensToObject(tokeniser, options);
if (value === BREAK) {
if (token.value === Infinity) {
break;
}
throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`);
}
if (value === DONE) {
throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`);
}
arr[i] = value;
}
return arr;
}
function tokenToMap(token, tokeniser, options) {
const useMaps = options.useMaps === true;
const obj = useMaps ? void 0 : {};
const m = useMaps ? /* @__PURE__ */ new Map() : void 0;
for (let i = 0; i < token.value; i++) {
const key = tokensToObject(tokeniser, options);
if (key === BREAK) {
if (token.value === Infinity) {
break;
}
throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`);
}
if (key === DONE) {
throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`);
}
if (useMaps !== true && typeof key !== "string") {
throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`);
}
if (options.rejectDuplicateMapKeys === true) {
if (useMaps && m.has(key) || !useMaps && key in obj) {
throw new Error(`${decodeErrPrefix} found repeat map key "${key}"`);
}
}
const value = tokensToObject(tokeniser, options);
if (value === DONE) {
throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`);
}
if (useMaps) {
m.set(key, value);
} else {
obj[key] = value;
}
}
return useMaps ? m : obj;
}
function tokensToObject(tokeniser, options) {
if (tokeniser.done()) {
return DONE;
}
const token = tokeniser.next();
if (token.type === Type.break) {
return BREAK;
}
if (token.type.terminal) {
return token.value;
}
if (token.type === Type.array) {
return tokenToArray(token, tokeniser, options);
}
if (token.type === Type.map) {
return tokenToMap(token, tokeniser, options);
}
if (token.type === Type.tag) {
if (options.tags && typeof options.tags[token.value] === "function") {
const tagged = tokensToObject(tokeniser, options);
return options.tags[token.value](tagged);
}
throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`);
}
throw new Error("unsupported");
}
function decode(data, options) {
if (!(data instanceof Uint8Array)) {
throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`);
}
options = Object.assign({}, defaultDecodeOptions, options);
const tokeniser = options.tokenizer || new Tokeniser(data, options);
const decoded = tokensToObject(tokeniser, options);
if (decoded === DONE) {
throw new Error(`${decodeErrPrefix} did not find any content to decode`);
}
if (decoded === BREAK) {
throw new Error(`${decodeErrPrefix} got unexpected break`);
}
if (!tokeniser.done()) {
throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`);
}
return decoded;
}
var defaultDecodeOptions, Tokeniser, DONE, BREAK;
var init_decode = __esm({
"../../node_modules/cborg/esm/lib/decode.js"() {
init_common();
init_token();
init_jump();
defaultDecodeOptions = {
strict: false,
allowIndefinite: true,
allowUndefined: true,
allowBigInt: true
};
Tokeniser = class {
constructor(data, options = {}) {
this.pos = 0;
this.data = data;
this.options = options;
}
done() {
return this.pos >= this.data.length;
}
next() {
const byt = this.data[this.pos];
let token = quick[byt];
if (token === void 0) {
const decoder = jump[byt];
if (!decoder) {
throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, "0")})`);
}
const minor = byt & 31;
token = decoder(this.data, this.pos, minor, this.options);
}
this.pos += token.encodedLength;
return token;
}
};
DONE = Symbol.for("DONE");
BREAK = Symbol.for("BREAK");
}
});
// ../../node_modules/cborg/esm/cborg.js
var init_cborg = __esm({
"../../node_modules/cborg/esm/cborg.js"() {
init_encode();
init_decode();
init_token();
}
});
// ../../node_modules/multiformats/vendor/varint.js
function encode2(num, out, offset) {
out = out || [];
offset = offset || 0;
var oldOffset = offset;
while (num >= INT) {
out[offset++] = num & 255 | MSB;
num /= 128;
}
while (num & MSBALL) {
out[offset++] = num & 255 | MSB;
num >>>= 7;
}
out[offset] = num | 0;
encode2.bytes = offset - oldOffset + 1;
return out;
}
function read(buf2, offset) {
var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf2.length;
do {
if (counter >= l) {
read.bytes = 0;
throw new RangeError("Could not decode varint");
}
b = buf2[counter++];
res += shift < 28 ? (b & REST$1) << shift : (b & REST$1) * Math.pow(2, shift);
shift += 7;
} while (b >= MSB$1);
read.bytes = counter - offset;
return res;
}
var encode_1, MSB, REST, MSBALL, INT, decode2, MSB$1, REST$1, N1, N2, N3, N4, N5, N6, N7, N8, N9, length, varint, _brrp_varint, varint_default;
var init_varint = __esm({
"../../node_modules/multiformats/vendor/varint.js"() {
encode_1 = encode2;
MSB = 128;
REST = 127;
MSBALL = ~REST;
INT = Math.pow(2, 31);
decode2 = read;
MSB$1 = 128;
REST$1 = 127;
N1 = Math.pow(2, 7);
N2 = Math.pow(2, 14);
N3 = Math.pow(2, 21);
N4 = Math.pow(2, 28);
N5 = Math.pow(2, 35);
N6 = Math.pow(2, 42);
N7 = Math.pow(2, 49);
N8 = Math.pow(2, 56);
N9 = Math.pow(2, 63);
length = function(value) {
return value < N1 ? 1 : value < N2 ? 2 : value < N3 ? 3 : value < N4 ? 4 : value < N5 ? 5 : value < N6 ? 6 : value < N7 ? 7 : value < N8 ? 8 : value < N9 ? 9 : 10;
};
varint = {
encode: encode_1,
decode: decode2,
encodingLength: length
};
_brrp_varint = varint;
varint_default = _brrp_varint;
}
});
// ../../node_modules/multiformats/src/varint.js
var decode3, encodeTo, encodingLength;
var init_varint2 = __esm({
"../../node_modules/multiformats/src/varint.js"() {
init_varint();
decode3 = (data, offset = 0) => {
const code2 = varint_default.decode(data, offset);
return [code2, varint_default.decode.bytes];
};
encodeTo = (int, target, offset = 0) => {
varint_default.encode(int, target, offset);
return target;
};
encodingLength = (int) => {
return varint_default.encodingLength(int);
};
}
});
// ../../node_modules/multiformats/src/bytes.js
var empty, equals, coerce;
var init_bytes2 = __esm({
"../../node_modules/multiformats/src/bytes.js"() {
empty = new Uint8Array(0);
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;
};
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");
};
}
});
// ../../node_modules/multiformats/src/hashes/digest.js
var create, decode4, equals2, Digest;
var init_digest = __esm({
"../../node_modules/multiformats/src/hashes/digest.js"() {
init_bytes2();
init_varint2();
create = (code2, digest) => {
const size = digest.byteLength;
const sizeOffset = encodingLength(code2);
const digestOffset = sizeOffset + encodingLength(size);
const bytes = new Uint8Array(digestOffset + size);
encodeTo(code2, bytes, 0);
encodeTo(size, bytes, sizeOffset);
bytes.set(digest, digestOffset);
return new Digest(code2, size, digest, bytes);
};
decode4 = (multihash) => {
const bytes = coerce(multihash);
const [code2, sizeOffset] = decode3(bytes);
const [size, digestOffset] = decode3(bytes.subarray(sizeOffset));
const digest = bytes.subarray(sizeOffset + digestOffset);
if (digest.byteLength !== size) {
throw new Error("Incorrect length");
}
return new Digest(code2, size, digest, bytes);
};
equals2 = (a, b) => {
if (a === b) {
return true;
} else {
const data = (
/** @type {{code?:unknown, size?:unknown, bytes?:unknown}} */
b
);
return a.code === data.code && a.size === data.size && data.bytes instanceof Uint8Array && equals(a.bytes, data.bytes);
}
};
Digest = class {
/**
* Creates a multihash digest.
*
* @param {Code} code
* @param {Size} size
* @param {Uint8Array} digest
* @param {Uint8Array} bytes
*/
constructor(code2, size, digest, bytes) {
this.code = code2;
this.size = size;
this.digest = digest;
this.bytes = bytes;
}
};
}
});
// ../../node_modules/multiformats/vendor/base-x.js
function base(ALPHABET, name2) {
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);
var iFACTOR = Math.log(256) / Math.log(BASE);
function encode6(source) {
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 "";
}
var zeroes = 0;
var length2 = 0;
var pbegin = 0;
var pend = source.length;
while (pbegin !== pend && source[pbegin] === 0) {
pbegin++;
zeroes++;
}
var size = (pend - pbegin) * iFACTOR + 1 >>> 0;
var b58 = new Uint8Array(size);
while (pbegin !== pend) {
var carry = source[pbegin];
var i2 = 0;
for (var it1 = size - 1; (carry !== 0 || i2 < length2) && it1 !== -1; it1--, i2++) {
carry += 256 * b58[it1] >>> 0;
b58[it1] = carry % BASE >>> 0;
carry = carry / BASE >>> 0;
}
if (carry !== 0) {
throw new Error("Non-zero carry");
}
length2 = i2;
pbegin++;
}
var it2 = size - length2;
while (it2 !== size && b58[it2] === 0) {
it2++;
}
var str = LEADER.repeat(zeroes);
for (; it2 < size; ++it2) {
str += ALPHABET.charAt(b58[it2]);
}
return str;
}
function decodeUnsafe(source) {
if (typeof source !== "string") {
throw new TypeError("Expected String");
}
if (source.length === 0) {
return new Uint8Array();
}
var psz = 0;
if (source[psz] === " ") {
return;
}
var zeroes = 0;
var length2 = 0;
while (source[psz] === LEADER) {
zeroes++;
psz++;
}
var size = (source.length - psz) * FACTOR + 1 >>> 0;
var b256 = new Uint8Array(size);
while (source[psz]) {
var carry = BASE_MAP[source.charCodeAt(psz)];
if (carry === 255) {
return;
}
var i2 = 0;
for (var it3 = size - 1; (carry !== 0 || i2 < length2) && it3 !== -1; it3--, i2++) {
carry += BASE * b256[it3] >>> 0;
b256[it3] = carry % 256 >>> 0;
carry = carry / 256 >>> 0;
}
if (carry !== 0) {
throw new Error("Non-zero carry");
}
length2 = i2;
psz++;
}
if (source[psz] === " ") {
return;
}
var it4 = size - length2;
while (it4 !== size && b256[it4] === 0) {
it4++;
}
var vch = new Uint8Array(zeroes + (size - it4));
var j2 = zeroes;
while (it4 !== size) {
vch[j2++] = b256[it4++];
}
return vch;
}
function decode7(string) {
var buffer2 = decodeUnsafe(string);
if (buffer2) {
return buffer2;
}
throw new Error(`Non-${name2} character`);
}
return {
encode: encode6,
decodeUnsafe,
decode: decode7
};
}
var src, _brrp__multiformats_scope_baseX, base_x_default;
var init_base_x = __esm({
"../../node_modules/multiformats/vendor/base-x.js"() {
src = base;
_brrp__multiformats_scope_baseX = src;
base_x_default = _brrp__multiformats_scope_baseX;
}
});
// ../../node_modules/multiformats/src/bases/base.js
var Encoder, Decoder, ComposedDecoder, or, Codec, from, baseX, decode5, encode3, rfc4648;
var init_base = __esm({
"../../node_modules/multiformats/src/bases/base.js"() {
init_base_x();
init_bytes2();
Encoder = class {
/**
* @param {Base} name
* @param {Prefix} prefix
* @param {(bytes:Uint8Array) => string} baseEncode
*/
constructor(name2, prefix, baseEncode) {
this.name = name2;
this.prefix = prefix;
this.baseEncode = baseEncode;
}
/**
* @param {Uint8Array} bytes
* @returns {API.Multibase<Prefix>}
*/
encode(bytes) {
if (bytes instanceof Uint8Array) {
return `${this.prefix}${this.baseEncode(bytes)}`;
} else {
throw Error("Unknown type, must be binary type");
}
}
};
Decoder = class {
/**
* @param {Base} name
* @param {Prefix} prefix
* @param {(text:string) => Uint8Array} baseDecode
*/
constructor(name2, prefix, baseDecode) {
this.name = name2;
this.prefix = prefix;
if (prefix.codePointAt(0) === void 0) {
throw new Error("Invalid prefix character");
}
this.prefixCodePoint = /** @type {number} */
prefix.codePointAt(0);
this.baseDecode = baseDecode;
}
/**
* @param {string} text
*/
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");
}
}
/**
* @template {string} OtherPrefix
* @param {API.UnibaseDecoder<OtherPrefix>|ComposedDecoder<OtherPrefix>} decoder
* @returns {ComposedDecoder<Prefix|OtherPrefix>}
*/
or(decoder) {
return or(this, decoder);
}
};
ComposedDecoder = class {
/**
* @param {Decoders<Prefix>} decoders
*/
constructor(decoders) {
this.decoders = decoders;
}
/**
* @template {string} OtherPrefix
* @param {API.UnibaseDecoder<OtherPrefix>|ComposedDecoder<OtherPrefix>} decoder
* @returns {ComposedDecoder<Prefix|OtherPrefix>}
*/
or(decoder) {
return or(this, decoder);
}
/**
* @param {string} input
* @returns {Uint8Array}
*/
decode(input) {
const prefix = (
/** @type {Prefix} */
input[0]
);
const decoder = this.decoders[prefix];
if (decoder) {
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`);
}
}
};
or = (left, right) => new ComposedDecoder(
/** @type {Decoders<L|R>} */
{
...left.decoders || { [
/** @type API.UnibaseDecoder<L> */
left.prefix
]: left },
...right.decoders || { [
/** @type API.UnibaseDecoder<R> */
right.prefix
]: right }
}
);
Codec = class {
/**
* @param {Base} name
* @param {Prefix} prefix
* @param {(bytes:Uint8Array) => string} baseEncode
* @param {(text:string) => Uint8Array} baseDecode
*/
constructor(name2, prefix, baseEncode, baseDecode) {
this.name = name2;
this.prefix = prefix;
this.baseEncode = baseEncode;
this.baseDecode = baseDecode;
this.encoder = new Encoder(name2, prefix, baseEncode);
this.decoder = new Decoder(name2, prefix, baseDecode);
}
/**
* @param {Uint8Array} input
*/
encode(input) {
return this.encoder.encode(input);
}
/**
* @param {string} input
*/
decode(input) {
return this.decoder.decode(input);
}
};
from = ({ name: name2, prefix, encode: encode6, decode: decode7 }) => new Codec(name2, prefix, encode6, decode7);
baseX = ({ prefix, name: name2, alphabet }) => {
const { encode: encode6, decode: decode7 } = base_x_default(alphabet, name2);
return from({
prefix,
name: name2,
encode: encode6,
/**
* @param {string} text
*/
decode: (text) => coerce(decode7(text))
});
};
decode5 = (string, alphabet, bitsPerChar, name2) => {
const codes = {};
for (let i = 0; i < alphabet.length; ++i) {
codes[alphabet[i]] = i;
}
let end = string.length;
while (string[end - 1] === "=") {
--end;
}
const out = new Uint8Array(end * bitsPerChar / 8 | 0);
let bits = 0;
let buffer2 = 0;
let written = 0;
for (let i = 0; i < end; ++i) {
const value = codes[string[i]];
if (value === void 0) {
throw new SyntaxError(`Non-${name2} character`);
}
buffer2 = buffer2 << bitsPerChar | value;
bits += bitsPerChar;
if (bits >= 8) {
bits -= 8;
out[written++] = 255 & buffer2 >> bits;
}
}
if (bits >= bitsPerChar || 255 & buffer2 << 8 - bits) {
throw new SyntaxError("Unexpected end of data");
}
return out;
};
encode3 = (data, alphabet, bitsPerChar) => {
const pad = alphabet[alphabet.length - 1] === "=";
const mask = (1 << bitsPerChar) - 1;
let out = "";
let bits = 0;
let buffer2 = 0;
for (let i = 0; i < data.length; ++i) {
buffer2 = buffer2 << 8 | data[i];
bits += 8;
while (bits > bitsPerChar) {
bits -= bitsPerChar;
out += alphabet[mask & buffer2 >> bits];
}
}
if (bits) {
out += alphabet[mask & buffer2 << bitsPerChar - bits];
}
if (pad) {
while (out.length * bitsPerChar & 7) {
out += "=";
}
}
return out;
};
rfc4648 = ({ name: name2, prefix, bitsPerChar, alphabet }) => {
return from({
prefix,
name: name2,
encode(input) {
return encode3(input, alphabet, bitsPerChar);
},
decode(input) {
return decode5(input, alphabet, bitsPerChar, name2);
}
});
};
}
});
// ../../node_modules/multiformats/src/bases/base58.js
var base58btc, base58flickr;
var init_base58 = __esm({
"../../node_modules/multiformats/src/bases/base58.js"() {
init_base();
base58btc = baseX({
name: "base58btc",
prefix: "z",
alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
});
base58flickr = baseX({
name: "base58flickr",
prefix: "Z",
alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
});
}
});
// ../../node_modules/multiformats/src/bases/base32.js
var base32, base32upper, base32pad, base32padupper, base32hex, base32hexupper, base32hexpad, base32hexpadupper, base32z;
var init_base32 = __esm({
"../../node_modules/multiformats/src/bases/base32.js"() {
init_base();
base32 = rfc4648({
prefix: "b",
name: "base32",
alphabet: "abcdefghijklmnopqrstuvwxyz234567",
bitsPerChar: 5
});
base32upper = rfc4648({
prefix: "B",
name: "base32upper",
alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",
bitsPerChar: 5
});
base32pad = rfc4648({
prefix: "c",
name: "base32pad",
alphabet: "abcdefghijklmnopqrstuvwxyz234567=",
bitsPerChar: 5
});
base32padupper = rfc4648({
prefix: "C",
name: "base32padupper",
alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",
bitsPerChar: 5
});
base32hex = rfc4648({
prefix: "v",
name: "base32hex",
alphabet: "0123456789abcdefghijklmnopqrstuv",
bitsPerChar: 5
});
base32hexupper = rfc4648({
prefix: "V",
name: "base32hexupper",
alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV",
bitsPerChar: 5
});
base32hexpad = rfc4648({
prefix: "t",
name: "base32hexpad",
alphabet: "0123456789abcdefghijklmnopqrstuv=",
bitsPerChar: 5
});
base32hexpadupper = rfc4648({
prefix: "T",
name: "base32hexpadupper",
alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=",
bitsPerChar: 5
});
base32z = rfc4648({
prefix: "h",
name: "base32z",
alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769",
bitsPerChar: 5
});
}
});
// ../../node_modules/multiformats/src/link/interface.js
var init_interface = __esm({
"../../node_modules/multiformats/src/link/interface.js"() {
}
});
// ../../node_modules/multiformats/src/cid.js
var format, cache, baseCache, CID, parseCIDtoBytes, toStringV0, toStringV1, DAG_PB_CODE, SHA_256_CODE, encodeCID, cidSymbol;
var init_cid = __esm({
"../../node_modules/multiformats/src/cid.js"() {
init_varint2();
init_digest();
init_base58();
init_base32();
init_bytes2();
init_interface();
format = (link, base2) => {
const { bytes, version } = link;
switch (version) {
case 0:
return toStringV0(
bytes,
baseCache(link),
/** @type {API.MultibaseEncoder<"z">} */
base2 || base58btc.encoder
);
default:
return toStringV1(
bytes,
baseCache(link),
/** @type {API.MultibaseEncoder<Prefix>} */
base2 || base32.encoder
);
}
};
cache = /* @__PURE__ */ new WeakMap();
baseCache = (cid) => {
const baseCache2 = cache.get(cid);
if (baseCache2 == null) {
const baseCache3 = /* @__PURE__ */ new Map();
cache.set(cid, baseCache3);
return baseCache3;
}
return baseCache2;
};
CID = class {
/**
* @param {Version} version - Version of the CID
* @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
* @param {API.MultihashDigest<Alg>} multihash - (Multi)hash of the of the content.
* @param {Uint8Array} bytes
*
*/
constructor(version, code2, multihash, bytes) {
this.code = code2;
this.version = version;
this.multihash = multihash;
this.bytes = bytes;
this["/"] = bytes;
}
/**
* Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
* please either use `CID.asCID(cid)` or switch to new signalling mechanism
*
* @deprecated
*/
get asCID() {
return this;
}
// ArrayBufferView
get byteOffset() {
return this.bytes.byteOffset;
}
// ArrayBufferView
get byteLength() {
return this.bytes.byteLength;
}
/**
* @returns {CID<Data, API.DAG_PB, API.SHA_256, 0>}
*/
toV0() {
switch (this.version) {
case 0: {
return (
/** @type {CID<Data, API.DAG_PB, API.SHA_256, 0>} */
this
);
}
case 1: {
const { code: code2, multihash } = this;
if (code2 !== DAG_PB_CODE) {
throw new Error("Cannot convert a non dag-pb CID to CIDv0");
}
if (multihash.code !== SHA_256_CODE) {
throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");
}
return (
/** @type {CID<Data, API.DAG_PB, API.SHA_256, 0>} */
CID.createV0(
/** @type {API.MultihashDigest<API.SHA_256>} */
multihash
)
);
}
default: {
throw Error(
`Can not convert CID version ${this.version} to version 0. This is a bug please report`
);
}
}
}
/**
* @returns {CID<Data, Format, Alg, 1>}
*/
toV1() {
switch (this.version) {
case 0: {
const { code: code2, digest } = this.multihash;
const multihash = create(code2, digest);
return (
/** @type {CID<Data, Format, Alg, 1>} */
CID.createV1(this.code, multihash)
);
}
case 1: {
return (
/** @type {CID<Data, Format, Alg, 1>} */
this
);
}
default: {
throw Error(
`Can not convert CID version ${this.version} to version 1. This is a bug please report`
);
}
}
}
/**
* @param {unknown} other
* @returns {other is CID<Data, Format, Alg, Version>}
*/
equals(other) {
return CID.equals(this, other);
}
/**
* @template {unknown} Data
* @template {number} Format
* @template {number} Alg
* @template {API.Version} Version
* @param {API.Link<Data, Format, Alg, Version>} self
* @param {unknown} other
* @returns {other is CID}
*/
static equals(self, other) {
const unknown = (
/** @type {{code?:unknown, version?:unknown, multihash?:unknown}} */
other
);
return unknown && self.code === unknown.code && self.version === unknown.version && equals2(self.multihash, unknown.multihash);
}
/**
* @param {API.MultibaseEncoder<string>} [base]
* @returns {string}
*/
toString(base2) {
return format(this, base2);
}
toJSON() {
return { "/": format(this) };
}
link() {
return this;
}
get [Symbol.toStringTag]() {
return "CID";
}
// Legacy
[Symbol.for("nodejs.util.inspect.custom")]() {
return `CID(${this.toString()})`;
}
/**
* Takes any input `value` and returns a `CID` instance if it was
* a `CID` otherwise returns `null`. If `value` is instanceof `CID`
* it will return value back. If `value` is not instance of this CID
* class, but is compatible CID it will return new instance of this
* `CID` class. Otherwise returns null.
*
* This allows two different incompatible versions of CID library to
* co-exist and interop as long as binary interface is compatible.
*
* @template {unknown} Data
* @template {number} Format
* @template {number} Alg
* @template {API.Version} Version
* @template {unknown} U
* @param {API.Link<Data, Format, Alg, Version>|U} input
* @returns {CID<Data, Format, Alg, Version>|null}
*/
static asCID(input) {
if (input == null) {
return null;
}
const value = (
/** @type {any} */
input
);
if (value instanceof CID) {
return value;
} else if (value["/"] != null && value["/"] === value.bytes || value.asCID === value) {
const { version, code: code2, multihash, bytes } = value;
return new CID(
version,
code2,
/** @type {API.MultihashDigest<Alg>} */
multihash,
bytes || encodeCID(version, code2, multihash.bytes)
);
} else if (value[cidSymbol] === true) {
const { version, multihash, code: code2 } = value;
const digest = (
/** @type {API.MultihashDigest<Alg>} */
decode4(multihash)
);
return CID.create(version, code2, digest);
} else {
return null;
}
}
/**
*
* @template {unknown} Data
* @template {number} Format
* @template {number} Alg
* @template {API.Version} Version
* @param {Version} version - Version of the CID
* @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
* @param {API.MultihashDigest<Alg>} digest - (Multi)hash of the of the content.
* @returns {CID<Data, Format, Alg, Version>}
*/
static create(version, code2, digest) {
if (typeof code2 !== "number") {
throw new Error("String codecs are no longer supported");
}
if (!(digest.bytes instanceof Uint8Array)) {
throw new Error("Invalid digest");
}
switch (version) {
case 0: {
if (code2 !== DAG_PB_CODE) {
throw new Error(
`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`
);
} else {
return new CID(version, code2, digest, digest.bytes);
}
}
case 1: {
const bytes = encodeCID(version, code2, digest.bytes);
return new CID(version, code2, digest, bytes);
}
default: {
throw new Error("Invalid version");
}
}
}
/**
* Simplified version of `create` for CIDv0.
*
* @template {unknown} [T=unknown]
* @param {API.MultihashDigest<typeof SHA_256_CODE>} digest - Multihash.
* @returns {CID<T, typeof DAG_PB_CODE, typeof SHA_256_CODE, 0>}
*/
static createV0(digest) {
return CID.create(0, DAG_PB_CODE, digest);
}
/**
* Simplified version of `create` for CIDv1.
*
* @template {unknown} Data
* @template {number} Code
* @template {number} Alg
* @param {Code} code - Content encoding format code.
* @param {API.MultihashDigest<Alg>} digest - Miltihash of the content.
* @returns {CID<Data, Code, Alg, 1>}
*/
static createV1(code2, digest) {
return CID.create(1, code2, digest);
}
/**
* Decoded a CID from its binary representation. The byte array must contain
* only the CID with no additional bytes.
*
* An error will be thrown if the bytes provided do not contain a valid
* binary representation of a CID.
*
* @template {unknown} Data
* @template {number} Code
* @template {number} Alg
* @template {API.Version} Ver
* @param {API.ByteView<API.Link<Data, Code, Alg, Ver>>} bytes
* @returns {CID<Data, Code, Alg, Ver>}
*/
static decode(bytes) {
const [cid, remainder] = CID.decodeFirst(bytes);
if (remainder.length) {
throw new Error("Incorrect length");
}
return cid;
}
/**
* Decoded a CID from its binary representation at the beginning of a byte
* array.
*
* Returns an array with the first element containing the CID and the second
* element containing the remainder of the original byte array. The remainder
* will be a zero-length byte array if the provided bytes only contained a
* binary CID representation.
*
* @template {unknown} T
* @template {number} C
* @template {number} A
* @template {API.Version} V
* @param {API.ByteView<API.Link<T, C, A, V>>} bytes
* @returns {[CID<T, C, A, V>, Uint8Array]}
*/
static decodeFirst(bytes) {
const specs = CID.inspectBytes(bytes);
const prefixSize = specs.size - specs.multihashSize;
const multihashBytes = coerce(
bytes.subarray(prefixSize, prefixSize + specs.multihashSize)
);
if (multihashBytes.byteLength !== specs.multihashSize) {
throw new Error("Incorrect length");
}
const digestBytes = multihashBytes.subarray(
specs.multihashSize - specs.digestSize
);
const digest = new Digest(
specs.multihashCode,
specs.digestSize,
digestBytes,
multihashBytes
);
const cid = specs.version === 0 ? CID.createV0(
/** @type {API.MultihashDigest<API.SHA_256>} */
digest
) : CID.createV1(specs.codec, digest);
return [
/** @type {CID<T, C, A, V>} */
cid,
bytes.subarray(specs.size)
];
}
/**
* Inspect the initial bytes of a CID to determine its properties.
*
* Involves decoding up to 4 varints. Typically this will require only 4 to 6
* bytes but for larger multicodec code values and larger multihash digest
* lengths these varints can be quite large. It is recommended that at least
* 10 bytes be made available in the `initialBytes` argument for a complete
* inspection.
*
* @template {unknown} T
* @template {number} C
* @template {number} A
* @template {API.Version} V
* @param {API.ByteView<API.Link<T, C, A, V>>} initialBytes
* @returns {{ version:V, codec:C, multihashCode:A, digestSize:number, multihashSize:number, size:number }}
*/
static inspectBytes(initialBytes) {
let offset = 0;
const next = () => {
const [i, length2] = decode3(initialBytes.subarray(offset));
offset += length2;
return i;
};
let version = (
/** @type {V} */
next()
);
let codec = (
/** @type {C} */
DAG_PB_CODE
);
if (
/** @type {number} */
version === 18
) {
version = /** @type {V} */
0;
offset = 0;
} else {
codec = /** @type {C} */
next();
}
if (version !== 0 && version !== 1) {
throw new RangeError(`Invalid CID version ${version}`);
}
const prefixSize = offset;
const multihashCode = (
/** @type {A} */
next()
);
const digestSize = next();
const size = offset + digestSize;
const multihashSize = size - prefixSize;
return { version, codec, multihashCode, digestSize, multihashSize, size };
}
/**
* Takes cid in a string representation and creates an instance. If `base`
* decoder is not provided will use a default from the configuration. It will
* throw an error if encoding of the CID is not compatible with supplied (or
* a default decoder).
*
* @template {string} Prefix
* @template {unknown} Data
* @template {number} Code
* @template {number} Alg
* @template {API.Version} Ver
* @param {API.ToString<API.Link<Data, Code, Alg, Ver>, Prefix>} source
* @param {API.MultibaseDecoder<Prefix>} [base]
* @returns {CID<Data, Code, Alg, Ver>}
*/
static parse(source, base2) {
const [prefix, bytes] = parseCIDtoBytes(source, base2);
const cid = CID.decode(bytes);
if (cid.version === 0 && source[0] !== "Q") {
throw Error("Version 0 CID string must not include multibase prefix");
}
baseCache(cid).set(prefix, source);
return cid;
}
};
parseCIDtoBytes = (source, base2) => {
switch (source[0]) {
case "Q": {
const decoder = base2 || base58btc;
return [
/** @type {Prefix} */
base58btc.prefix,
decoder.decode(`${base58btc.prefix}${source}`)
];
}
case base58btc.prefix: {
const decoder = base2 || base58btc;
return [
/** @type {Prefix} */
base58btc.prefix,
decoder.decode(source)
];
}
case base32.prefix: {
const decoder = base2 || base32;
return [
/** @type {Prefix} */
base32.prefix,
decoder.decode(source)
];
}
default: {
if (base2 == null) {
throw Error(
"To parse non base32 or base58btc encoded CID multibase decoder must be provided"
);
}
return [
/** @type {Prefix} */
source[0],
base2.decode(source)
];
}
}
};
toStringV0 = (bytes, cache2, base2) => {
const { prefix } = base2;
if (prefix !== base58btc.prefix) {
throw Error(`Cannot string encode V0 in ${base2.name} encoding`);
}
const cid = cache2.get(prefix);
if (cid == null) {
const cid2 = base2.encode(bytes).slice(1);
cache2.set(prefix, cid2);
return cid2;
} else {
return cid;
}
};
toStringV1 = (bytes, cache2, base2) => {
const { prefix } = base2;
const cid = cache2.get(prefix);
if (cid == null) {
const cid2 = base2.encode(bytes);
cache2.set(prefix, cid2);
return cid2;
} else {
return cid;
}
};
DAG_PB_CODE = 112;
SHA_256_CODE = 18;
encodeCID = (version, code2, multihash) => {
const codeOffset = encodingLength(version);
const hashOffset = codeOffset + encodingLength(code2);
const bytes = new Uint8Array(hashOffset + multihash.byteLength);
encodeTo(version, bytes, 0);
encodeTo(code2, bytes, codeOffset);
bytes.set(multihash, hashOffset);
return bytes;
};
cidSymbol = Symbol.for("@ipld/js-cid/CID");
}
});
// ../../node_modules/@ipld/dag-cbor/src/index.js
var src_exports = {};
__export(src_exports, {
code: () => code,
decode: () => decode6,
encode: () => encode4,
name: () => name
});
function cidEncoder(obj) {
if (obj.asCID !== obj && obj["/"] !== obj.bytes) {
return null;
}
const cid = CID.asCID(obj);
if (!cid) {
return null;
}
const bytes = new Uint8Array(cid.bytes.byteLength + 1);
bytes.set(cid.bytes, 1);
return [
new Token(Type.tag, CID_CBOR_TAG),
new Token(Type.bytes, bytes)
];
}
function undefinedEncoder() {
throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded");
}
function numberEncoder(num) {
if (Number.isNaN(num)) {
throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");
}
if (num === Infinity || num === -Infinity) {
throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");
}
return null;
}
function cidDecoder(bytes) {
if (bytes[0] !== 0) {
throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");
}
return CID.decode(bytes.subarray(1));
}
var CID_CBOR_TAG, encodeOptions, decodeOptions, name, code, encode4, decode6;
var init_src = __esm({
"../../node_modules/@ipld/dag-cbor/src/index.js"() {
init_cborg();
init_cid();
CID_CBOR_TAG = 42;
encodeOptions = {
float64: true,
typeEncoders: {
Object: cidEncoder,
undefined: undefinedEncoder,
number: numberEncoder
}
};
decodeOptions = {
allowIndefinite: false,
coerceUndefinedToNull: true,
allowNaN: false,
allowInfinity: false,
allowBigInt: true,
// this will lead to BigInt for ints outside of
// safe-integer range, which may surprise users
strict: true,
useMaps: false,
rejectDuplicateMapKeys: true,
/** @type {import('cborg').TagDecoder[]} */
tags: []
};
decodeOptions.tags[CID_CBOR_TAG] = cidDecoder;
name = "dag-cbor";
code = 113;
encode4 = (node) => encode(node, encodeOptions);
decode6 = (data) => decode(data, decodeOptions);
}
});
// ../../node_modules/multiformats/src/hashes/hasher.js
var from2, Hasher;
var init_hasher = __esm({
"../../node_modules/multiformats/src/hashes/hasher.js"() {
init_digest();
from2 = ({ name: name2, code: code2, encode: encode6 }) => new Hasher(name2, code2, encode6);
Hasher = class {
/**
*
* @param {Name} name
* @param {Code} code
* @param {(input: Uint8Array) => Await<Uint8Array>} encode
*/
constructor(name2, code2, encode6) {
this.name = name2;
this.code = code2;
this.encode = encode6;
}
/**
* @param {Uint8Array} input
* @returns {Await<Digest.Digest<Code, number>>}
*/
digest(input) {
if (input instanceof Uint8Array) {
const result = this.encode(input);
return result instanceof Uint8Array ? create(this.code, result) : result.then((digest) => create(this.code, digest));
} else {
throw Error("Unknown type, must be binary type");
}
}
};
}
});
// ../../node_modules/multiformats/src/hashes/sha2-browser.js
var sha, sha256, sha512;
var init_sha2_browser = __esm({
"../../node_modules/multiformats/src/hashes/sha2-browser.js"() {
init_hasher();
sha = (name2) => (
/**
* @param {Uint8Array} data
*/
async (data) => new Uint8Array(await crypto.subtle.digest(name2, data))
);
sha256 = from2({
name: "sha2-256",
code: 18,
encode: sha("SHA-256")
});
sha512 = from2({
name: "sha2-512",
code: 19,
encode: sha("SHA-512")
});
}
});
// ../../node_modules/multiformats/src/interface.js
var init_interface2 = __esm({
"../../node_modules/multiformats/src/interface.js"() {
}
});
// ../../node_modules/multiformats/src/index.js
var init_src2 = __esm({
"../../node_modules/multiformats/src/index.js"() {
init_cid();
init_varint2();
init_bytes2();
init_hasher();
init_digest();
init_interface2();
}
});
// ../../node_modules/multiformats/src/block.js
function readonly({ enumerable = true, configurable = false } = {}) {
return { enumerable, configurable, writable: false };
}
function* linksWithin(path, value) {
if (value != null && typeof value === "object") {
if (Array.isArray(value)) {
for (const [index, element] of value.entries()) {
const elementPath = [...path, index];
const cid = CID.asCID(element);
if (cid) {
yield [elementPath.join("/"), cid];
} else if (typeof element === "object") {
yield* links(element, elementPath);
}
}
} else {
const cid = CID.asCID(value);
if (cid) {
yield [path.join("/"), cid];
} else {
yield* links(value, path);
}
}
}
}
function* links(source, base2) {
if (source == null || source instanceof Uint8Array) {
return;
}
const cid = CID.asCID(source);
if (cid) {
yield [base2.join("/"), cid];
}
for (const [key, value] of Object.entries(source)) {
const path = (
/** @type {[string|number, string]} */
[...base2, key]
);
yield* linksWithin(path, value);
}
}
function* treeWithin(path, value) {
if (Array.isArray(value)) {
for (const [index, element] of value.entries()) {
const elementPath = [...path, index];
yield elementPath.join("/");
if (typeof element === "object" && !CID.asCID(element)) {
yield* tree(element, elementPath);
}
}
} else {
yield* tree(value, path);
}
}
function* tree(source, base2) {
if (source == null || typeof source !== "object") {
return;
}
for (const [key, value] of Object.entries(source)) {
const path = (
/** @type {[string|number, string]} */
[...base2, key]
);
yield path.join("/");
if (value != null && !(value instanceof Uint8Array) && typeof value === "object" && !CID.asCID(value)) {
yield* treeWithin(path, value);
}
}
}
function get(source, path) {
let node = (
/** @type {Record<string, any>} */
source
);
for (const [index, key] of path.entries()) {
node = node[key];
if (node == null) {
throw new Error(`Object has no property at ${path.slice(0, index + 1).map((part) => `[${JSON.stringify(part)}]`).join("")}`);
}
const cid = CID.asCID(node);
if (cid) {
return { value: cid, remaining: path.slice(index + 1).join("/") };
}
}
return { value: node };
}
async function encode5({ value, codec, hasher }) {
if (typeof value === "undefined")
throw new Error('Missing required argument "value"');
if (!codec || !hasher)
throw new Error("Missing required argument: codec or hasher");
const bytes = codec.encode(value);
const hash = await hasher.digest(bytes);
const cid = CID.create(
1,
codec.code,
hash
);
return new Block({ value, bytes, cid });
}
var Block;
var init_block = __esm({
"../../node_modules/multiformats/src/block.js"() {
init_src2();
Block = class {
/**
* @param {object} options
* @param {CID<T, C, A, V>} options.cid
* @param {API.ByteView<T>} options.bytes
* @param {T} options.value
*/
constructor({ cid, bytes, value }) {
if (!cid || !bytes || typeof value === "undefined") {
throw new Error("Missing required argument");
}
this.cid = cid;
this.bytes = bytes;
this.value = value;
this.asBlock = this;
Object.defineProperties(this, {
cid: readonly(),
bytes: readonly(),
value: readonly(),
asBlock: readonly()
});
}
links() {
return links(this.value, []);
}
tree() {
return tree(this.value, []);
}
/**
*
* @param {string} [path]
* @returns {API.BlockCursorView<unknown>}
*/
get(path = "/") {
return get(this.value, path.split("/").filter(Boolean));
}
};
}
});
// lit_actions/src/main.action.ts
var require_main_action = __commonJS({
"lit_actions/src/main.action.ts"(exports) {
init_src();
init_sha2_browser();
init_block();
var go = () => __async(exports, null, function* () {
const payload = { "data": { "link_id": "kjzl6kcym7w8y6mlt4jg7so9lvuqixkl7c7uh9y7ndvxcnmf65d30hua8eku9wu", "index_id": "kjzl6kcym7w8y87yu5qkjfo27l3wvvkfq2b99t0p624b32tqc0wu0eoeiqb02s2", "created_at": "2023-04-20T12:53:48.407Z", "updated_at": "2023-04-20T12:53:48.407Z", "indexer_did": "did:key:z6MkfQcGtC6diZtiT379LLugPsYFeeFjX9m6UUrrzdwHNmH1" }, "header": { "model": { "0": 206, "1": 1, "2": 2, "3": 1, "4": 133, "5": 1, "6": 18, "7": 32, "8": 6, "9": 44, "10": 48, "11": 93, "12": 42, "13": 123, "14": 115, "15": 227, "16": 175, "17": 161, "18": 221, "19": 33, "20": 16, "21": 132, "22": 9, "23": 76, "24": 7, "25": 213, "26": 1, "27": 0, "28": 27, "29": 11, "30": 202, "31": 111, "32": 141, "33": 152, "34": 144, "35": 43, "36": 40, "37": 109, "38": 155, "39": 96 }, "unique": { "0": 248, "1": 194, "2": 130, "3": 214, "4": 112, "5": 125, "6": 98, "7": 43, "8": 88, "9": 171, "10": 207, "11": 9 }, "controllers": ["did:key:zQ3shmbBM4xA6h4gfgLhvYSpkm2vXDnFeWcBoBEPcoghwBQEn"] } };
const linkedBlockEncoded = yield encode5({
value: payload,
codec: src_exports,
hasher: sha256
});
console.log(linkedBlockEncoded);
return;
});
go();
}
});
require_main_action();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment