{"version":3,"file":"Royh6j-X.js","sources":["../../../../node_modules/@heroicons/vue/outline/esm/BadgeCheckIcon.js","../../../../node_modules/@heroicons/vue/outline/esm/CheckCircleIcon.js","../../../../node_modules/@heroicons/vue/outline/esm/CheckIcon.js","../../../../components/mint/MintDidSelector.client.vue","../../../../components/mint/MintCollectionSelector.vue","../../../../node_modules/multiformats/dist/src/bytes.js","../../../../node_modules/multiformats/dist/src/vendor/base-x.js","../../../../node_modules/multiformats/dist/src/bases/base.js","../../../../node_modules/multiformats/dist/src/bases/base32.js","../../../../node_modules/multiformats/dist/src/bases/base58.js","../../../../node_modules/multiformats/dist/src/vendor/varint.js","../../../../node_modules/multiformats/dist/src/varint.js","../../../../node_modules/multiformats/dist/src/hashes/digest.js","../../../../node_modules/multiformats/dist/src/cid.js","../../../../node_modules/@ipld/dag-pb/src/pb-decode.js","../../../../node_modules/@ipld/dag-pb/src/pb-encode.js","../../../../node_modules/@ipld/dag-pb/src/util.js","../../../../node_modules/@ipld/dag-pb/src/index.js","../../../../node_modules/@protobufjs/aspromise/index.js","../../../../node_modules/@protobufjs/base64/index.js","../../../../node_modules/@protobufjs/eventemitter/index.js","../../../../node_modules/@protobufjs/float/index.js","../../../../node_modules/@protobufjs/inquire/index.js","../../../../node_modules/@protobufjs/utf8/index.js","../../../../node_modules/@protobufjs/pool/index.js","../../../../node_modules/protobufjs/src/util/longbits.js","../../../../node_modules/protobufjs/src/util/minimal.js","../../../../node_modules/protobufjs/src/writer.js","../../../../node_modules/protobufjs/src/writer_buffer.js","../../../../node_modules/protobufjs/src/reader.js","../../../../node_modules/protobufjs/src/reader_buffer.js","../../../../node_modules/protobufjs/src/rpc/service.js","../../../../node_modules/protobufjs/src/rpc.js","../../../../node_modules/protobufjs/src/roots.js","../../../../node_modules/protobufjs/src/index-minimal.js","../../../../node_modules/protobufjs/minimal.js","../../../../node_modules/@ipld/unixfs/gen/unixfs.js","../../../../node_modules/@ipld/unixfs/src/unixfs.js","../../../../node_modules/@ipld/unixfs/src/codec.js","../../../../node_modules/actor/src/lib.js","../../../../node_modules/@ipld/unixfs/src/file/chunker/indexed.js","../../../../node_modules/@ipld/unixfs/src/file/chunker/buffer.js","../../../../node_modules/@ipld/unixfs/src/writer/util.js","../../../../node_modules/@ipld/unixfs/src/file/chunker.js","../../../../node_modules/@ipld/unixfs/src/file/layout/queue.js","../../../../node_modules/@ipld/unixfs/src/file/writer.js","../../../../node_modules/@ipld/unixfs/src/file/chunker/fixed.js","../../../../node_modules/multiformats/dist/src/hashes/hasher.js","../../../../node_modules/multiformats/dist/src/hashes/sha2-browser.js","../../../../node_modules/@ipld/unixfs/src/file/layout/balanced.js","../../../../node_modules/@ipld/unixfs/src/file.js","../../../../node_modules/@ipld/unixfs/src/directory.js","../../../../node_modules/@perma/map/src/bitfield/Uint32.js","../../../../node_modules/murmurhash3js-revisited/lib/murmurHash3js.js","../../../../node_modules/murmurhash3js-revisited/index.js","../../../../node_modules/@perma/map/src/path/Uint32.js","../../../../node_modules/@perma/map/src/node.js","../../../../node_modules/@multiformats/murmur3/src/index.js","../../../../node_modules/@perma/map/src/path/Uint8Array.js","../../../../node_modules/@perma/map/src/bitfield/Uint8Array.js","../../../../node_modules/@perma/map/src/lib.js","../../../../node_modules/@perma/map/src/path/InfiniteUint8Array.js","../../../../node_modules/@perma/map/src/unixfs.js","../../../../node_modules/multiformats/dist/src/block.js","../../../../node_modules/@ipld/unixfs/src/sharded-directory.js","../../../../node_modules/@ipld/unixfs/src/lib.js","../../../../node_modules/multiformats/dist/src/codecs/raw.js","../../../../node_modules/ipfs-car/unixfs.js","../../../../node_modules/varint/encode.js","../../../../node_modules/varint/decode.js","../../../../node_modules/varint/length.js","../../../../node_modules/varint/index.js","../../../../node_modules/cborg/lib/is.js","../../../../node_modules/cborg/lib/token.js","../../../../node_modules/cborg/lib/byte-utils.js","../../../../node_modules/cborg/lib/bl.js","../../../../node_modules/cborg/lib/common.js","../../../../node_modules/cborg/lib/0uint.js","../../../../node_modules/cborg/lib/1negint.js","../../../../node_modules/cborg/lib/2bytes.js","../../../../node_modules/cborg/lib/3string.js","../../../../node_modules/cborg/lib/4array.js","../../../../node_modules/cborg/lib/5map.js","../../../../node_modules/cborg/lib/6tag.js","../../../../node_modules/cborg/lib/7float.js","../../../../node_modules/cborg/lib/jump.js","../../../../node_modules/cborg/lib/encode.js","../../../../node_modules/@ipld/dag-cbor/src/index.js","../../../../node_modules/ipfs-car/car.js","../../../../utilities/filebase-uploader.ts","../../../../components/goby/GobyUrlInputWithUpload.vue","../../../../components/goby/GobyCreateCollectionForm.vue","../../../../components/mint/MintDropZone.vue","../../../../node_modules/papaparse/papaparse.min.js","../../../../types/minting.ts","../../../../components/mint/MintFolderUploader.vue","../../../../components/mint/MintSingleDetailsForm.vue","../../../../node_modules/base64-js/index.js","../../../../node_modules/ieee754/index.js","../../../../node_modules/buffer/index.js","../../../../components/goby/GobyCreateCollectionModal.vue","../../../../types/store.ts","../../../../utilities/files.ts","../../../../components/mint/MintSingleForm.client.vue","../../../../pages/mint/index.vue"],"sourcesContent":["import { createVNode as _createVNode, openBlock as _openBlock, createBlock as _createBlock } from \"vue\"\n\nexport default function render(_ctx, _cache) {\n return (_openBlock(), _createBlock(\"svg\", {\n xmlns: \"http://www.w3.org/2000/svg\",\n fill: \"none\",\n viewBox: \"0 0 24 24\",\n \"stroke-width\": \"2\",\n stroke: \"currentColor\",\n \"aria-hidden\": \"true\"\n }, [\n _createVNode(\"path\", {\n \"stroke-linecap\": \"round\",\n \"stroke-linejoin\": \"round\",\n d: \"M9 12l2 2 4-4M7.835 4.697a3.42 3.42 0 001.946-.806 3.42 3.42 0 014.438 0 3.42 3.42 0 001.946.806 3.42 3.42 0 013.138 3.138 3.42 3.42 0 00.806 1.946 3.42 3.42 0 010 4.438 3.42 3.42 0 00-.806 1.946 3.42 3.42 0 01-3.138 3.138 3.42 3.42 0 00-1.946.806 3.42 3.42 0 01-4.438 0 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-3.138-3.138 3.42 3.42 0 00-.806-1.946 3.42 3.42 0 010-4.438 3.42 3.42 0 00.806-1.946 3.42 3.42 0 013.138-3.138z\"\n })\n ]))\n}","import { createVNode as _createVNode, openBlock as _openBlock, createBlock as _createBlock } from \"vue\"\n\nexport default function render(_ctx, _cache) {\n return (_openBlock(), _createBlock(\"svg\", {\n xmlns: \"http://www.w3.org/2000/svg\",\n fill: \"none\",\n viewBox: \"0 0 24 24\",\n \"stroke-width\": \"2\",\n stroke: \"currentColor\",\n \"aria-hidden\": \"true\"\n }, [\n _createVNode(\"path\", {\n \"stroke-linecap\": \"round\",\n \"stroke-linejoin\": \"round\",\n d: \"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z\"\n })\n ]))\n}","import { createVNode as _createVNode, openBlock as _openBlock, createBlock as _createBlock } from \"vue\"\n\nexport default function render(_ctx, _cache) {\n return (_openBlock(), _createBlock(\"svg\", {\n xmlns: \"http://www.w3.org/2000/svg\",\n fill: \"none\",\n viewBox: \"0 0 24 24\",\n \"stroke-width\": \"2\",\n stroke: \"currentColor\",\n \"aria-hidden\": \"true\"\n }, [\n _createVNode(\"path\", {\n \"stroke-linecap\": \"round\",\n \"stroke-linejoin\": \"round\",\n d: \"M5 13l4 4L19 7\"\n })\n ]))\n}","\n\n \n \n \n \n \n \n \n {{ selectedProfile.name }}\n {{\n selectedProfile.encoded_id.substring(0, 36) + '...'\n }}\n \n \n \n Loading...\n \n \n No profile available\n \n \n \n \n \n\n \n \n \n \n \n \n \n\n \n \n {{ profile.name }} {{ profile.didCoin.locked ? '(locked)' : '' }}\n {{\n profile.encoded_id.substring(0, 36) + '...'\n }}\n \n \n\n \n \n \n \n \n \n \n \n \n\n","\n\n \n \n \n \n \n \n {{\n selectedCollection.name\n }}\n \n \n Loading...\n \n \n No Collection\n \n \n \n \n \n\n \n \n \n \n \n No Collection \n \n\n \n \n \n \n \n \n \n \n \n \n {{ collection.name }}\n \n \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n {{ collection.name }}\n \n \n \n \n\n","export const empty = new Uint8Array(0);\nexport function toHex(d) {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');\n}\nexport function fromHex(hex) {\n const hexes = hex.match(/../g);\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;\n}\nexport function equals(aa, bb) {\n if (aa === bb)\n return true;\n if (aa.byteLength !== bb.byteLength) {\n return false;\n }\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false;\n }\n }\n return true;\n}\nexport function coerce(o) {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array')\n return o;\n if (o instanceof ArrayBuffer)\n return new Uint8Array(o);\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);\n }\n throw new Error('Unknown type, must be binary type');\n}\nexport function isBinary(o) {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o);\n}\nexport function fromString(str) {\n return new TextEncoder().encode(str);\n}\nexport function toString(b) {\n return new TextDecoder().decode(b);\n}\n//# sourceMappingURL=bytes.js.map","/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base(ALPHABET, name) {\n if (ALPHABET.length >= 255) {\n throw new TypeError('Alphabet too long');\n }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) {\n throw new TypeError(x + ' is ambiguous');\n }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable} source\n */\n function encode(source) {\n // @ts-ignore\n if (source instanceof Uint8Array)\n ;\n else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n }\n else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) {\n throw new TypeError('Expected Uint8Array');\n }\n if (source.length === 0) {\n return '';\n }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) {\n throw new Error('Non-zero carry');\n }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) {\n str += ALPHABET.charAt(b58[it2]);\n }\n return str;\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe(source) {\n if (typeof source !== 'string') {\n throw new TypeError('Expected String');\n }\n if (source.length === 0) {\n return new Uint8Array();\n }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') {\n return;\n }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) {\n return;\n }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) {\n throw new Error('Non-zero carry');\n }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') {\n return;\n }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch;\n }\n /**\n * @param {string | string[]} string\n */\n function decode(string) {\n var buffer = decodeUnsafe(string);\n if (buffer) {\n return buffer;\n }\n throw new Error(`Non-${name} character`);\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n };\n}\nvar src = base;\nvar _brrp__multiformats_scope_baseX = src;\nexport default _brrp__multiformats_scope_baseX;\n//# sourceMappingURL=base-x.js.map","import { coerce } from '../bytes.js';\nimport basex from '../vendor/base-x.js';\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefix.codePointAt(0);\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nexport function or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nexport class Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nexport function from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nexport function baseX({ name, prefix, alphabet }) {\n const { encode, decode } = basex(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => coerce(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nexport function rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map","import { rfc4648 } from './base.js';\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n});\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n});\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n});\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n});\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n});\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n});\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n});\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n});\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n});\n//# sourceMappingURL=base32.js.map","import { baseX } from './base.js';\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n});\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n});\n//# sourceMappingURL=base58.js.map","/* eslint-disable */\nvar encode_1 = encode;\nvar MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n while (num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while (num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n return out;\n}\nvar decode = read;\nvar MSB$1 = 0x80, REST$1 = 0x7F;\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint');\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1);\n // @ts-ignore\n read.bytes = counter - offset;\n return res;\n}\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\nvar length = function (/** @type {number} */ value) {\n return (value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10);\n};\nvar varint = {\n encode: encode_1,\n decode: decode,\n encodingLength: length\n};\nvar _brrp_varint = varint;\nexport default _brrp_varint;\n//# sourceMappingURL=varint.js.map","import varint from './vendor/varint.js';\nexport function decode(data, offset = 0) {\n const code = varint.decode(data, offset);\n return [code, varint.decode.bytes];\n}\nexport function encodeTo(int, target, offset = 0) {\n varint.encode(int, target, offset);\n return target;\n}\nexport function encodingLength(int) {\n return varint.encodingLength(int);\n}\n//# sourceMappingURL=varint.js.map","import { coerce, equals as equalBytes } from '../bytes.js';\nimport * as varint from '../varint.js';\n/**\n * Creates a multihash digest.\n */\nexport function create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = varint.encodingLength(code);\n const digestOffset = sizeOffset + varint.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n varint.encodeTo(code, bytes, 0);\n varint.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode(multihash) {\n const bytes = coerce(multihash);\n const [code, sizeOffset] = varint.decode(bytes);\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nexport function equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n//# sourceMappingURL=digest.js.map","import { base32 } from './bases/base32.js';\nimport { base58btc } from './bases/base58.js';\nimport { coerce } from './bytes.js';\nimport * as Digest from './hashes/digest.js';\nimport * as varint from './varint.js';\n// This way TS will also expose all the types from module\nexport * from './link/interface.js';\nexport function format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? base32.encoder));\n }\n}\nexport function toJSON(link) {\n return {\n '/': format(link)\n };\n}\nexport function fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nexport class CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = Digest.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = Digest.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new Digest.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = varint.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc;\n return [\n base58btc.prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ];\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc;\n return [base58btc.prefix, decoder.decode(source)];\n }\n case base32.prefix: {\n const decoder = base ?? base32;\n return [base32.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = varint.encodingLength(version);\n const hashOffset = codeOffset + varint.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n varint.encodeTo(version, bytes, 0);\n varint.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map","const textDecoder = new TextDecoder()\n\n/**\n * @typedef {import('./interface.js').RawPBLink} RawPBLink\n */\n\n/**\n * @typedef {import('./interface.js').RawPBNode} RawPBNode\n */\n\n/**\n * @param {Uint8Array} bytes\n * @param {number} offset\n * @returns {[number, number]}\n */\nfunction decodeVarint (bytes, offset) {\n let v = 0\n\n for (let shift = 0; ; shift += 7) {\n /* c8 ignore next 3 */\n if (shift >= 64) {\n throw new Error('protobuf: varint overflow')\n }\n /* c8 ignore next 3 */\n if (offset >= bytes.length) {\n throw new Error('protobuf: unexpected end of data')\n }\n\n const b = bytes[offset++]\n v += shift < 28 ? (b & 0x7f) << shift : (b & 0x7f) * (2 ** shift)\n if (b < 0x80) {\n break\n }\n }\n return [v, offset]\n}\n\n/**\n * @param {Uint8Array} bytes\n * @param {number} offset\n * @returns {[Uint8Array, number]}\n */\nfunction decodeBytes (bytes, offset) {\n let byteLen\n ;[byteLen, offset] = decodeVarint(bytes, offset)\n const postOffset = offset + byteLen\n\n /* c8 ignore next 3 */\n if (byteLen < 0 || postOffset < 0) {\n throw new Error('protobuf: invalid length')\n }\n /* c8 ignore next 3 */\n if (postOffset > bytes.length) {\n throw new Error('protobuf: unexpected end of data')\n }\n\n return [bytes.subarray(offset, postOffset), postOffset]\n}\n\n/**\n * @param {Uint8Array} bytes\n * @param {number} index\n * @returns {[number, number, number]}\n */\nfunction decodeKey (bytes, index) {\n let wire\n ;[wire, index] = decodeVarint(bytes, index)\n // [wireType, fieldNum, newIndex]\n return [wire & 0x7, wire >> 3, index]\n}\n\n/**\n * @param {Uint8Array} bytes\n * @returns {RawPBLink}\n */\nfunction decodeLink (bytes) {\n /** @type {RawPBLink} */\n const link = {}\n const l = bytes.length\n let index = 0\n\n while (index < l) {\n let wireType, fieldNum\n ;[wireType, fieldNum, index] = decodeKey(bytes, index)\n\n if (fieldNum === 1) {\n if (link.Hash) {\n throw new Error('protobuf: (PBLink) duplicate Hash section')\n }\n if (wireType !== 2) {\n throw new Error(`protobuf: (PBLink) wrong wireType (${wireType}) for Hash`)\n }\n if (link.Name !== undefined) {\n throw new Error('protobuf: (PBLink) invalid order, found Name before Hash')\n }\n if (link.Tsize !== undefined) {\n throw new Error('protobuf: (PBLink) invalid order, found Tsize before Hash')\n }\n\n [link.Hash, index] = decodeBytes(bytes, index)\n } else if (fieldNum === 2) {\n if (link.Name !== undefined) {\n throw new Error('protobuf: (PBLink) duplicate Name section')\n }\n if (wireType !== 2) {\n throw new Error(`protobuf: (PBLink) wrong wireType (${wireType}) for Name`)\n }\n if (link.Tsize !== undefined) {\n throw new Error('protobuf: (PBLink) invalid order, found Tsize before Name')\n }\n\n let byts\n ;[byts, index] = decodeBytes(bytes, index)\n link.Name = textDecoder.decode(byts)\n } else if (fieldNum === 3) {\n if (link.Tsize !== undefined) {\n throw new Error('protobuf: (PBLink) duplicate Tsize section')\n }\n if (wireType !== 0) {\n throw new Error(`protobuf: (PBLink) wrong wireType (${wireType}) for Tsize`)\n }\n\n [link.Tsize, index] = decodeVarint(bytes, index)\n } else {\n throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${fieldNum}`)\n }\n }\n\n /* c8 ignore next 3 */\n if (index > l) {\n throw new Error('protobuf: (PBLink) unexpected end of data')\n }\n\n return link\n}\n\n/**\n * @param {Uint8Array} bytes\n * @returns {RawPBNode}\n */\nexport function decodeNode (bytes) {\n const l = bytes.length\n let index = 0\n /** @type {RawPBLink[]|void} */\n let links = undefined // eslint-disable-line no-undef-init\n let linksBeforeData = false\n /** @type {Uint8Array|void} */\n let data = undefined // eslint-disable-line no-undef-init\n\n while (index < l) {\n let wireType, fieldNum\n ;[wireType, fieldNum, index] = decodeKey(bytes, index)\n\n if (wireType !== 2) {\n throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${wireType}`)\n }\n\n if (fieldNum === 1) {\n if (data) {\n throw new Error('protobuf: (PBNode) duplicate Data section')\n }\n\n [data, index] = decodeBytes(bytes, index)\n if (links) {\n linksBeforeData = true\n }\n } else if (fieldNum === 2) {\n if (linksBeforeData) { // interleaved Links/Data/Links\n throw new Error('protobuf: (PBNode) duplicate Links section')\n } else if (!links) {\n links = []\n }\n let byts\n ;[byts, index] = decodeBytes(bytes, index)\n links.push(decodeLink(byts))\n } else {\n throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${fieldNum}`)\n }\n }\n\n /* c8 ignore next 3 */\n if (index > l) {\n throw new Error('protobuf: (PBNode) unexpected end of data')\n }\n\n /** @type {RawPBNode} */\n const node = {}\n if (data) {\n node.Data = data\n }\n node.Links = links || []\n return node\n}\n","const textEncoder = new TextEncoder()\nconst maxInt32 = 2 ** 32\nconst maxUInt32 = 2 ** 31\n\n/**\n * @typedef {import('./interface.js').RawPBLink} RawPBLink\n */\n\n/**\n * @typedef {import('./interface.js').RawPBNode} RawPBNode\n */\n\n// the encoders work backward from the end of the bytes array\n\n/**\n * encodeLink() is passed a slice of the parent byte array that ends where this\n * link needs to end, so it packs to the right-most part of the passed `bytes`\n *\n * @param {RawPBLink} link\n * @param {Uint8Array} bytes\n * @returns {number}\n */\nfunction encodeLink (link, bytes) {\n let i = bytes.length\n\n if (typeof link.Tsize === 'number') {\n if (link.Tsize < 0) {\n throw new Error('Tsize cannot be negative')\n }\n if (!Number.isSafeInteger(link.Tsize)) {\n throw new Error('Tsize too large for encoding')\n }\n i = encodeVarint(bytes, i, link.Tsize) - 1\n bytes[i] = 0x18\n }\n\n if (typeof link.Name === 'string') {\n const nameBytes = textEncoder.encode(link.Name)\n i -= nameBytes.length\n bytes.set(nameBytes, i)\n i = encodeVarint(bytes, i, nameBytes.length) - 1\n bytes[i] = 0x12\n }\n\n if (link.Hash) {\n i -= link.Hash.length\n bytes.set(link.Hash, i)\n i = encodeVarint(bytes, i, link.Hash.length) - 1\n bytes[i] = 0xa\n }\n\n return bytes.length - i\n}\n\n/**\n * Encodes a PBNode into a new byte array of precisely the correct size\n *\n * @param {RawPBNode} node\n * @returns {Uint8Array}\n */\nexport function encodeNode (node) {\n const size = sizeNode(node)\n const bytes = new Uint8Array(size)\n let i = size\n\n if (node.Data) {\n i -= node.Data.length\n bytes.set(node.Data, i)\n i = encodeVarint(bytes, i, node.Data.length) - 1\n bytes[i] = 0xa\n }\n\n if (node.Links) {\n for (let index = node.Links.length - 1; index >= 0; index--) {\n const size = encodeLink(node.Links[index], bytes.subarray(0, i))\n i -= size\n i = encodeVarint(bytes, i, size) - 1\n bytes[i] = 0x12\n }\n }\n\n return bytes\n}\n\n/**\n * work out exactly how many bytes this link takes up\n *\n * @param {RawPBLink} link\n * @returns\n */\nfunction sizeLink (link) {\n let n = 0\n\n if (link.Hash) {\n const l = link.Hash.length\n n += 1 + l + sov(l)\n }\n\n if (typeof link.Name === 'string') {\n const l = textEncoder.encode(link.Name).length\n n += 1 + l + sov(l)\n }\n\n if (typeof link.Tsize === 'number') {\n n += 1 + sov(link.Tsize)\n }\n\n return n\n}\n\n/**\n * Work out exactly how many bytes this node takes up\n *\n * @param {RawPBNode} node\n * @returns {number}\n */\nfunction sizeNode (node) {\n let n = 0\n\n if (node.Data) {\n const l = node.Data.length\n n += 1 + l + sov(l)\n }\n\n if (node.Links) {\n for (const link of node.Links) {\n const l = sizeLink(link)\n n += 1 + l + sov(l)\n }\n }\n\n return n\n}\n\n/**\n * @param {Uint8Array} bytes\n * @param {number} offset\n * @param {number} v\n * @returns {number}\n */\nfunction encodeVarint (bytes, offset, v) {\n offset -= sov(v)\n const base = offset\n\n while (v >= maxUInt32) {\n bytes[offset++] = (v & 0x7f) | 0x80\n v /= 128\n }\n\n while (v >= 128) {\n bytes[offset++] = (v & 0x7f) | 0x80\n v >>>= 7\n }\n\n bytes[offset] = v\n\n return base\n}\n\n/**\n * size of varint\n *\n * @param {number} x\n * @returns {number}\n */\nfunction sov (x) {\n if (x % 2 === 0) {\n x++\n }\n return Math.floor((len64(x) + 6) / 7)\n}\n\n/**\n * golang math/bits, how many bits does it take to represent this integer?\n *\n * @param {number} x\n * @returns {number}\n */\nfunction len64 (x) {\n let n = 0\n if (x >= maxInt32) {\n x = Math.floor(x / maxInt32)\n n = 32\n }\n if (x >= (1 << 16)) {\n x >>>= 16\n n += 16\n }\n if (x >= (1 << 8)) {\n x >>>= 8\n n += 8\n }\n return n + len8tab[x]\n}\n\n// golang math/bits\nconst len8tab = [\n 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,\n 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,\n 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,\n 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,\n 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,\n 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,\n 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,\n 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8\n]\n","import { CID } from 'multiformats/cid'\n\n/**\n * @typedef {import('./interface.js').PBLink} PBLink\n * @typedef {import('./interface.js').PBNode} PBNode\n */\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ByteView} ByteView\n */\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ArrayBufferView} ArrayBufferView\n */\n\nconst pbNodeProperties = ['Data', 'Links']\nconst pbLinkProperties = ['Hash', 'Name', 'Tsize']\n\nconst textEncoder = new TextEncoder()\n\n/**\n * @param {PBLink} a\n * @param {PBLink} b\n * @returns {number}\n */\nfunction linkComparator (a, b) {\n if (a === b) {\n return 0\n }\n\n const abuf = a.Name ? textEncoder.encode(a.Name) : []\n const bbuf = b.Name ? textEncoder.encode(b.Name) : []\n\n let x = abuf.length\n let y = bbuf.length\n\n for (let i = 0, len = Math.min(x, y); i < len; ++i) {\n if (abuf[i] !== bbuf[i]) {\n x = abuf[i]\n y = bbuf[i]\n break\n }\n }\n\n return x < y ? -1 : y < x ? 1 : 0\n}\n\n/**\n * @param {any} node\n * @param {string[]} properties\n * @returns {boolean}\n */\nfunction hasOnlyProperties (node, properties) {\n return !Object.keys(node).some((p) => !properties.includes(p))\n}\n\n/**\n * Converts a CID, or a PBLink-like object to a PBLink\n *\n * @param {any} link\n * @returns {PBLink}\n */\nfunction asLink (link) {\n if (typeof link.asCID === 'object') {\n const Hash = CID.asCID(link)\n if (!Hash) {\n throw new TypeError('Invalid DAG-PB form')\n }\n return { Hash }\n }\n\n if (typeof link !== 'object' || Array.isArray(link)) {\n throw new TypeError('Invalid DAG-PB form')\n }\n\n const pbl = {}\n\n if (link.Hash) {\n let cid = CID.asCID(link.Hash)\n try {\n if (!cid) {\n if (typeof link.Hash === 'string') {\n cid = CID.parse(link.Hash)\n } else if (link.Hash instanceof Uint8Array) {\n cid = CID.decode(link.Hash)\n }\n }\n } catch (/** @type {any} */ e) {\n throw new TypeError(`Invalid DAG-PB form: ${e.message}`)\n }\n\n if (cid) {\n pbl.Hash = cid\n }\n }\n\n if (!pbl.Hash) {\n throw new TypeError('Invalid DAG-PB form')\n }\n\n if (typeof link.Name === 'string') {\n pbl.Name = link.Name\n }\n\n if (typeof link.Tsize === 'number') {\n pbl.Tsize = link.Tsize\n }\n\n return pbl\n}\n\n/**\n * @param {any} node\n * @returns {PBNode}\n */\nexport function prepare (node) {\n if (node instanceof Uint8Array || typeof node === 'string') {\n node = { Data: node }\n }\n\n if (typeof node !== 'object' || Array.isArray(node)) {\n throw new TypeError('Invalid DAG-PB form')\n }\n\n /** @type {PBNode} */\n const pbn = {}\n\n if (node.Data !== undefined) {\n if (typeof node.Data === 'string') {\n pbn.Data = textEncoder.encode(node.Data)\n } else if (node.Data instanceof Uint8Array) {\n pbn.Data = node.Data\n } else {\n throw new TypeError('Invalid DAG-PB form')\n }\n }\n\n if (node.Links !== undefined) {\n if (Array.isArray(node.Links)) {\n pbn.Links = node.Links.map(asLink)\n pbn.Links.sort(linkComparator)\n } else {\n throw new TypeError('Invalid DAG-PB form')\n }\n } else {\n pbn.Links = []\n }\n\n return pbn\n}\n\n/**\n * @param {PBNode} node\n */\nexport function validate (node) {\n /*\n type PBLink struct {\n Hash optional Link\n Name optional String\n Tsize optional Int\n }\n\n type PBNode struct {\n Links [PBLink]\n Data optional Bytes\n }\n */\n // @ts-ignore private property for TS\n if (!node || typeof node !== 'object' || Array.isArray(node) || node instanceof Uint8Array || (node['/'] && node['/'] === node.bytes)) {\n throw new TypeError('Invalid DAG-PB form')\n }\n\n if (!hasOnlyProperties(node, pbNodeProperties)) {\n throw new TypeError('Invalid DAG-PB form (extraneous properties)')\n }\n\n if (node.Data !== undefined && !(node.Data instanceof Uint8Array)) {\n throw new TypeError('Invalid DAG-PB form (Data must be bytes)')\n }\n\n if (!Array.isArray(node.Links)) {\n throw new TypeError('Invalid DAG-PB form (Links must be a list)')\n }\n\n for (let i = 0; i < node.Links.length; i++) {\n const link = node.Links[i]\n // @ts-ignore private property for TS\n if (!link || typeof link !== 'object' || Array.isArray(link) || link instanceof Uint8Array || (link['/'] && link['/'] === link.bytes)) {\n throw new TypeError('Invalid DAG-PB form (bad link)')\n }\n\n if (!hasOnlyProperties(link, pbLinkProperties)) {\n throw new TypeError('Invalid DAG-PB form (extraneous properties on link)')\n }\n\n if (link.Hash === undefined) {\n throw new TypeError('Invalid DAG-PB form (link must have a Hash)')\n }\n\n // @ts-ignore private property for TS\n if (link.Hash == null || !link.Hash['/'] || link.Hash['/'] !== link.Hash.bytes) {\n throw new TypeError('Invalid DAG-PB form (link Hash must be a CID)')\n }\n\n if (link.Name !== undefined && typeof link.Name !== 'string') {\n throw new TypeError('Invalid DAG-PB form (link Name must be a string)')\n }\n\n if (link.Tsize !== undefined) {\n if (typeof link.Tsize !== 'number' || link.Tsize % 1 !== 0) {\n throw new TypeError('Invalid DAG-PB form (link Tsize must be an integer)')\n }\n if (link.Tsize < 0) {\n throw new TypeError('Invalid DAG-PB form (link Tsize cannot be negative)')\n }\n }\n\n if (i > 0 && linkComparator(link, node.Links[i - 1]) === -1) {\n throw new TypeError('Invalid DAG-PB form (links must be sorted by Name bytes)')\n }\n }\n}\n\n/**\n * @param {Uint8Array} data\n * @param {PBLink[]} [links=[]]\n * @returns {PBNode}\n */\nexport function createNode (data, links = []) {\n return prepare({ Data: data, Links: links })\n}\n\n/**\n * @param {string} name\n * @param {number} size\n * @param {CID} cid\n * @returns {PBLink}\n */\nexport function createLink (name, size, cid) {\n return asLink({ Hash: cid, Name: name, Tsize: size })\n}\n\n/**\n * @template T\n * @param {ByteView | ArrayBufferView} buf\n * @returns {ByteView}\n */\nexport function toByteView (buf) {\n if (buf instanceof ArrayBuffer) {\n return new Uint8Array(buf, 0, buf.byteLength)\n }\n\n return buf\n}\n","import { CID } from 'multiformats/cid'\nimport { decodeNode } from './pb-decode.js'\nimport { encodeNode } from './pb-encode.js'\nimport { prepare, validate, createNode, createLink, toByteView } from './util.js'\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ByteView} ByteView\n */\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ArrayBufferView} ArrayBufferView\n */\n\n/**\n * @typedef {import('./interface.js').PBLink} PBLink\n * @typedef {import('./interface.js').PBNode} PBNode\n */\n\nexport const name = 'dag-pb'\nexport const code = 0x70\n\n/**\n * @param {PBNode} node\n * @returns {ByteView}\n */\nexport function encode (node) {\n validate(node)\n\n const pbn = {}\n if (node.Links) {\n pbn.Links = node.Links.map((l) => {\n const link = {}\n if (l.Hash) {\n link.Hash = l.Hash.bytes // cid -> bytes\n }\n if (l.Name !== undefined) {\n link.Name = l.Name\n }\n if (l.Tsize !== undefined) {\n link.Tsize = l.Tsize\n }\n return link\n })\n }\n if (node.Data) {\n pbn.Data = node.Data\n }\n\n return encodeNode(pbn)\n}\n\n/**\n * @param {ByteView | ArrayBufferView} bytes\n * @returns {PBNode}\n */\nexport function decode (bytes) {\n const buf = toByteView(bytes)\n const pbn = decodeNode(buf)\n\n const node = {}\n\n if (pbn.Data) {\n node.Data = pbn.Data\n }\n\n if (pbn.Links) {\n node.Links = pbn.Links.map((l) => {\n const link = {}\n try {\n link.Hash = CID.decode(l.Hash)\n } catch (e) {}\n if (!link.Hash) {\n throw new Error('Invalid Hash field found in link, expected CID')\n }\n if (l.Name !== undefined) {\n link.Name = l.Name\n }\n if (l.Tsize !== undefined) {\n link.Tsize = l.Tsize\n }\n return link\n })\n }\n\n return node\n}\n\nexport { prepare, validate, createNode, createLink }\n","\"use strict\";\r\nmodule.exports = asPromise;\r\n\r\n/**\r\n * Callback as used by {@link util.asPromise}.\r\n * @typedef asPromiseCallback\r\n * @type {function}\r\n * @param {Error|null} error Error, if any\r\n * @param {...*} params Additional arguments\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Returns a promise from a node-style callback function.\r\n * @memberof util\r\n * @param {asPromiseCallback} fn Function to call\r\n * @param {*} ctx Function context\r\n * @param {...*} params Function arguments\r\n * @returns {Promise<*>} Promisified function\r\n */\r\nfunction asPromise(fn, ctx/*, varargs */) {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0,\r\n index = 2,\r\n pending = true;\r\n while (index < arguments.length)\r\n params[offset++] = arguments[index++];\r\n return new Promise(function executor(resolve, reject) {\r\n params[offset] = function callback(err/*, varargs */) {\r\n if (pending) {\r\n pending = false;\r\n if (err)\r\n reject(err);\r\n else {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0;\r\n while (offset < params.length)\r\n params[offset++] = arguments[offset];\r\n resolve.apply(null, params);\r\n }\r\n }\r\n };\r\n try {\r\n fn.apply(ctx || null, params);\r\n } catch (err) {\r\n if (pending) {\r\n pending = false;\r\n reject(err);\r\n }\r\n }\r\n });\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal base64 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar base64 = exports;\r\n\r\n/**\r\n * Calculates the byte length of a base64 encoded string.\r\n * @param {string} string Base64 encoded string\r\n * @returns {number} Byte length\r\n */\r\nbase64.length = function length(string) {\r\n var p = string.length;\r\n if (!p)\r\n return 0;\r\n var n = 0;\r\n while (--p % 4 > 1 && string.charAt(p) === \"=\")\r\n ++n;\r\n return Math.ceil(string.length * 3) / 4 - n;\r\n};\r\n\r\n// Base64 encoding table\r\nvar b64 = new Array(64);\r\n\r\n// Base64 decoding table\r\nvar s64 = new Array(123);\r\n\r\n// 65..90, 97..122, 48..57, 43, 47\r\nfor (var i = 0; i < 64;)\r\n s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;\r\n\r\n/**\r\n * Encodes a buffer to a base64 encoded string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} Base64 encoded string\r\n */\r\nbase64.encode = function encode(buffer, start, end) {\r\n var parts = null,\r\n chunk = [];\r\n var i = 0, // output index\r\n j = 0, // goto index\r\n t; // temporary\r\n while (start < end) {\r\n var b = buffer[start++];\r\n switch (j) {\r\n case 0:\r\n chunk[i++] = b64[b >> 2];\r\n t = (b & 3) << 4;\r\n j = 1;\r\n break;\r\n case 1:\r\n chunk[i++] = b64[t | b >> 4];\r\n t = (b & 15) << 2;\r\n j = 2;\r\n break;\r\n case 2:\r\n chunk[i++] = b64[t | b >> 6];\r\n chunk[i++] = b64[b & 63];\r\n j = 0;\r\n break;\r\n }\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (j) {\r\n chunk[i++] = b64[t];\r\n chunk[i++] = 61;\r\n if (j === 1)\r\n chunk[i++] = 61;\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\nvar invalidEncoding = \"invalid encoding\";\r\n\r\n/**\r\n * Decodes a base64 encoded string to a buffer.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Number of bytes written\r\n * @throws {Error} If encoding is invalid\r\n */\r\nbase64.decode = function decode(string, buffer, offset) {\r\n var start = offset;\r\n var j = 0, // goto index\r\n t; // temporary\r\n for (var i = 0; i < string.length;) {\r\n var c = string.charCodeAt(i++);\r\n if (c === 61 && j > 1)\r\n break;\r\n if ((c = s64[c]) === undefined)\r\n throw Error(invalidEncoding);\r\n switch (j) {\r\n case 0:\r\n t = c;\r\n j = 1;\r\n break;\r\n case 1:\r\n buffer[offset++] = t << 2 | (c & 48) >> 4;\r\n t = c;\r\n j = 2;\r\n break;\r\n case 2:\r\n buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;\r\n t = c;\r\n j = 3;\r\n break;\r\n case 3:\r\n buffer[offset++] = (t & 3) << 6 | c;\r\n j = 0;\r\n break;\r\n }\r\n }\r\n if (j === 1)\r\n throw Error(invalidEncoding);\r\n return offset - start;\r\n};\r\n\r\n/**\r\n * Tests if the specified string appears to be base64 encoded.\r\n * @param {string} string String to test\r\n * @returns {boolean} `true` if probably base64 encoded, otherwise false\r\n */\r\nbase64.test = function test(string) {\r\n return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);\r\n};\r\n","\"use strict\";\r\nmodule.exports = EventEmitter;\r\n\r\n/**\r\n * Constructs a new event emitter instance.\r\n * @classdesc A minimal event emitter.\r\n * @memberof util\r\n * @constructor\r\n */\r\nfunction EventEmitter() {\r\n\r\n /**\r\n * Registered listeners.\r\n * @type {Object.}\r\n * @private\r\n */\r\n this._listeners = {};\r\n}\r\n\r\n/**\r\n * Registers an event listener.\r\n * @param {string} evt Event name\r\n * @param {function} fn Listener\r\n * @param {*} [ctx] Listener context\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.on = function on(evt, fn, ctx) {\r\n (this._listeners[evt] || (this._listeners[evt] = [])).push({\r\n fn : fn,\r\n ctx : ctx || this\r\n });\r\n return this;\r\n};\r\n\r\n/**\r\n * Removes an event listener or any matching listeners if arguments are omitted.\r\n * @param {string} [evt] Event name. Removes all listeners if omitted.\r\n * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.off = function off(evt, fn) {\r\n if (evt === undefined)\r\n this._listeners = {};\r\n else {\r\n if (fn === undefined)\r\n this._listeners[evt] = [];\r\n else {\r\n var listeners = this._listeners[evt];\r\n for (var i = 0; i < listeners.length;)\r\n if (listeners[i].fn === fn)\r\n listeners.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Emits an event by calling its listeners with the specified arguments.\r\n * @param {string} evt Event name\r\n * @param {...*} args Arguments\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.emit = function emit(evt) {\r\n var listeners = this._listeners[evt];\r\n if (listeners) {\r\n var args = [],\r\n i = 1;\r\n for (; i < arguments.length;)\r\n args.push(arguments[i++]);\r\n for (i = 0; i < listeners.length;)\r\n listeners[i].fn.apply(listeners[i++].ctx, args);\r\n }\r\n return this;\r\n};\r\n","\"use strict\";\r\n\r\nmodule.exports = factory(factory);\r\n\r\n/**\r\n * Reads / writes floats / doubles from / to buffers.\r\n * @name util.float\r\n * @namespace\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using little endian byte order.\r\n * @name util.float.writeFloatLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using big endian byte order.\r\n * @name util.float.writeFloatBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using little endian byte order.\r\n * @name util.float.readFloatLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using big endian byte order.\r\n * @name util.float.readFloatBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using little endian byte order.\r\n * @name util.float.writeDoubleLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using big endian byte order.\r\n * @name util.float.writeDoubleBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using little endian byte order.\r\n * @name util.float.readDoubleLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using big endian byte order.\r\n * @name util.float.readDoubleBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n// Factory function for the purpose of node-based testing in modified global environments\r\nfunction factory(exports) {\r\n\r\n // float: typed array\r\n if (typeof Float32Array !== \"undefined\") (function() {\r\n\r\n var f32 = new Float32Array([ -0 ]),\r\n f8b = new Uint8Array(f32.buffer),\r\n le = f8b[3] === 128;\r\n\r\n function writeFloat_f32_cpy(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n }\r\n\r\n function writeFloat_f32_rev(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[3];\r\n buf[pos + 1] = f8b[2];\r\n buf[pos + 2] = f8b[1];\r\n buf[pos + 3] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;\r\n\r\n function readFloat_f32_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n function readFloat_f32_rev(buf, pos) {\r\n f8b[3] = buf[pos ];\r\n f8b[2] = buf[pos + 1];\r\n f8b[1] = buf[pos + 2];\r\n f8b[0] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;\r\n\r\n // float: ieee754\r\n })(); else (function() {\r\n\r\n function writeFloat_ieee754(writeUint, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0)\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);\r\n else if (isNaN(val))\r\n writeUint(2143289344, buf, pos);\r\n else if (val > 3.4028234663852886e+38) // +-Infinity\r\n writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);\r\n else if (val < 1.1754943508222875e-38) // denormal\r\n writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);\r\n else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2),\r\n mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;\r\n writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);\r\n }\r\n }\r\n\r\n exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);\r\n exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);\r\n\r\n function readFloat_ieee754(readUint, buf, pos) {\r\n var uint = readUint(buf, pos),\r\n sign = (uint >> 31) * 2 + 1,\r\n exponent = uint >>> 23 & 255,\r\n mantissa = uint & 8388607;\r\n return exponent === 255\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 1.401298464324817e-45 * mantissa\r\n : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);\r\n }\r\n\r\n exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);\r\n exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);\r\n\r\n })();\r\n\r\n // double: typed array\r\n if (typeof Float64Array !== \"undefined\") (function() {\r\n\r\n var f64 = new Float64Array([-0]),\r\n f8b = new Uint8Array(f64.buffer),\r\n le = f8b[7] === 128;\r\n\r\n function writeDouble_f64_cpy(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n buf[pos + 4] = f8b[4];\r\n buf[pos + 5] = f8b[5];\r\n buf[pos + 6] = f8b[6];\r\n buf[pos + 7] = f8b[7];\r\n }\r\n\r\n function writeDouble_f64_rev(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[7];\r\n buf[pos + 1] = f8b[6];\r\n buf[pos + 2] = f8b[5];\r\n buf[pos + 3] = f8b[4];\r\n buf[pos + 4] = f8b[3];\r\n buf[pos + 5] = f8b[2];\r\n buf[pos + 6] = f8b[1];\r\n buf[pos + 7] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;\r\n\r\n function readDouble_f64_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n f8b[4] = buf[pos + 4];\r\n f8b[5] = buf[pos + 5];\r\n f8b[6] = buf[pos + 6];\r\n f8b[7] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n function readDouble_f64_rev(buf, pos) {\r\n f8b[7] = buf[pos ];\r\n f8b[6] = buf[pos + 1];\r\n f8b[5] = buf[pos + 2];\r\n f8b[4] = buf[pos + 3];\r\n f8b[3] = buf[pos + 4];\r\n f8b[2] = buf[pos + 5];\r\n f8b[1] = buf[pos + 6];\r\n f8b[0] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;\r\n\r\n // double: ieee754\r\n })(); else (function() {\r\n\r\n function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);\r\n } else if (isNaN(val)) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(2146959360, buf, pos + off1);\r\n } else if (val > 1.7976931348623157e+308) { // +-Infinity\r\n writeUint(0, buf, pos + off0);\r\n writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);\r\n } else {\r\n var mantissa;\r\n if (val < 2.2250738585072014e-308) { // denormal\r\n mantissa = val / 5e-324;\r\n writeUint(mantissa >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);\r\n } else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2);\r\n if (exponent === 1024)\r\n exponent = 1023;\r\n mantissa = val * Math.pow(2, -exponent);\r\n writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);\r\n }\r\n }\r\n }\r\n\r\n exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);\r\n exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);\r\n\r\n function readDouble_ieee754(readUint, off0, off1, buf, pos) {\r\n var lo = readUint(buf, pos + off0),\r\n hi = readUint(buf, pos + off1);\r\n var sign = (hi >> 31) * 2 + 1,\r\n exponent = hi >>> 20 & 2047,\r\n mantissa = 4294967296 * (hi & 1048575) + lo;\r\n return exponent === 2047\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 5e-324 * mantissa\r\n : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);\r\n }\r\n\r\n exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);\r\n exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);\r\n\r\n })();\r\n\r\n return exports;\r\n}\r\n\r\n// uint helpers\r\n\r\nfunction writeUintLE(val, buf, pos) {\r\n buf[pos ] = val & 255;\r\n buf[pos + 1] = val >>> 8 & 255;\r\n buf[pos + 2] = val >>> 16 & 255;\r\n buf[pos + 3] = val >>> 24;\r\n}\r\n\r\nfunction writeUintBE(val, buf, pos) {\r\n buf[pos ] = val >>> 24;\r\n buf[pos + 1] = val >>> 16 & 255;\r\n buf[pos + 2] = val >>> 8 & 255;\r\n buf[pos + 3] = val & 255;\r\n}\r\n\r\nfunction readUintLE(buf, pos) {\r\n return (buf[pos ]\r\n | buf[pos + 1] << 8\r\n | buf[pos + 2] << 16\r\n | buf[pos + 3] << 24) >>> 0;\r\n}\r\n\r\nfunction readUintBE(buf, pos) {\r\n return (buf[pos ] << 24\r\n | buf[pos + 1] << 16\r\n | buf[pos + 2] << 8\r\n | buf[pos + 3]) >>> 0;\r\n}\r\n","\"use strict\";\r\nmodule.exports = inquire;\r\n\r\n/**\r\n * Requires a module only if available.\r\n * @memberof util\r\n * @param {string} moduleName Module to require\r\n * @returns {?Object} Required module if available and not empty, otherwise `null`\r\n */\r\nfunction inquire(moduleName) {\r\n try {\r\n var mod = eval(\"quire\".replace(/^/,\"re\"))(moduleName); // eslint-disable-line no-eval\r\n if (mod && (mod.length || Object.keys(mod).length))\r\n return mod;\r\n } catch (e) {} // eslint-disable-line no-empty\r\n return null;\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal UTF8 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar utf8 = exports;\r\n\r\n/**\r\n * Calculates the UTF8 byte length of a string.\r\n * @param {string} string String\r\n * @returns {number} Byte length\r\n */\r\nutf8.length = function utf8_length(string) {\r\n var len = 0,\r\n c = 0;\r\n for (var i = 0; i < string.length; ++i) {\r\n c = string.charCodeAt(i);\r\n if (c < 128)\r\n len += 1;\r\n else if (c < 2048)\r\n len += 2;\r\n else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\r\n ++i;\r\n len += 4;\r\n } else\r\n len += 3;\r\n }\r\n return len;\r\n};\r\n\r\n/**\r\n * Reads UTF8 bytes as a string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} String read\r\n */\r\nutf8.read = function utf8_read(buffer, start, end) {\r\n var len = end - start;\r\n if (len < 1)\r\n return \"\";\r\n var parts = null,\r\n chunk = [],\r\n i = 0, // char offset\r\n t; // temporary\r\n while (start < end) {\r\n t = buffer[start++];\r\n if (t < 128)\r\n chunk[i++] = t;\r\n else if (t > 191 && t < 224)\r\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;\r\n else if (t > 239 && t < 365) {\r\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;\r\n chunk[i++] = 0xD800 + (t >> 10);\r\n chunk[i++] = 0xDC00 + (t & 1023);\r\n } else\r\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\n/**\r\n * Writes a string as UTF8 bytes.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Bytes written\r\n */\r\nutf8.write = function utf8_write(string, buffer, offset) {\r\n var start = offset,\r\n c1, // character 1\r\n c2; // character 2\r\n for (var i = 0; i < string.length; ++i) {\r\n c1 = string.charCodeAt(i);\r\n if (c1 < 128) {\r\n buffer[offset++] = c1;\r\n } else if (c1 < 2048) {\r\n buffer[offset++] = c1 >> 6 | 192;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\r\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);\r\n ++i;\r\n buffer[offset++] = c1 >> 18 | 240;\r\n buffer[offset++] = c1 >> 12 & 63 | 128;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else {\r\n buffer[offset++] = c1 >> 12 | 224;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n }\r\n }\r\n return offset - start;\r\n};\r\n","\"use strict\";\r\nmodule.exports = pool;\r\n\r\n/**\r\n * An allocator as used by {@link util.pool}.\r\n * @typedef PoolAllocator\r\n * @type {function}\r\n * @param {number} size Buffer size\r\n * @returns {Uint8Array} Buffer\r\n */\r\n\r\n/**\r\n * A slicer as used by {@link util.pool}.\r\n * @typedef PoolSlicer\r\n * @type {function}\r\n * @param {number} start Start offset\r\n * @param {number} end End offset\r\n * @returns {Uint8Array} Buffer slice\r\n * @this {Uint8Array}\r\n */\r\n\r\n/**\r\n * A general purpose buffer pool.\r\n * @memberof util\r\n * @function\r\n * @param {PoolAllocator} alloc Allocator\r\n * @param {PoolSlicer} slice Slicer\r\n * @param {number} [size=8192] Slab size\r\n * @returns {PoolAllocator} Pooled allocator\r\n */\r\nfunction pool(alloc, slice, size) {\r\n var SIZE = size || 8192;\r\n var MAX = SIZE >>> 1;\r\n var slab = null;\r\n var offset = SIZE;\r\n return function pool_alloc(size) {\r\n if (size < 1 || size > MAX)\r\n return alloc(size);\r\n if (offset + size > SIZE) {\r\n slab = alloc(SIZE);\r\n offset = 0;\r\n }\r\n var buf = slice.call(slab, offset, offset += size);\r\n if (offset & 7) // align to 32 bit\r\n offset = (offset | 7) + 1;\r\n return buf;\r\n };\r\n}\r\n","\"use strict\";\nmodule.exports = LongBits;\n\nvar util = require(\"../util/minimal\");\n\n/**\n * Constructs new long bits.\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @constructor\n * @param {number} lo Low 32 bits, unsigned\n * @param {number} hi High 32 bits, unsigned\n */\nfunction LongBits(lo, hi) {\n\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits.\n * @type {number}\n */\n this.lo = lo >>> 0;\n\n /**\n * High bits.\n * @type {number}\n */\n this.hi = hi >>> 0;\n}\n\n/**\n * Zero bits.\n * @memberof util.LongBits\n * @type {util.LongBits}\n */\nvar zero = LongBits.zero = new LongBits(0, 0);\n\nzero.toNumber = function() { return 0; };\nzero.zzEncode = zero.zzDecode = function() { return this; };\nzero.length = function() { return 1; };\n\n/**\n * Zero hash.\n * @memberof util.LongBits\n * @type {string}\n */\nvar zeroHash = LongBits.zeroHash = \"\\0\\0\\0\\0\\0\\0\\0\\0\";\n\n/**\n * Constructs new long bits from the specified number.\n * @param {number} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.fromNumber = function fromNumber(value) {\n if (value === 0)\n return zero;\n var sign = value < 0;\n if (sign)\n value = -value;\n var lo = value >>> 0,\n hi = (value - lo) / 4294967296 >>> 0;\n if (sign) {\n hi = ~hi >>> 0;\n lo = ~lo >>> 0;\n if (++lo > 4294967295) {\n lo = 0;\n if (++hi > 4294967295)\n hi = 0;\n }\n }\n return new LongBits(lo, hi);\n};\n\n/**\n * Constructs new long bits from a number, long or string.\n * @param {Long|number|string} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.from = function from(value) {\n if (typeof value === \"number\")\n return LongBits.fromNumber(value);\n if (util.isString(value)) {\n /* istanbul ignore else */\n if (util.Long)\n value = util.Long.fromString(value);\n else\n return LongBits.fromNumber(parseInt(value, 10));\n }\n return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;\n};\n\n/**\n * Converts this long bits to a possibly unsafe JavaScript number.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {number} Possibly unsafe number\n */\nLongBits.prototype.toNumber = function toNumber(unsigned) {\n if (!unsigned && this.hi >>> 31) {\n var lo = ~this.lo + 1 >>> 0,\n hi = ~this.hi >>> 0;\n if (!lo)\n hi = hi + 1 >>> 0;\n return -(lo + hi * 4294967296);\n }\n return this.lo + this.hi * 4294967296;\n};\n\n/**\n * Converts this long bits to a long.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long} Long\n */\nLongBits.prototype.toLong = function toLong(unsigned) {\n return util.Long\n ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))\n /* istanbul ignore next */\n : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };\n};\n\nvar charCodeAt = String.prototype.charCodeAt;\n\n/**\n * Constructs new long bits from the specified 8 characters long hash.\n * @param {string} hash Hash\n * @returns {util.LongBits} Bits\n */\nLongBits.fromHash = function fromHash(hash) {\n if (hash === zeroHash)\n return zero;\n return new LongBits(\n ( charCodeAt.call(hash, 0)\n | charCodeAt.call(hash, 1) << 8\n | charCodeAt.call(hash, 2) << 16\n | charCodeAt.call(hash, 3) << 24) >>> 0\n ,\n ( charCodeAt.call(hash, 4)\n | charCodeAt.call(hash, 5) << 8\n | charCodeAt.call(hash, 6) << 16\n | charCodeAt.call(hash, 7) << 24) >>> 0\n );\n};\n\n/**\n * Converts this long bits to a 8 characters long hash.\n * @returns {string} Hash\n */\nLongBits.prototype.toHash = function toHash() {\n return String.fromCharCode(\n this.lo & 255,\n this.lo >>> 8 & 255,\n this.lo >>> 16 & 255,\n this.lo >>> 24 ,\n this.hi & 255,\n this.hi >>> 8 & 255,\n this.hi >>> 16 & 255,\n this.hi >>> 24\n );\n};\n\n/**\n * Zig-zag encodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzEncode = function zzEncode() {\n var mask = this.hi >> 31;\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;\n this.lo = ( this.lo << 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Zig-zag decodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzDecode = function zzDecode() {\n var mask = -(this.lo & 1);\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;\n this.hi = ( this.hi >>> 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Calculates the length of this longbits when encoded as a varint.\n * @returns {number} Length\n */\nLongBits.prototype.length = function length() {\n var part0 = this.lo,\n part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,\n part2 = this.hi >>> 24;\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10;\n};\n","\"use strict\";\nvar util = exports;\n\n// used to return a Promise where callback is omitted\nutil.asPromise = require(\"@protobufjs/aspromise\");\n\n// converts to / from base64 encoded strings\nutil.base64 = require(\"@protobufjs/base64\");\n\n// base class of rpc.Service\nutil.EventEmitter = require(\"@protobufjs/eventemitter\");\n\n// float handling accross browsers\nutil.float = require(\"@protobufjs/float\");\n\n// requires modules optionally and hides the call from bundlers\nutil.inquire = require(\"@protobufjs/inquire\");\n\n// converts to / from utf8 encoded strings\nutil.utf8 = require(\"@protobufjs/utf8\");\n\n// provides a node-like buffer pool in the browser\nutil.pool = require(\"@protobufjs/pool\");\n\n// utility to work with the low and high bits of a 64 bit value\nutil.LongBits = require(\"./longbits\");\n\n/**\n * Whether running within node or not.\n * @memberof util\n * @type {boolean}\n */\nutil.isNode = Boolean(typeof global !== \"undefined\"\n && global\n && global.process\n && global.process.versions\n && global.process.versions.node);\n\n/**\n * Global object reference.\n * @memberof util\n * @type {Object}\n */\nutil.global = util.isNode && global\n || typeof window !== \"undefined\" && window\n || typeof self !== \"undefined\" && self\n || this; // eslint-disable-line no-invalid-this\n\n/**\n * An immuable empty array.\n * @memberof util\n * @type {Array.<*>}\n * @const\n */\nutil.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes\n\n/**\n * An immutable empty object.\n * @type {Object}\n * @const\n */\nutil.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes\n\n/**\n * Tests if the specified value is an integer.\n * @function\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is an integer\n */\nutil.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {\n return typeof value === \"number\" && isFinite(value) && Math.floor(value) === value;\n};\n\n/**\n * Tests if the specified value is a string.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a string\n */\nutil.isString = function isString(value) {\n return typeof value === \"string\" || value instanceof String;\n};\n\n/**\n * Tests if the specified value is a non-null object.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a non-null object\n */\nutil.isObject = function isObject(value) {\n return value && typeof value === \"object\";\n};\n\n/**\n * Checks if a property on a message is considered to be present.\n * This is an alias of {@link util.isSet}.\n * @function\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isset =\n\n/**\n * Checks if a property on a message is considered to be present.\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isSet = function isSet(obj, prop) {\n var value = obj[prop];\n if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins\n return typeof value !== \"object\" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;\n return false;\n};\n\n/**\n * Any compatible Buffer instance.\n * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.\n * @interface Buffer\n * @extends Uint8Array\n */\n\n/**\n * Node's Buffer class if available.\n * @type {Constructor}\n */\nutil.Buffer = (function() {\n try {\n var Buffer = util.inquire(\"buffer\").Buffer;\n // refuse to use non-node buffers if not explicitly assigned (perf reasons):\n return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;\n } catch (e) {\n /* istanbul ignore next */\n return null;\n }\n})();\n\n// Internal alias of or polyfull for Buffer.from.\nutil._Buffer_from = null;\n\n// Internal alias of or polyfill for Buffer.allocUnsafe.\nutil._Buffer_allocUnsafe = null;\n\n/**\n * Creates a new buffer of whatever type supported by the environment.\n * @param {number|number[]} [sizeOrArray=0] Buffer size or number array\n * @returns {Uint8Array|Buffer} Buffer\n */\nutil.newBuffer = function newBuffer(sizeOrArray) {\n /* istanbul ignore next */\n return typeof sizeOrArray === \"number\"\n ? util.Buffer\n ? util._Buffer_allocUnsafe(sizeOrArray)\n : new util.Array(sizeOrArray)\n : util.Buffer\n ? util._Buffer_from(sizeOrArray)\n : typeof Uint8Array === \"undefined\"\n ? sizeOrArray\n : new Uint8Array(sizeOrArray);\n};\n\n/**\n * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.\n * @type {Constructor}\n */\nutil.Array = typeof Uint8Array !== \"undefined\" ? Uint8Array /* istanbul ignore next */ : Array;\n\n/**\n * Any compatible Long instance.\n * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.\n * @interface Long\n * @property {number} low Low bits\n * @property {number} high High bits\n * @property {boolean} unsigned Whether unsigned or not\n */\n\n/**\n * Long.js's Long class if available.\n * @type {Constructor}\n */\nutil.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long\n || /* istanbul ignore next */ util.global.Long\n || util.inquire(\"long\");\n\n/**\n * Regular expression used to verify 2 bit (`bool`) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key2Re = /^true|false|0|1$/;\n\n/**\n * Regular expression used to verify 32 bit (`int32` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key32Re = /^-?(?:0|[1-9][0-9]*)$/;\n\n/**\n * Regular expression used to verify 64 bit (`int64` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key64Re = /^(?:[\\\\x00-\\\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;\n\n/**\n * Converts a number or long to an 8 characters long hash string.\n * @param {Long|number} value Value to convert\n * @returns {string} Hash\n */\nutil.longToHash = function longToHash(value) {\n return value\n ? util.LongBits.from(value).toHash()\n : util.LongBits.zeroHash;\n};\n\n/**\n * Converts an 8 characters long hash string to a long or number.\n * @param {string} hash Hash\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long|number} Original value\n */\nutil.longFromHash = function longFromHash(hash, unsigned) {\n var bits = util.LongBits.fromHash(hash);\n if (util.Long)\n return util.Long.fromBits(bits.lo, bits.hi, unsigned);\n return bits.toNumber(Boolean(unsigned));\n};\n\n/**\n * Merges the properties of the source object into the destination object.\n * @memberof util\n * @param {Object.} dst Destination object\n * @param {Object.} src Source object\n * @param {boolean} [ifNotSet=false] Merges only if the key is not already set\n * @returns {Object.} Destination object\n */\nfunction merge(dst, src, ifNotSet) { // used by converters\n for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)\n if (dst[keys[i]] === undefined || !ifNotSet)\n dst[keys[i]] = src[keys[i]];\n return dst;\n}\n\nutil.merge = merge;\n\n/**\n * Converts the first character of a string to lower case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.lcFirst = function lcFirst(str) {\n return str.charAt(0).toLowerCase() + str.substring(1);\n};\n\n/**\n * Creates a custom error constructor.\n * @memberof util\n * @param {string} name Error name\n * @returns {Constructor} Custom error constructor\n */\nfunction newError(name) {\n\n function CustomError(message, properties) {\n\n if (!(this instanceof CustomError))\n return new CustomError(message, properties);\n\n // Error.call(this, message);\n // ^ just returns a new error instance because the ctor can be called as a function\n\n Object.defineProperty(this, \"message\", { get: function() { return message; } });\n\n /* istanbul ignore next */\n if (Error.captureStackTrace) // node\n Error.captureStackTrace(this, CustomError);\n else\n Object.defineProperty(this, \"stack\", { value: new Error().stack || \"\" });\n\n if (properties)\n merge(this, properties);\n }\n\n CustomError.prototype = Object.create(Error.prototype, {\n constructor: {\n value: CustomError,\n writable: true,\n enumerable: false,\n configurable: true,\n },\n name: {\n get: function get() { return name; },\n set: undefined,\n enumerable: false,\n // configurable: false would accurately preserve the behavior of\n // the original, but I'm guessing that was not intentional.\n // For an actual error subclass, this property would\n // be configurable.\n configurable: true,\n },\n toString: {\n value: function value() { return this.name + \": \" + this.message; },\n writable: true,\n enumerable: false,\n configurable: true,\n },\n });\n\n return CustomError;\n}\n\nutil.newError = newError;\n\n/**\n * Constructs a new protocol error.\n * @classdesc Error subclass indicating a protocol specifc error.\n * @memberof util\n * @extends Error\n * @template T extends Message\n * @constructor\n * @param {string} message Error message\n * @param {Object.} [properties] Additional properties\n * @example\n * try {\n * MyMessage.decode(someBuffer); // throws if required fields are missing\n * } catch (e) {\n * if (e instanceof ProtocolError && e.instance)\n * console.log(\"decoded so far: \" + JSON.stringify(e.instance));\n * }\n */\nutil.ProtocolError = newError(\"ProtocolError\");\n\n/**\n * So far decoded message instance.\n * @name util.ProtocolError#instance\n * @type {Message}\n */\n\n/**\n * A OneOf getter as returned by {@link util.oneOfGetter}.\n * @typedef OneOfGetter\n * @type {function}\n * @returns {string|undefined} Set field name, if any\n */\n\n/**\n * Builds a getter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfGetter} Unbound getter\n */\nutil.oneOfGetter = function getOneOf(fieldNames) {\n var fieldMap = {};\n for (var i = 0; i < fieldNames.length; ++i)\n fieldMap[fieldNames[i]] = 1;\n\n /**\n * @returns {string|undefined} Set field name, if any\n * @this Object\n * @ignore\n */\n return function() { // eslint-disable-line consistent-return\n for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)\n if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)\n return keys[i];\n };\n};\n\n/**\n * A OneOf setter as returned by {@link util.oneOfSetter}.\n * @typedef OneOfSetter\n * @type {function}\n * @param {string|undefined} value Field name\n * @returns {undefined}\n */\n\n/**\n * Builds a setter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfSetter} Unbound setter\n */\nutil.oneOfSetter = function setOneOf(fieldNames) {\n\n /**\n * @param {string} name Field name\n * @returns {undefined}\n * @this Object\n * @ignore\n */\n return function(name) {\n for (var i = 0; i < fieldNames.length; ++i)\n if (fieldNames[i] !== name)\n delete this[fieldNames[i]];\n };\n};\n\n/**\n * Default conversion options used for {@link Message#toJSON} implementations.\n *\n * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:\n *\n * - Longs become strings\n * - Enums become string keys\n * - Bytes become base64 encoded strings\n * - (Sub-)Messages become plain objects\n * - Maps become plain objects with all string keys\n * - Repeated fields become arrays\n * - NaN and Infinity for float and double fields become strings\n *\n * @type {IConversionOptions}\n * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json\n */\nutil.toJSONOptions = {\n longs: String,\n enums: String,\n bytes: String,\n json: true\n};\n\n// Sets up buffer utility according to the environment (called in index-minimal)\nutil._configure = function() {\n var Buffer = util.Buffer;\n /* istanbul ignore if */\n if (!Buffer) {\n util._Buffer_from = util._Buffer_allocUnsafe = null;\n return;\n }\n // because node 4.x buffers are incompatible & immutable\n // see: https://github.com/dcodeIO/protobuf.js/pull/665\n util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||\n /* istanbul ignore next */\n function Buffer_from(value, encoding) {\n return new Buffer(value, encoding);\n };\n util._Buffer_allocUnsafe = Buffer.allocUnsafe ||\n /* istanbul ignore next */\n function Buffer_allocUnsafe(size) {\n return new Buffer(size);\n };\n};\n","\"use strict\";\nmodule.exports = Writer;\n\nvar util = require(\"./util/minimal\");\n\nvar BufferWriter; // cyclic\n\nvar LongBits = util.LongBits,\n base64 = util.base64,\n utf8 = util.utf8;\n\n/**\n * Constructs a new writer operation instance.\n * @classdesc Scheduled writer operation.\n * @constructor\n * @param {function(*, Uint8Array, number)} fn Function to call\n * @param {number} len Value byte length\n * @param {*} val Value to write\n * @ignore\n */\nfunction Op(fn, len, val) {\n\n /**\n * Function to call.\n * @type {function(Uint8Array, number, *)}\n */\n this.fn = fn;\n\n /**\n * Value byte length.\n * @type {number}\n */\n this.len = len;\n\n /**\n * Next operation.\n * @type {Writer.Op|undefined}\n */\n this.next = undefined;\n\n /**\n * Value to write.\n * @type {*}\n */\n this.val = val; // type varies\n}\n\n/* istanbul ignore next */\nfunction noop() {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance.\n * @classdesc Copied writer state.\n * @memberof Writer\n * @constructor\n * @param {Writer} writer Writer to copy state from\n * @ignore\n */\nfunction State(writer) {\n\n /**\n * Current head.\n * @type {Writer.Op}\n */\n this.head = writer.head;\n\n /**\n * Current tail.\n * @type {Writer.Op}\n */\n this.tail = writer.tail;\n\n /**\n * Current buffer length.\n * @type {number}\n */\n this.len = writer.len;\n\n /**\n * Next state.\n * @type {State|null}\n */\n this.next = writer.states;\n}\n\n/**\n * Constructs a new writer instance.\n * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n */\nfunction Writer() {\n\n /**\n * Current length.\n * @type {number}\n */\n this.len = 0;\n\n /**\n * Operations head.\n * @type {Object}\n */\n this.head = new Op(noop, 0, 0);\n\n /**\n * Operations tail\n * @type {Object}\n */\n this.tail = this.head;\n\n /**\n * Linked forked states.\n * @type {Object|null}\n */\n this.states = null;\n\n // When a value is written, the writer calculates its byte length and puts it into a linked\n // list of operations to perform when finish() is called. This both allows us to allocate\n // buffers of the exact required size and reduces the amount of work we have to do compared\n // to first calculating over objects and then encoding over objects. In our case, the encoding\n // part is just a linked list walk calling operations with already prepared values.\n}\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup() {\n return (Writer.create = function create_buffer() {\n return new BufferWriter();\n })();\n }\n /* istanbul ignore next */\n : function create_array() {\n return new Writer();\n };\n};\n\n/**\n * Creates a new writer.\n * @function\n * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}\n */\nWriter.create = create();\n\n/**\n * Allocates a buffer of the specified size.\n * @param {number} size Buffer size\n * @returns {Uint8Array} Buffer\n */\nWriter.alloc = function alloc(size) {\n return new util.Array(size);\n};\n\n// Use Uint8Array buffer pool in the browser, just like node does with buffers\n/* istanbul ignore else */\nif (util.Array !== Array)\n Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);\n\n/**\n * Pushes a new operation to the queue.\n * @param {function(Uint8Array, number, *)} fn Function to call\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @returns {Writer} `this`\n * @private\n */\nWriter.prototype._push = function push(fn, len, val) {\n this.tail = this.tail.next = new Op(fn, len, val);\n this.len += len;\n return this;\n};\n\nfunction writeByte(val, buf, pos) {\n buf[pos] = val & 255;\n}\n\nfunction writeVarint32(val, buf, pos) {\n while (val > 127) {\n buf[pos++] = val & 127 | 128;\n val >>>= 7;\n }\n buf[pos] = val;\n}\n\n/**\n * Constructs a new varint writer operation instance.\n * @classdesc Scheduled varint writer operation.\n * @extends Op\n * @constructor\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @ignore\n */\nfunction VarintOp(len, val) {\n this.len = len;\n this.next = undefined;\n this.val = val;\n}\n\nVarintOp.prototype = Object.create(Op.prototype);\nVarintOp.prototype.fn = writeVarint32;\n\n/**\n * Writes an unsigned 32 bit value as a varint.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.uint32 = function write_uint32(value) {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0)\n < 128 ? 1\n : value < 16384 ? 2\n : value < 2097152 ? 3\n : value < 268435456 ? 4\n : 5,\n value)).len;\n return this;\n};\n\n/**\n * Writes a signed 32 bit value as a varint.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.int32 = function write_int32(value) {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value);\n};\n\n/**\n * Writes a 32 bit value as a varint, zig-zag encoded.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sint32 = function write_sint32(value) {\n return this.uint32((value << 1 ^ value >> 31) >>> 0);\n};\n\nfunction writeVarint64(val, buf, pos) {\n while (val.hi) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;\n val.hi >>>= 7;\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = val.lo >>> 7;\n }\n buf[pos++] = val.lo;\n}\n\n/**\n * Writes an unsigned 64 bit value as a varint.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.uint64 = function write_uint64(value) {\n var bits = LongBits.from(value);\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a signed 64 bit value as a varint.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.int64 = Writer.prototype.uint64;\n\n/**\n * Writes a signed 64 bit value as a varint, zig-zag encoded.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sint64 = function write_sint64(value) {\n var bits = LongBits.from(value).zzEncode();\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a boolish value as a varint.\n * @param {boolean} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bool = function write_bool(value) {\n return this._push(writeByte, 1, value ? 1 : 0);\n};\n\nfunction writeFixed32(val, buf, pos) {\n buf[pos ] = val & 255;\n buf[pos + 1] = val >>> 8 & 255;\n buf[pos + 2] = val >>> 16 & 255;\n buf[pos + 3] = val >>> 24;\n}\n\n/**\n * Writes an unsigned 32 bit value as fixed 32 bits.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.fixed32 = function write_fixed32(value) {\n return this._push(writeFixed32, 4, value >>> 0);\n};\n\n/**\n * Writes a signed 32 bit value as fixed 32 bits.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sfixed32 = Writer.prototype.fixed32;\n\n/**\n * Writes an unsigned 64 bit value as fixed 64 bits.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.fixed64 = function write_fixed64(value) {\n var bits = LongBits.from(value);\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\n};\n\n/**\n * Writes a signed 64 bit value as fixed 64 bits.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sfixed64 = Writer.prototype.fixed64;\n\n/**\n * Writes a float (32 bit).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.float = function write_float(value) {\n return this._push(util.float.writeFloatLE, 4, value);\n};\n\n/**\n * Writes a double (64 bit float).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.double = function write_double(value) {\n return this._push(util.float.writeDoubleLE, 8, value);\n};\n\nvar writeBytes = util.Array.prototype.set\n ? function writeBytes_set(val, buf, pos) {\n buf.set(val, pos); // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytes_for(val, buf, pos) {\n for (var i = 0; i < val.length; ++i)\n buf[pos + i] = val[i];\n };\n\n/**\n * Writes a sequence of bytes.\n * @param {Uint8Array|string} value Buffer or base64 encoded string to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bytes = function write_bytes(value) {\n var len = value.length >>> 0;\n if (!len)\n return this._push(writeByte, 1, 0);\n if (util.isString(value)) {\n var buf = Writer.alloc(len = base64.length(value));\n base64.decode(value, buf, 0);\n value = buf;\n }\n return this.uint32(len)._push(writeBytes, len, value);\n};\n\n/**\n * Writes a string.\n * @param {string} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.string = function write_string(value) {\n var len = utf8.length(value);\n return len\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0);\n};\n\n/**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n * @returns {Writer} `this`\n */\nWriter.prototype.fork = function fork() {\n this.states = new State(this);\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n return this;\n};\n\n/**\n * Resets this instance to the last state.\n * @returns {Writer} `this`\n */\nWriter.prototype.reset = function reset() {\n if (this.states) {\n this.head = this.states.head;\n this.tail = this.states.tail;\n this.len = this.states.len;\n this.states = this.states.next;\n } else {\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n }\n return this;\n};\n\n/**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n * @returns {Writer} `this`\n */\nWriter.prototype.ldelim = function ldelim() {\n var head = this.head,\n tail = this.tail,\n len = this.len;\n this.reset().uint32(len);\n if (len) {\n this.tail.next = head.next; // skip noop\n this.tail = tail;\n this.len += len;\n }\n return this;\n};\n\n/**\n * Finishes the write operation.\n * @returns {Uint8Array} Finished buffer\n */\nWriter.prototype.finish = function finish() {\n var head = this.head.next, // skip noop\n buf = this.constructor.alloc(this.len),\n pos = 0;\n while (head) {\n head.fn(head.val, buf, pos);\n pos += head.len;\n head = head.next;\n }\n // this.head = this.tail = null;\n return buf;\n};\n\nWriter._configure = function(BufferWriter_) {\n BufferWriter = BufferWriter_;\n Writer.create = create();\n BufferWriter._configure();\n};\n","\"use strict\";\nmodule.exports = BufferWriter;\n\n// extends Writer\nvar Writer = require(\"./writer\");\n(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;\n\nvar util = require(\"./util/minimal\");\n\n/**\n * Constructs a new buffer writer instance.\n * @classdesc Wire format writer using node buffers.\n * @extends Writer\n * @constructor\n */\nfunction BufferWriter() {\n Writer.call(this);\n}\n\nBufferWriter._configure = function () {\n /**\n * Allocates a buffer of the specified size.\n * @function\n * @param {number} size Buffer size\n * @returns {Buffer} Buffer\n */\n BufferWriter.alloc = util._Buffer_allocUnsafe;\n\n BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === \"set\"\n ? function writeBytesBuffer_set(val, buf, pos) {\n buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytesBuffer_copy(val, buf, pos) {\n if (val.copy) // Buffer values\n val.copy(buf, pos, 0, val.length);\n else for (var i = 0; i < val.length;) // plain array values\n buf[pos++] = val[i++];\n };\n};\n\n\n/**\n * @override\n */\nBufferWriter.prototype.bytes = function write_bytes_buffer(value) {\n if (util.isString(value))\n value = util._Buffer_from(value, \"base64\");\n var len = value.length >>> 0;\n this.uint32(len);\n if (len)\n this._push(BufferWriter.writeBytesBuffer, len, value);\n return this;\n};\n\nfunction writeStringBuffer(val, buf, pos) {\n if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)\n util.utf8.write(val, buf, pos);\n else if (buf.utf8Write)\n buf.utf8Write(val, pos);\n else\n buf.write(val, pos);\n}\n\n/**\n * @override\n */\nBufferWriter.prototype.string = function write_string_buffer(value) {\n var len = util.Buffer.byteLength(value);\n this.uint32(len);\n if (len)\n this._push(writeStringBuffer, len, value);\n return this;\n};\n\n\n/**\n * Finishes the write operation.\n * @name BufferWriter#finish\n * @function\n * @returns {Buffer} Finished buffer\n */\n\nBufferWriter._configure();\n","\"use strict\";\nmodule.exports = Reader;\n\nvar util = require(\"./util/minimal\");\n\nvar BufferReader; // cyclic\n\nvar LongBits = util.LongBits,\n utf8 = util.utf8;\n\n/* istanbul ignore next */\nfunction indexOutOfRange(reader, writeLength) {\n return RangeError(\"index out of range: \" + reader.pos + \" + \" + (writeLength || 1) + \" > \" + reader.len);\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n * @param {Uint8Array} buffer Buffer to read from\n */\nfunction Reader(buffer) {\n\n /**\n * Read buffer.\n * @type {Uint8Array}\n */\n this.buf = buffer;\n\n /**\n * Read buffer position.\n * @type {number}\n */\n this.pos = 0;\n\n /**\n * Read buffer length.\n * @type {number}\n */\n this.len = buffer.length;\n}\n\nvar create_array = typeof Uint8Array !== \"undefined\"\n ? function create_typed_array(buffer) {\n if (buffer instanceof Uint8Array || Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n }\n /* istanbul ignore next */\n : function create_array(buffer) {\n if (Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n };\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup(buffer) {\n return (Reader.create = function create_buffer(buffer) {\n return util.Buffer.isBuffer(buffer)\n ? new BufferReader(buffer)\n /* istanbul ignore next */\n : create_array(buffer);\n })(buffer);\n }\n /* istanbul ignore next */\n : create_array;\n};\n\n/**\n * Creates a new reader using the specified buffer.\n * @function\n * @param {Uint8Array|Buffer} buffer Buffer to read from\n * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}\n * @throws {Error} If `buffer` is not a valid buffer\n */\nReader.create = create();\n\nReader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;\n\n/**\n * Reads a varint as an unsigned 32 bit value.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.uint32 = (function read_uint32_setup() {\n var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)\n return function read_uint32() {\n value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;\n\n /* istanbul ignore if */\n if ((this.pos += 5) > this.len) {\n this.pos = this.len;\n throw indexOutOfRange(this, 10);\n }\n return value;\n };\n})();\n\n/**\n * Reads a varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.int32 = function read_int32() {\n return this.uint32() | 0;\n};\n\n/**\n * Reads a zig-zag encoded varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.sint32 = function read_sint32() {\n var value = this.uint32();\n return value >>> 1 ^ -(value & 1) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readLongVarint() {\n // tends to deopt with local vars for octet etc.\n var bits = new LongBits(0, 0);\n var i = 0;\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n i = 0;\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;\n return bits;\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n } else {\n for (; i < 5; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n }\n /* istanbul ignore next */\n throw Error(\"invalid varint encoding\");\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads a varint as a signed 64 bit value.\n * @name Reader#int64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as an unsigned 64 bit value.\n * @name Reader#uint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a zig-zag encoded varint as a signed 64 bit value.\n * @name Reader#sint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as a boolean.\n * @returns {boolean} Value read\n */\nReader.prototype.bool = function read_bool() {\n return this.uint32() !== 0;\n};\n\nfunction readFixed32_end(buf, end) { // note that this uses `end`, not `pos`\n return (buf[end - 4]\n | buf[end - 3] << 8\n | buf[end - 2] << 16\n | buf[end - 1] << 24) >>> 0;\n}\n\n/**\n * Reads fixed 32 bits as an unsigned 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.fixed32 = function read_fixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4);\n};\n\n/**\n * Reads fixed 32 bits as a signed 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.sfixed32 = function read_sfixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readFixed64(/* this: Reader */) {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 8);\n\n return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads fixed 64 bits.\n * @name Reader#fixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads zig-zag encoded fixed 64 bits.\n * @name Reader#sfixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a float (32 bit) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.float = function read_float() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readFloatLE(this.buf, this.pos);\n this.pos += 4;\n return value;\n};\n\n/**\n * Reads a double (64 bit float) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.double = function read_double() {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readDoubleLE(this.buf, this.pos);\n this.pos += 8;\n return value;\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @returns {Uint8Array} Value read\n */\nReader.prototype.bytes = function read_bytes() {\n var length = this.uint32(),\n start = this.pos,\n end = this.pos + length;\n\n /* istanbul ignore if */\n if (end > this.len)\n throw indexOutOfRange(this, length);\n\n this.pos += length;\n if (Array.isArray(this.buf)) // plain array\n return this.buf.slice(start, end);\n\n if (start === end) { // fix for IE 10/Win8 and others' subarray returning array of size 1\n var nativeBuffer = util.Buffer;\n return nativeBuffer\n ? nativeBuffer.alloc(0)\n : new this.buf.constructor(0);\n }\n return this._slice.call(this.buf, start, end);\n};\n\n/**\n * Reads a string preceeded by its byte length as a varint.\n * @returns {string} Value read\n */\nReader.prototype.string = function read_string() {\n var bytes = this.bytes();\n return utf8.read(bytes, 0, bytes.length);\n};\n\n/**\n * Skips the specified number of bytes if specified, otherwise skips a varint.\n * @param {number} [length] Length if known, otherwise a varint is assumed\n * @returns {Reader} `this`\n */\nReader.prototype.skip = function skip(length) {\n if (typeof length === \"number\") {\n /* istanbul ignore if */\n if (this.pos + length > this.len)\n throw indexOutOfRange(this, length);\n this.pos += length;\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n } while (this.buf[this.pos++] & 128);\n }\n return this;\n};\n\n/**\n * Skips the next element of the specified wire type.\n * @param {number} wireType Wire type received\n * @returns {Reader} `this`\n */\nReader.prototype.skipType = function(wireType) {\n switch (wireType) {\n case 0:\n this.skip();\n break;\n case 1:\n this.skip(8);\n break;\n case 2:\n this.skip(this.uint32());\n break;\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType);\n }\n break;\n case 5:\n this.skip(4);\n break;\n\n /* istanbul ignore next */\n default:\n throw Error(\"invalid wire type \" + wireType + \" at offset \" + this.pos);\n }\n return this;\n};\n\nReader._configure = function(BufferReader_) {\n BufferReader = BufferReader_;\n Reader.create = create();\n BufferReader._configure();\n\n var fn = util.Long ? \"toLong\" : /* istanbul ignore next */ \"toNumber\";\n util.merge(Reader.prototype, {\n\n int64: function read_int64() {\n return readLongVarint.call(this)[fn](false);\n },\n\n uint64: function read_uint64() {\n return readLongVarint.call(this)[fn](true);\n },\n\n sint64: function read_sint64() {\n return readLongVarint.call(this).zzDecode()[fn](false);\n },\n\n fixed64: function read_fixed64() {\n return readFixed64.call(this)[fn](true);\n },\n\n sfixed64: function read_sfixed64() {\n return readFixed64.call(this)[fn](false);\n }\n\n });\n};\n","\"use strict\";\nmodule.exports = BufferReader;\n\n// extends Reader\nvar Reader = require(\"./reader\");\n(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;\n\nvar util = require(\"./util/minimal\");\n\n/**\n * Constructs a new buffer reader instance.\n * @classdesc Wire format reader using node buffers.\n * @extends Reader\n * @constructor\n * @param {Buffer} buffer Buffer to read from\n */\nfunction BufferReader(buffer) {\n Reader.call(this, buffer);\n\n /**\n * Read buffer.\n * @name BufferReader#buf\n * @type {Buffer}\n */\n}\n\nBufferReader._configure = function () {\n /* istanbul ignore else */\n if (util.Buffer)\n BufferReader.prototype._slice = util.Buffer.prototype.slice;\n};\n\n\n/**\n * @override\n */\nBufferReader.prototype.string = function read_string_buffer() {\n var len = this.uint32(); // modifies pos\n return this.buf.utf8Slice\n ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len))\n : this.buf.toString(\"utf-8\", this.pos, this.pos = Math.min(this.pos + len, this.len));\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @name BufferReader#bytes\n * @function\n * @returns {Buffer} Value read\n */\n\nBufferReader._configure();\n","\"use strict\";\nmodule.exports = Service;\n\nvar util = require(\"../util/minimal\");\n\n// Extends EventEmitter\n(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;\n\n/**\n * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.\n *\n * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.\n * @typedef rpc.ServiceMethodCallback\n * @template TRes extends Message\n * @type {function}\n * @param {Error|null} error Error, if any\n * @param {TRes} [response] Response message\n * @returns {undefined}\n */\n\n/**\n * A service method part of a {@link rpc.Service} as created by {@link Service.create}.\n * @typedef rpc.ServiceMethod\n * @template TReq extends Message\n * @template TRes extends Message\n * @type {function}\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message\n * @returns {Promise>} Promise if `callback` has been omitted, otherwise `undefined`\n */\n\n/**\n * Constructs a new RPC service instance.\n * @classdesc An RPC service as returned by {@link Service#create}.\n * @exports rpc.Service\n * @extends util.EventEmitter\n * @constructor\n * @param {RPCImpl} rpcImpl RPC implementation\n * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\n * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\n */\nfunction Service(rpcImpl, requestDelimited, responseDelimited) {\n\n if (typeof rpcImpl !== \"function\")\n throw TypeError(\"rpcImpl must be a function\");\n\n util.EventEmitter.call(this);\n\n /**\n * RPC implementation. Becomes `null` once the service is ended.\n * @type {RPCImpl|null}\n */\n this.rpcImpl = rpcImpl;\n\n /**\n * Whether requests are length-delimited.\n * @type {boolean}\n */\n this.requestDelimited = Boolean(requestDelimited);\n\n /**\n * Whether responses are length-delimited.\n * @type {boolean}\n */\n this.responseDelimited = Boolean(responseDelimited);\n}\n\n/**\n * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.\n * @param {Method|rpc.ServiceMethod} method Reflected or static method\n * @param {Constructor} requestCtor Request constructor\n * @param {Constructor} responseCtor Response constructor\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} callback Service callback\n * @returns {undefined}\n * @template TReq extends Message\n * @template TRes extends Message\n */\nService.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {\n\n if (!request)\n throw TypeError(\"request must be specified\");\n\n var self = this;\n if (!callback)\n return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);\n\n if (!self.rpcImpl) {\n setTimeout(function() { callback(Error(\"already ended\")); }, 0);\n return undefined;\n }\n\n try {\n return self.rpcImpl(\n method,\n requestCtor[self.requestDelimited ? \"encodeDelimited\" : \"encode\"](request).finish(),\n function rpcCallback(err, response) {\n\n if (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n\n if (response === null) {\n self.end(/* endedByRPC */ true);\n return undefined;\n }\n\n if (!(response instanceof responseCtor)) {\n try {\n response = responseCtor[self.responseDelimited ? \"decodeDelimited\" : \"decode\"](response);\n } catch (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n }\n\n self.emit(\"data\", response, method);\n return callback(null, response);\n }\n );\n } catch (err) {\n self.emit(\"error\", err, method);\n setTimeout(function() { callback(err); }, 0);\n return undefined;\n }\n};\n\n/**\n * Ends this service and emits the `end` event.\n * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.\n * @returns {rpc.Service} `this`\n */\nService.prototype.end = function end(endedByRPC) {\n if (this.rpcImpl) {\n if (!endedByRPC) // signal end to rpcImpl\n this.rpcImpl(null, null, null);\n this.rpcImpl = null;\n this.emit(\"end\").off();\n }\n return this;\n};\n","\"use strict\";\n\n/**\n * Streaming RPC helpers.\n * @namespace\n */\nvar rpc = exports;\n\n/**\n * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.\n * @typedef RPCImpl\n * @type {function}\n * @param {Method|rpc.ServiceMethod,Message<{}>>} method Reflected or static method being called\n * @param {Uint8Array} requestData Request data\n * @param {RPCImplCallback} callback Callback function\n * @returns {undefined}\n * @example\n * function rpcImpl(method, requestData, callback) {\n * if (protobuf.util.lcFirst(method.name) !== \"myMethod\") // compatible with static code\n * throw Error(\"no such method\");\n * asynchronouslyObtainAResponse(requestData, function(err, responseData) {\n * callback(err, responseData);\n * });\n * }\n */\n\n/**\n * Node-style callback as used by {@link RPCImpl}.\n * @typedef RPCImplCallback\n * @type {function}\n * @param {Error|null} error Error, if any, otherwise `null`\n * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error\n * @returns {undefined}\n */\n\nrpc.Service = require(\"./rpc/service\");\n","\"use strict\";\nmodule.exports = {};\n\n/**\n * Named roots.\n * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).\n * Can also be used manually to make roots available across modules.\n * @name roots\n * @type {Object.}\n * @example\n * // pbjs -r myroot -o compiled.js ...\n *\n * // in another module:\n * require(\"./compiled.js\");\n *\n * // in any subsequent module:\n * var root = protobuf.roots[\"myroot\"];\n */\n","\"use strict\";\nvar protobuf = exports;\n\n/**\n * Build type, one of `\"full\"`, `\"light\"` or `\"minimal\"`.\n * @name build\n * @type {string}\n * @const\n */\nprotobuf.build = \"minimal\";\n\n// Serialization\nprotobuf.Writer = require(\"./writer\");\nprotobuf.BufferWriter = require(\"./writer_buffer\");\nprotobuf.Reader = require(\"./reader\");\nprotobuf.BufferReader = require(\"./reader_buffer\");\n\n// Utility\nprotobuf.util = require(\"./util/minimal\");\nprotobuf.rpc = require(\"./rpc\");\nprotobuf.roots = require(\"./roots\");\nprotobuf.configure = configure;\n\n/* istanbul ignore next */\n/**\n * Reconfigures the library according to the environment.\n * @returns {undefined}\n */\nfunction configure() {\n protobuf.util._configure();\n protobuf.Writer._configure(protobuf.BufferWriter);\n protobuf.Reader._configure(protobuf.BufferReader);\n}\n\n// Set up buffer utility according to the environment\nconfigure();\n","// minimal library entry point.\n\n\"use strict\";\nmodule.exports = require(\"./src/index-minimal\");\n","/*eslint-disable*/\nimport $protobuf from \"protobufjs/minimal.js\";\n\n// Common aliases\nconst $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util;\n\n// Exported root namespace\nconst $root = $protobuf.roots.unixfs || ($protobuf.roots.unixfs = {});\n\nexport const Data = $root.Data = (() => {\n\n /**\n * Properties of a Data.\n * @exports IData\n * @interface IData\n * @property {Data.DataType} Type Data Type\n * @property {Uint8Array|null} [Data] Data Data\n * @property {number|null} [filesize] Data filesize\n * @property {Array.|null} [blocksizes] Data blocksizes\n * @property {number|null} [hashType] Data hashType\n * @property {number|null} [fanout] Data fanout\n * @property {number|null} [mode] Data mode\n * @property {IUnixTime|null} [mtime] Data mtime\n */\n\n /**\n * Constructs a new Data.\n * @exports Data\n * @classdesc Represents a Data.\n * @implements IData\n * @constructor\n * @param {IData=} [p] Properties to set\n */\n function Data(p) {\n this.blocksizes = [];\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Data Type.\n * @member {Data.DataType} Type\n * @memberof Data\n * @instance\n */\n Data.prototype.Type = 0;\n\n /**\n * Data Data.\n * @member {Uint8Array} Data\n * @memberof Data\n * @instance\n */\n Data.prototype.Data = $util.newBuffer([]);\n\n /**\n * Data filesize.\n * @member {number} filesize\n * @memberof Data\n * @instance\n */\n Data.prototype.filesize = $util.Long ? $util.Long.fromBits(0,0,true) : 0;\n\n /**\n * Data blocksizes.\n * @member {Array.} blocksizes\n * @memberof Data\n * @instance\n */\n Data.prototype.blocksizes = $util.emptyArray;\n\n /**\n * Data hashType.\n * @member {number} hashType\n * @memberof Data\n * @instance\n */\n Data.prototype.hashType = $util.Long ? $util.Long.fromBits(0,0,true) : 0;\n\n /**\n * Data fanout.\n * @member {number} fanout\n * @memberof Data\n * @instance\n */\n Data.prototype.fanout = $util.Long ? $util.Long.fromBits(0,0,true) : 0;\n\n /**\n * Data mode.\n * @member {number} mode\n * @memberof Data\n * @instance\n */\n Data.prototype.mode = 0;\n\n /**\n * Data mtime.\n * @member {IUnixTime|null|undefined} mtime\n * @memberof Data\n * @instance\n */\n Data.prototype.mtime = null;\n\n /**\n * Encodes the specified Data message. Does not implicitly {@link Data.verify|verify} messages.\n * @function encode\n * @memberof Data\n * @static\n * @param {IData} m Data message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Data.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n w.uint32(8).int32(m.Type);\n if (m.Data != null && Object.hasOwnProperty.call(m, \"Data\"))\n w.uint32(18).bytes(m.Data);\n if (m.filesize != null && Object.hasOwnProperty.call(m, \"filesize\"))\n w.uint32(24).uint64(m.filesize);\n if (m.blocksizes != null && m.blocksizes.length) {\n for (var i = 0; i < m.blocksizes.length; ++i)\n w.uint32(32).uint64(m.blocksizes[i]);\n }\n if (m.hashType != null && Object.hasOwnProperty.call(m, \"hashType\"))\n w.uint32(40).uint64(m.hashType);\n if (m.fanout != null && Object.hasOwnProperty.call(m, \"fanout\"))\n w.uint32(48).uint64(m.fanout);\n if (m.mode != null && Object.hasOwnProperty.call(m, \"mode\"))\n w.uint32(56).uint32(m.mode);\n if (m.mtime != null && Object.hasOwnProperty.call(m, \"mtime\"))\n $root.UnixTime.encode(m.mtime, w.uint32(66).fork()).ldelim();\n return w;\n };\n\n /**\n * Decodes a Data message from the specified reader or buffer.\n * @function decode\n * @memberof Data\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Data} Data\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Data.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Data();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.Type = r.int32();\n break;\n case 2:\n m.Data = r.bytes();\n break;\n case 3:\n m.filesize = r.uint64();\n break;\n case 4:\n if (!(m.blocksizes && m.blocksizes.length))\n m.blocksizes = [];\n if ((t & 7) === 2) {\n var c2 = r.uint32() + r.pos;\n while (r.pos < c2)\n m.blocksizes.push(r.uint64());\n } else\n m.blocksizes.push(r.uint64());\n break;\n case 5:\n m.hashType = r.uint64();\n break;\n case 6:\n m.fanout = r.uint64();\n break;\n case 7:\n m.mode = r.uint32();\n break;\n case 8:\n m.mtime = $root.UnixTime.decode(r, r.uint32());\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n if (!m.hasOwnProperty(\"Type\"))\n throw $util.ProtocolError(\"missing required 'Type'\", { instance: m });\n return m;\n };\n\n /**\n * Creates a Data message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Data\n * @static\n * @param {Object.} d Plain object\n * @returns {Data} Data\n */\n Data.fromObject = function fromObject(d) {\n if (d instanceof $root.Data)\n return d;\n var m = new $root.Data();\n switch (d.Type) {\n case \"Raw\":\n case 0:\n m.Type = 0;\n break;\n case \"Directory\":\n case 1:\n m.Type = 1;\n break;\n case \"File\":\n case 2:\n m.Type = 2;\n break;\n case \"Metadata\":\n case 3:\n m.Type = 3;\n break;\n case \"Symlink\":\n case 4:\n m.Type = 4;\n break;\n case \"HAMTShard\":\n case 5:\n m.Type = 5;\n break;\n }\n if (d.Data != null) {\n if (typeof d.Data === \"string\")\n $util.base64.decode(d.Data, m.Data = $util.newBuffer($util.base64.length(d.Data)), 0);\n else if (d.Data.length)\n m.Data = d.Data;\n }\n if (d.filesize != null) {\n if ($util.Long)\n (m.filesize = $util.Long.fromValue(d.filesize)).unsigned = true;\n else if (typeof d.filesize === \"string\")\n m.filesize = parseInt(d.filesize, 10);\n else if (typeof d.filesize === \"number\")\n m.filesize = d.filesize;\n else if (typeof d.filesize === \"object\")\n m.filesize = new $util.LongBits(d.filesize.low >>> 0, d.filesize.high >>> 0).toNumber(true);\n }\n if (d.blocksizes) {\n if (!Array.isArray(d.blocksizes))\n throw TypeError(\".Data.blocksizes: array expected\");\n m.blocksizes = [];\n for (var i = 0; i < d.blocksizes.length; ++i) {\n if ($util.Long)\n (m.blocksizes[i] = $util.Long.fromValue(d.blocksizes[i])).unsigned = true;\n else if (typeof d.blocksizes[i] === \"string\")\n m.blocksizes[i] = parseInt(d.blocksizes[i], 10);\n else if (typeof d.blocksizes[i] === \"number\")\n m.blocksizes[i] = d.blocksizes[i];\n else if (typeof d.blocksizes[i] === \"object\")\n m.blocksizes[i] = new $util.LongBits(d.blocksizes[i].low >>> 0, d.blocksizes[i].high >>> 0).toNumber(true);\n }\n }\n if (d.hashType != null) {\n if ($util.Long)\n (m.hashType = $util.Long.fromValue(d.hashType)).unsigned = true;\n else if (typeof d.hashType === \"string\")\n m.hashType = parseInt(d.hashType, 10);\n else if (typeof d.hashType === \"number\")\n m.hashType = d.hashType;\n else if (typeof d.hashType === \"object\")\n m.hashType = new $util.LongBits(d.hashType.low >>> 0, d.hashType.high >>> 0).toNumber(true);\n }\n if (d.fanout != null) {\n if ($util.Long)\n (m.fanout = $util.Long.fromValue(d.fanout)).unsigned = true;\n else if (typeof d.fanout === \"string\")\n m.fanout = parseInt(d.fanout, 10);\n else if (typeof d.fanout === \"number\")\n m.fanout = d.fanout;\n else if (typeof d.fanout === \"object\")\n m.fanout = new $util.LongBits(d.fanout.low >>> 0, d.fanout.high >>> 0).toNumber(true);\n }\n if (d.mode != null) {\n m.mode = d.mode >>> 0;\n }\n if (d.mtime != null) {\n if (typeof d.mtime !== \"object\")\n throw TypeError(\".Data.mtime: object expected\");\n m.mtime = $root.UnixTime.fromObject(d.mtime);\n }\n return m;\n };\n\n /**\n * Creates a plain object from a Data message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Data\n * @static\n * @param {Data} m Data\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Data.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.arrays || o.defaults) {\n d.blocksizes = [];\n }\n if (o.defaults) {\n d.Type = o.enums === String ? \"Raw\" : 0;\n if (o.bytes === String)\n d.Data = \"\";\n else {\n d.Data = [];\n if (o.bytes !== Array)\n d.Data = $util.newBuffer(d.Data);\n }\n if ($util.Long) {\n var n = new $util.Long(0, 0, true);\n d.filesize = o.longs === String ? n.toString() : o.longs === Number ? n.toNumber() : n;\n } else\n d.filesize = o.longs === String ? \"0\" : 0;\n if ($util.Long) {\n var n = new $util.Long(0, 0, true);\n d.hashType = o.longs === String ? n.toString() : o.longs === Number ? n.toNumber() : n;\n } else\n d.hashType = o.longs === String ? \"0\" : 0;\n if ($util.Long) {\n var n = new $util.Long(0, 0, true);\n d.fanout = o.longs === String ? n.toString() : o.longs === Number ? n.toNumber() : n;\n } else\n d.fanout = o.longs === String ? \"0\" : 0;\n d.mode = 0;\n d.mtime = null;\n }\n if (m.Type != null && m.hasOwnProperty(\"Type\")) {\n d.Type = o.enums === String ? $root.Data.DataType[m.Type] : m.Type;\n }\n if (m.Data != null && m.hasOwnProperty(\"Data\")) {\n d.Data = o.bytes === String ? $util.base64.encode(m.Data, 0, m.Data.length) : o.bytes === Array ? Array.prototype.slice.call(m.Data) : m.Data;\n }\n if (m.filesize != null && m.hasOwnProperty(\"filesize\")) {\n if (typeof m.filesize === \"number\")\n d.filesize = o.longs === String ? String(m.filesize) : m.filesize;\n else\n d.filesize = o.longs === String ? $util.Long.prototype.toString.call(m.filesize) : o.longs === Number ? new $util.LongBits(m.filesize.low >>> 0, m.filesize.high >>> 0).toNumber(true) : m.filesize;\n }\n if (m.blocksizes && m.blocksizes.length) {\n d.blocksizes = [];\n for (var j = 0; j < m.blocksizes.length; ++j) {\n if (typeof m.blocksizes[j] === \"number\")\n d.blocksizes[j] = o.longs === String ? String(m.blocksizes[j]) : m.blocksizes[j];\n else\n d.blocksizes[j] = o.longs === String ? $util.Long.prototype.toString.call(m.blocksizes[j]) : o.longs === Number ? new $util.LongBits(m.blocksizes[j].low >>> 0, m.blocksizes[j].high >>> 0).toNumber(true) : m.blocksizes[j];\n }\n }\n if (m.hashType != null && m.hasOwnProperty(\"hashType\")) {\n if (typeof m.hashType === \"number\")\n d.hashType = o.longs === String ? String(m.hashType) : m.hashType;\n else\n d.hashType = o.longs === String ? $util.Long.prototype.toString.call(m.hashType) : o.longs === Number ? new $util.LongBits(m.hashType.low >>> 0, m.hashType.high >>> 0).toNumber(true) : m.hashType;\n }\n if (m.fanout != null && m.hasOwnProperty(\"fanout\")) {\n if (typeof m.fanout === \"number\")\n d.fanout = o.longs === String ? String(m.fanout) : m.fanout;\n else\n d.fanout = o.longs === String ? $util.Long.prototype.toString.call(m.fanout) : o.longs === Number ? new $util.LongBits(m.fanout.low >>> 0, m.fanout.high >>> 0).toNumber(true) : m.fanout;\n }\n if (m.mode != null && m.hasOwnProperty(\"mode\")) {\n d.mode = m.mode;\n }\n if (m.mtime != null && m.hasOwnProperty(\"mtime\")) {\n d.mtime = $root.UnixTime.toObject(m.mtime, o);\n }\n return d;\n };\n\n /**\n * Converts this Data to JSON.\n * @function toJSON\n * @memberof Data\n * @instance\n * @returns {Object.} JSON object\n */\n Data.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n /**\n * DataType enum.\n * @name Data.DataType\n * @enum {number}\n * @property {number} Raw=0 Raw value\n * @property {number} Directory=1 Directory value\n * @property {number} File=2 File value\n * @property {number} Metadata=3 Metadata value\n * @property {number} Symlink=4 Symlink value\n * @property {number} HAMTShard=5 HAMTShard value\n */\n Data.DataType = (function() {\n const valuesById = {}, values = Object.create(valuesById);\n values[valuesById[0] = \"Raw\"] = 0;\n values[valuesById[1] = \"Directory\"] = 1;\n values[valuesById[2] = \"File\"] = 2;\n values[valuesById[3] = \"Metadata\"] = 3;\n values[valuesById[4] = \"Symlink\"] = 4;\n values[valuesById[5] = \"HAMTShard\"] = 5;\n return values;\n })();\n\n return Data;\n})();\n\nexport const UnixTime = $root.UnixTime = (() => {\n\n /**\n * Properties of an UnixTime.\n * @exports IUnixTime\n * @interface IUnixTime\n * @property {number} Seconds UnixTime Seconds\n * @property {number|null} [FractionalNanoseconds] UnixTime FractionalNanoseconds\n */\n\n /**\n * Constructs a new UnixTime.\n * @exports UnixTime\n * @classdesc Represents an UnixTime.\n * @implements IUnixTime\n * @constructor\n * @param {IUnixTime=} [p] Properties to set\n */\n function UnixTime(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * UnixTime Seconds.\n * @member {number} Seconds\n * @memberof UnixTime\n * @instance\n */\n UnixTime.prototype.Seconds = $util.Long ? $util.Long.fromBits(0,0,false) : 0;\n\n /**\n * UnixTime FractionalNanoseconds.\n * @member {number} FractionalNanoseconds\n * @memberof UnixTime\n * @instance\n */\n UnixTime.prototype.FractionalNanoseconds = 0;\n\n /**\n * Encodes the specified UnixTime message. Does not implicitly {@link UnixTime.verify|verify} messages.\n * @function encode\n * @memberof UnixTime\n * @static\n * @param {IUnixTime} m UnixTime message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n UnixTime.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n w.uint32(8).int64(m.Seconds);\n if (m.FractionalNanoseconds != null && Object.hasOwnProperty.call(m, \"FractionalNanoseconds\"))\n w.uint32(21).fixed32(m.FractionalNanoseconds);\n return w;\n };\n\n /**\n * Decodes an UnixTime message from the specified reader or buffer.\n * @function decode\n * @memberof UnixTime\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {UnixTime} UnixTime\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n UnixTime.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.UnixTime();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.Seconds = r.int64();\n break;\n case 2:\n m.FractionalNanoseconds = r.fixed32();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n if (!m.hasOwnProperty(\"Seconds\"))\n throw $util.ProtocolError(\"missing required 'Seconds'\", { instance: m });\n return m;\n };\n\n /**\n * Creates an UnixTime message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof UnixTime\n * @static\n * @param {Object.} d Plain object\n * @returns {UnixTime} UnixTime\n */\n UnixTime.fromObject = function fromObject(d) {\n if (d instanceof $root.UnixTime)\n return d;\n var m = new $root.UnixTime();\n if (d.Seconds != null) {\n if ($util.Long)\n (m.Seconds = $util.Long.fromValue(d.Seconds)).unsigned = false;\n else if (typeof d.Seconds === \"string\")\n m.Seconds = parseInt(d.Seconds, 10);\n else if (typeof d.Seconds === \"number\")\n m.Seconds = d.Seconds;\n else if (typeof d.Seconds === \"object\")\n m.Seconds = new $util.LongBits(d.Seconds.low >>> 0, d.Seconds.high >>> 0).toNumber();\n }\n if (d.FractionalNanoseconds != null) {\n m.FractionalNanoseconds = d.FractionalNanoseconds >>> 0;\n }\n return m;\n };\n\n /**\n * Creates a plain object from an UnixTime message. Also converts values to other types if specified.\n * @function toObject\n * @memberof UnixTime\n * @static\n * @param {UnixTime} m UnixTime\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n UnixTime.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.defaults) {\n if ($util.Long) {\n var n = new $util.Long(0, 0, false);\n d.Seconds = o.longs === String ? n.toString() : o.longs === Number ? n.toNumber() : n;\n } else\n d.Seconds = o.longs === String ? \"0\" : 0;\n d.FractionalNanoseconds = 0;\n }\n if (m.Seconds != null && m.hasOwnProperty(\"Seconds\")) {\n if (typeof m.Seconds === \"number\")\n d.Seconds = o.longs === String ? String(m.Seconds) : m.Seconds;\n else\n d.Seconds = o.longs === String ? $util.Long.prototype.toString.call(m.Seconds) : o.longs === Number ? new $util.LongBits(m.Seconds.low >>> 0, m.Seconds.high >>> 0).toNumber() : m.Seconds;\n }\n if (m.FractionalNanoseconds != null && m.hasOwnProperty(\"FractionalNanoseconds\")) {\n d.FractionalNanoseconds = m.FractionalNanoseconds;\n }\n return d;\n };\n\n /**\n * Converts this UnixTime to JSON.\n * @function toJSON\n * @memberof UnixTime\n * @instance\n * @returns {Object.} JSON object\n */\n UnixTime.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return UnixTime;\n})();\n\nexport const Metadata = $root.Metadata = (() => {\n\n /**\n * Properties of a Metadata.\n * @exports IMetadata\n * @interface IMetadata\n * @property {string|null} [MimeType] Metadata MimeType\n */\n\n /**\n * Constructs a new Metadata.\n * @exports Metadata\n * @classdesc Represents a Metadata.\n * @implements IMetadata\n * @constructor\n * @param {IMetadata=} [p] Properties to set\n */\n function Metadata(p) {\n if (p)\n for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)\n if (p[ks[i]] != null)\n this[ks[i]] = p[ks[i]];\n }\n\n /**\n * Metadata MimeType.\n * @member {string} MimeType\n * @memberof Metadata\n * @instance\n */\n Metadata.prototype.MimeType = \"\";\n\n /**\n * Encodes the specified Metadata message. Does not implicitly {@link Metadata.verify|verify} messages.\n * @function encode\n * @memberof Metadata\n * @static\n * @param {IMetadata} m Metadata message or plain object to encode\n * @param {$protobuf.Writer} [w] Writer to encode to\n * @returns {$protobuf.Writer} Writer\n */\n Metadata.encode = function encode(m, w) {\n if (!w)\n w = $Writer.create();\n if (m.MimeType != null && Object.hasOwnProperty.call(m, \"MimeType\"))\n w.uint32(10).string(m.MimeType);\n return w;\n };\n\n /**\n * Decodes a Metadata message from the specified reader or buffer.\n * @function decode\n * @memberof Metadata\n * @static\n * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from\n * @param {number} [l] Message length if known beforehand\n * @returns {Metadata} Metadata\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {$protobuf.util.ProtocolError} If required fields are missing\n */\n Metadata.decode = function decode(r, l) {\n if (!(r instanceof $Reader))\n r = $Reader.create(r);\n var c = l === undefined ? r.len : r.pos + l, m = new $root.Metadata();\n while (r.pos < c) {\n var t = r.uint32();\n switch (t >>> 3) {\n case 1:\n m.MimeType = r.string();\n break;\n default:\n r.skipType(t & 7);\n break;\n }\n }\n return m;\n };\n\n /**\n * Creates a Metadata message from a plain object. Also converts values to their respective internal types.\n * @function fromObject\n * @memberof Metadata\n * @static\n * @param {Object.} d Plain object\n * @returns {Metadata} Metadata\n */\n Metadata.fromObject = function fromObject(d) {\n if (d instanceof $root.Metadata)\n return d;\n var m = new $root.Metadata();\n if (d.MimeType != null) {\n m.MimeType = String(d.MimeType);\n }\n return m;\n };\n\n /**\n * Creates a plain object from a Metadata message. Also converts values to other types if specified.\n * @function toObject\n * @memberof Metadata\n * @static\n * @param {Metadata} m Metadata\n * @param {$protobuf.IConversionOptions} [o] Conversion options\n * @returns {Object.} Plain object\n */\n Metadata.toObject = function toObject(m, o) {\n if (!o)\n o = {};\n var d = {};\n if (o.defaults) {\n d.MimeType = \"\";\n }\n if (m.MimeType != null && m.hasOwnProperty(\"MimeType\")) {\n d.MimeType = m.MimeType;\n }\n return d;\n };\n\n /**\n * Converts this Metadata to JSON.\n * @function toJSON\n * @memberof Metadata\n * @instance\n * @returns {Object.} JSON object\n */\n Metadata.prototype.toJSON = function toJSON() {\n return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n };\n\n return Metadata;\n})();\n\nexport { $root as default };\n","// @ts-nocheck\n\n/**\n * This is file is shadowed by api.ts and only exists so JS could import it to\n * refer to types without encountering runtime errors\n * @see https://github.com/microsoft/TypeScript/issues/41825\n */\n\nimport { Data } from \"../gen/unixfs.js\"\nexport const NodeType = Data.DataType\n","import * as PB from \"@ipld/dag-pb\"\nimport * as UnixFS from \"./unixfs.js\"\nimport { NodeType } from \"./unixfs.js\"\nimport { Data } from \"../gen/unixfs.js\"\n\nexport * from \"./unixfs.js\"\n\n/** @type {ReadonlyArray} */\nconst EMPTY = Object.freeze([])\nconst EMPTY_BUFFER = new Uint8Array(0)\n\nconst BLANK = Object.freeze({})\nexport const DEFAULT_FILE_MODE = parseInt(\"0644\", 8)\nexport const DEFAULT_DIRECTORY_MODE = parseInt(\"0755\", 8)\n\nexport const code = PB.code\nexport const name = \"UnixFS\"\n\n/**\n * @param {UnixFS.IData} data\n * @param {ReadonlyArray} links\n */\nconst encodePB = (data, links) => {\n Object(globalThis).debug && console.log({ data, links })\n\n return PB.encode(\n // We run through prepare as links need to be sorted by name which it will\n // do.\n PB.prepare({\n Data: Data.encode(data).finish(),\n // We can cast to mutable array as we know no mutation occurs there\n Links:\n /** @type {PB.PBLink[]} */ (links),\n })\n )\n}\n\n/**\n * @param {Uint8Array} content\n * @returns {UnixFS.Raw}\n */\nexport const createRaw = content => ({\n type: NodeType.Raw,\n content,\n})\n\n/**\n * @param {UnixFS.Metadata} [metadata]\n * @returns {UnixFS.SimpleFile}\n */\nexport const createEmptyFile = metadata =>\n createSimpleFile(EMPTY_BUFFER, metadata)\n\n/**\n * @param {Uint8Array} content\n * @param {UnixFS.Metadata} [metadata]\n * @returns {UnixFS.SimpleFile}\n */\nexport const createSimpleFile = (content, metadata) => ({\n type: NodeType.File,\n layout: \"simple\",\n content,\n metadata: decodeMetadata(metadata),\n})\n\n/**\n * @param {Uint8Array} content\n * @returns {UnixFS.FileChunk}\n */\nexport const createFileChunk = content => ({\n type: NodeType.File,\n layout: \"simple\",\n content,\n})\n\n/**\n * @param {UnixFS.FileLink[]} parts\n * @param {UnixFS.Metadata} [metadata]\n * @returns {UnixFS.AdvancedFile}\n */\nexport const createAdvancedFile = (parts, metadata) => ({\n type: NodeType.File,\n layout: \"advanced\",\n parts,\n metadata: decodeMetadata(metadata),\n})\n\n/**\n * @param {UnixFS.FileLink[]} parts\n * @returns {UnixFS.FileShard}\n */\nexport const createFileShard = parts => ({\n type: NodeType.File,\n layout: \"advanced\",\n parts,\n})\n\n/**\n * @deprecated\n * @param {Uint8Array} content\n * @param {UnixFS.FileLink[]} parts\n * @param {UnixFS.Metadata} [metadata]\n * @returns {UnixFS.ComplexFile}\n */\nexport const createComplexFile = (content, parts, metadata) => ({\n type: NodeType.File,\n layout: \"complex\",\n content,\n parts,\n metadata: decodeMetadata(metadata),\n})\n\n/**\n * @param {UnixFS.DirectoryEntryLink[]} entries\n * @param {UnixFS.Metadata} [metadata]\n * @returns {UnixFS.FlatDirectory}\n */\nexport const createFlatDirectory = (entries, metadata) => ({\n type: NodeType.Directory,\n metadata: decodeMetadata(metadata),\n entries,\n})\n\n/**\n * @param {UnixFS.ShardedDirectoryLink[]} entries\n * @param {Uint8Array} bitfield\n * @param {number} fanout\n * @param {number} hashType\n * @param {UnixFS.Metadata} [metadata]\n * @returns {UnixFS.ShardedDirectory}\n */\nexport const createShardedDirectory = (\n entries,\n bitfield,\n fanout,\n hashType,\n metadata = BLANK\n) => ({\n type: NodeType.HAMTShard,\n bitfield,\n fanout: readFanout(fanout),\n hashType: readInt(hashType),\n entries,\n metadata: decodeMetadata(metadata),\n})\n\n/**\n * @param {UnixFS.ShardedDirectoryLink[]} entries\n * @param {Uint8Array} bitfield\n * @param {number} fanout\n * @param {number} hashType\n * @returns {UnixFS.DirectoryShard}\n */\nexport const createDirectoryShard = (entries, bitfield, fanout, hashType) => ({\n type: NodeType.HAMTShard,\n bitfield,\n fanout: readFanout(fanout),\n hashType: readInt(hashType),\n entries,\n})\n\n/**\n *\n * @param {Uint8Array} content\n * @returns {UnixFS.ByteView}\n */\nexport const encodeRaw = content =>\n encodePB(\n {\n Type: NodeType.Raw,\n // TODO:\n Data: content.byteLength > 0 ? content : undefined,\n filesize: content.byteLength,\n // @ts-ignore\n blocksizes: EMPTY,\n },\n []\n )\n\n/**\n * @param {UnixFS.File|UnixFS.FileChunk|UnixFS.FileShard} node\n * @param {boolean} [ignoreMetadata]\n * @returns {UnixFS.ByteView}\n */\nexport const encodeFile = (node, ignoreMetadata = false) => {\n const metadata = ignoreMetadata ? BLANK : Object(node).metadata\n switch (node.layout) {\n case \"simple\":\n return encodeSimpleFile(node.content, metadata)\n case \"advanced\":\n return encodeAdvancedFile(node.parts, metadata)\n case \"complex\":\n return encodeComplexFile(node.content, node.parts, metadata)\n default:\n throw new TypeError(\n `File with unknown layout \"${Object(node).layout}\" was passed`\n )\n }\n}\n\n/**\n * @param {Uint8Array} content\n * @returns {UnixFS.ByteView}\n */\nexport const encodeFileChunk = content => encodeSimpleFile(content, BLANK)\n\n/**\n * @param {ReadonlyArray} parts\n * @returns {UnixFS.ByteView}\n */\nexport const encodeFileShard = parts =>\n encodePB(\n {\n Type: NodeType.File,\n blocksizes: parts.map(contentByteLength),\n filesize: cumulativeContentByteLength(parts),\n },\n parts.map(encodeLink)\n )\n\n/**\n * @param {ReadonlyArray} parts\n * @param {UnixFS.Metadata} [metadata]\n * @returns {UnixFS.ByteView}\n */\nexport const encodeAdvancedFile = (parts, metadata = BLANK) =>\n encodePB(\n {\n Type: NodeType.File,\n blocksizes: parts.map(contentByteLength),\n filesize: cumulativeContentByteLength(parts),\n\n ...encodeMetadata(metadata),\n },\n parts.map(encodeLink)\n )\n\n/**\n * @param {UnixFS.DAGLink} dag\n * @returns {UnixFS.PBLink}\n */\nexport const encodeLink = dag => ({\n Name: \"\",\n Tsize: dag.dagByteLength,\n // @ts-ignore - @see https://github.com/multiformats/js-multiformats/pull/161\n Hash: dag.cid,\n})\n\n/**\n * @param {Uint8Array} content\n * @param {UnixFS.Metadata} [metadata]\n * @returns {UnixFS.ByteView}\n */\n\nexport const encodeSimpleFile = (content, metadata = BLANK) =>\n encodePB(\n {\n Type: NodeType.File,\n // adding empty file to both go-ipfs and js-ipfs produces block in\n // which `Data` is omitted but filesize and blocksizes are present.\n // For the sake of hash consistency we do the same.\n Data: content.byteLength > 0 ? content : undefined,\n filesize: content.byteLength,\n blocksizes: [],\n ...encodeMetadata(metadata),\n },\n []\n )\n\n/**\n *\n * @param {Uint8Array} content\n * @param {ReadonlyArray} parts\n * @param {UnixFS.Metadata} [metadata]\n * @returns {UnixFS.ByteView}\n */\nexport const encodeComplexFile = (content, parts, metadata = BLANK) =>\n encodePB(\n {\n Type: NodeType.File,\n Data: content,\n filesize: content.byteLength + cumulativeContentByteLength(parts),\n blocksizes: parts.map(contentByteLength),\n },\n parts.map(encodeLink)\n )\n\n/**\n * @param {UnixFS.FlatDirectory} node\n * @returns {UnixFS.ByteView}\n */\nexport const encodeDirectory = node =>\n encodePB(\n {\n Type: node.type,\n ...encodeDirectoryMetadata(node.metadata || BLANK),\n },\n node.entries.map(encodeNamedLink)\n )\n\n/**\n * @param {UnixFS.ShardedDirectory|UnixFS.DirectoryShard} node\n * @returns {UnixFS.ByteView}\n */\nexport const encodeHAMTShard = ({\n bitfield,\n fanout,\n hashType,\n entries,\n metadata = BLANK,\n}) =>\n encodePB(\n {\n Type: NodeType.HAMTShard,\n Data: bitfield.byteLength > 0 ? bitfield : undefined,\n fanout: readFanout(fanout),\n hashType: readInt(hashType),\n\n ...encodeDirectoryMetadata(metadata),\n },\n entries.map(encodeNamedLink)\n )\n\n/**\n * @param {number} n\n * @returns {number}\n */\nconst readFanout = n => {\n if (Math.log2(n) % 1 === 0) {\n return n\n } else {\n throw new TypeError(\n `Expected hamt size to be a power of two instead got ${n}`\n )\n }\n}\n\n/**\n * @param {number} n\n * @returns {number}\n */\n\nconst readInt = n => {\n if (Number.isInteger(n)) {\n return n\n } else {\n throw new TypeError(`Expected an integer value instead got ${n}`)\n }\n}\n\n/**\n * @param {Uint8Array} bytes\n */\nconst readData = bytes => (bytes.byteLength > 0 ? bytes : undefined)\n\n/**\n * @param {Uint8Array} path\n * @param {UnixFS.Metadata} [metadata]\n * @returns {UnixFS.Symlink}\n */\nexport const createSymlink = (path, metadata = BLANK) => ({\n type: NodeType.Symlink,\n content: path,\n metadata: decodeMetadata(metadata),\n})\n\n/**\n * @param {UnixFS.Symlink} node\n * @param {boolean} [ignoreMetadata]\n * @returns {UnixFS.ByteView}\n */\nexport const encodeSymlink = (node, ignoreMetadata = false) => {\n const metadata = ignoreMetadata ? BLANK : Object(node).metadata\n // We do not include filesize on symlinks because that is what go-ipfs does\n // when doing `ipfs add mysymlink`. js-ipfs on the other hand seems to store\n // it, here we choose to follow go-ipfs\n // @see https://explore.ipld.io/#/explore/QmPZ1CTc5fYErTH2XXDGrfsPsHicYXtkZeVojGycwAfm3v\n // @see https://github.com/ipfs/js-ipfs-unixfs/issues/195\n return encodePB(\n {\n Type: NodeType.Symlink,\n Data: node.content,\n ...encodeMetadata(metadata || BLANK),\n },\n []\n )\n}\n\n/**\n * @template {UnixFS.Node} T\n * @param {T} node\n * @param {boolean} root\n */\nexport const encode = (node, root = true) => {\n switch (node.type) {\n case NodeType.Raw:\n return encodeRaw(node.content)\n case NodeType.File:\n return encodeFile(node)\n case NodeType.Directory:\n return encodeDirectory(node)\n case NodeType.HAMTShard:\n return encodeHAMTShard(node)\n case NodeType.Symlink:\n return encodeSymlink(node)\n default:\n throw new Error(`Unknown node type ${Object(node).type}`)\n }\n}\n\n/**\n * @param {UnixFS.ByteView} bytes\n * @returns {UnixFS.Node}\n */\nexport const decode = bytes => {\n const pb = PB.decode(bytes)\n const message = Data.decode(/** @type {Uint8Array} */ (pb.Data))\n\n const {\n Type: type,\n Data: data,\n mtime,\n mode,\n blocksizes,\n ...rest\n } = Data.toObject(message, {\n defaults: false,\n arrays: true,\n longs: Number,\n objects: false,\n })\n const metadata = {\n ...(mode && { mode }),\n ...decodeMtime(mtime),\n }\n /** @type {UnixFS.PBLink[]} */\n const links = pb.Links\n\n switch (message.Type) {\n case NodeType.Raw:\n return createRaw(data)\n case NodeType.File:\n if (links.length === 0) {\n return new SimpleFileView(data, metadata)\n } else if (data.byteLength === 0) {\n return new AdvancedFileView(\n decodeFileLinks(rest.blocksizes, links),\n metadata\n )\n } else {\n return new ComplexFileView(\n data,\n decodeFileLinks(rest.blocksizes, links),\n metadata\n )\n }\n case NodeType.Directory:\n return createFlatDirectory(decodeDirectoryLinks(links), metadata)\n case NodeType.HAMTShard:\n return createShardedDirectory(\n decodeDirectoryLinks(links),\n data || EMPTY_BUFFER,\n rest.fanout,\n rest.hashType,\n metadata\n )\n case NodeType.Symlink:\n return createSymlink(data, metadata)\n default:\n throw new TypeError(`Unsupported node type ${message.Type}`)\n }\n}\n\n/**\n * @param {UnixFS.UnixTime|undefined} mtime\n */\nconst decodeMtime = mtime =>\n mtime == null\n ? undefined\n : {\n mtime: { secs: mtime.Seconds, nsecs: mtime.FractionalNanoseconds || 0 },\n }\n\n/**\n * @param {NodeType} type\n * @param {number[]|undefined} blocksizes\n */\nconst decodeBlocksizes = (type, blocksizes) => {\n switch (type) {\n case NodeType.File:\n return blocksizes && blocksizes.length > 0 ? { blocksizes } : undefined\n default:\n return undefined\n }\n}\n\n/**\n *\n * @param {number[]} blocksizes\n * @param {UnixFS.PBLink[]} links\n * @returns {UnixFS.FileLink[]}\n */\n\nconst decodeFileLinks = (blocksizes, links) => {\n const parts = []\n const length = blocksizes.length\n let n = 0\n while (n < length) {\n parts.push(\n /** @type {UnixFS.FileLink} */ ({\n cid: links[n].Hash,\n dagByteLength: links[n].Tsize || 0,\n contentByteLength: blocksizes[n],\n })\n )\n }\n return parts\n}\n\n/**\n * @param {UnixFS.PBLink[]} links\n * @returns {UnixFS.DirectoryEntryLink[]}\n */\nconst decodeDirectoryLinks = links =>\n links.map(\n link =>\n /** @type {UnixFS.DirectoryEntryLink} */ ({\n cid: link.Hash,\n name: link.Name || \"\",\n dagByteLength: link.Tsize || 0,\n })\n )\n\n/**\n * @param {ReadonlyArray} links\n * @returns {number}\n */\nexport const cumulativeContentByteLength = links =>\n links.reduce((size, link) => size + link.contentByteLength, 0)\n\n/**\n * @param {Uint8Array} root\n * @param {ReadonlyArray} links\n * @returns {number}\n */\nexport const cumulativeDagByteLength = (root, links) =>\n links.reduce((size, link) => size + link.dagByteLength, root.byteLength)\n\n/**\n *\n * @param {UnixFS.FileLink} link\n */\nconst contentByteLength = link => link.contentByteLength\n\n/**\n * @param {UnixFS.NamedDAGLink} link\n * @returns {UnixFS.PBLink}\n */\nconst encodeNamedLink = ({ name, dagByteLength, cid }) => ({\n Name: name,\n Tsize: dagByteLength,\n Hash: cid,\n})\n\n/**\n * @param {UnixFS.Metadata} metadata\n */\nexport const encodeDirectoryMetadata = metadata =>\n encodeMetadata(metadata, DEFAULT_DIRECTORY_MODE)\n\n/**\n * @param {UnixFS.Metadata} metadata\n * @param {UnixFS.Mode} defaultMode\n */\nexport const encodeMetadata = (\n { mode, mtime },\n defaultMode = DEFAULT_FILE_MODE\n) => ({\n mode: mode != null ? encodeMode(mode, defaultMode) : undefined,\n mtime: mtime != null ? encodeMTime(mtime) : undefined,\n})\n\n/**\n * @param {UnixFS.Metadata} [data]\n */\nexport const decodeMetadata = data =>\n data == null\n ? BLANK\n : {\n ...(data.mode == null ? undefined : { mode: decodeMode(data.mode) }),\n ...(data.mtime == null ? undefined : { mtime: data.mtime }),\n }\n\n/**\n * @param {UnixFS.MTime} mtime\n */\nconst encodeMTime = mtime => {\n return mtime == null\n ? undefined\n : mtime.nsecs !== 0\n ? { Seconds: mtime.secs, FractionalNanoseconds: mtime.nsecs }\n : { Seconds: mtime.secs }\n}\n\n/**\n * @param {number} specifiedMode\n * @param {number} defaultMode\n */\nexport const encodeMode = (specifiedMode, defaultMode) => {\n const mode = specifiedMode == null ? undefined : decodeMode(specifiedMode)\n return mode === defaultMode || mode == null ? undefined : mode\n}\n\n/**\n * @param {UnixFS.Mode} mode\n * @returns {UnixFS.Mode}\n */\nconst decodeMode = mode => (mode & 0xfff) | (mode & 0xfffff000)\n\n/**\n * @param {{content?: Uint8Array, parts?: ReadonlyArray, metadata?: UnixFS.Metadata }} node\n * @returns {UnixFS.SimpleFile|UnixFS.AdvancedFile|UnixFS.ComplexFile}\n */\nexport const matchFile = ({\n content = EMPTY_BUFFER,\n parts = EMPTY,\n metadata = BLANK,\n ...rest\n}) => {\n if (parts.length === 0) {\n return new SimpleFileView(content, metadata)\n } else if (content.byteLength === 0) {\n return new AdvancedFileView(parts, metadata)\n } else {\n return new ComplexFileView(content, parts, metadata)\n }\n}\n\n/**\n * @implements {UnixFS.SimpleFile}\n */\nclass SimpleFileView {\n /**\n * @param {Uint8Array} content\n * @param {UnixFS.Metadata} metadata\n */\n constructor(content, metadata) {\n this.content = content\n this.metadata = metadata\n /**\n * @readonly\n * @type {\"simple\"}\n */\n this.layout = \"simple\"\n /**\n * @readonly\n * @type {NodeType.File}\n */\n this.type = NodeType.File\n }\n\n get filesize() {\n return this.content.byteLength\n }\n\n encode() {\n return encodeSimpleFile(this.content, this.metadata)\n }\n}\n\n/**\n * @implements {UnixFS.AdvancedFile}\n */\nclass AdvancedFileView {\n /**\n * @param {ReadonlyArray} parts\n * @param {UnixFS.Metadata} metadata\n */\n constructor(parts, metadata) {\n this.parts = parts\n this.metadata = metadata\n }\n /** @type {\"advanced\"} */\n get layout() {\n return \"advanced\"\n }\n\n /**\n * @returns {NodeType.File}\n */\n get type() {\n return NodeType.File\n }\n get fileSize() {\n return cumulativeContentByteLength(this.parts)\n }\n get blockSizes() {\n return this.parts.map(contentByteLength)\n }\n\n encode() {\n return encodeAdvancedFile(this.parts, this.metadata)\n }\n}\n\n/**\n * @implements {UnixFS.ComplexFile}\n */\nclass ComplexFileView {\n /**\n * @param {Uint8Array} content\n * @param {ReadonlyArray} parts\n * @param {UnixFS.Metadata} metadata\n */\n constructor(content, parts, metadata) {\n this.content = content\n this.parts = parts\n this.metadata = metadata\n }\n /** @type {\"complex\"} */\n get layout() {\n return \"complex\"\n }\n\n /**\n * @returns {NodeType.File}\n */\n get type() {\n return NodeType.File\n }\n get fileSize() {\n return this.content.byteLength + cumulativeContentByteLength(this.parts)\n }\n get blockSizes() {\n return this.parts.map(contentByteLength)\n }\n\n encode() {\n return encodeComplexFile(this.content, this.parts, this.metadata)\n }\n}\n\n/**\n * @param {UnixFS.File|UnixFS.Raw|UnixFS.FileChunk|UnixFS.FileShard|UnixFS.Symlink} node\n * @returns {number}\n */\nexport const filesize = node => {\n switch (node.type) {\n case NodeType.Raw:\n case NodeType.Symlink:\n return node.content.byteLength\n case NodeType.File:\n switch (node.layout) {\n case \"simple\":\n return node.content.byteLength\n case \"advanced\":\n return cumulativeContentByteLength(node.parts)\n case \"complex\":\n return (\n node.content.byteLength + cumulativeContentByteLength(node.parts)\n )\n }\n default:\n return 0\n }\n}\n","import * as Task from \"./task.js\"\nexport * from \"./task.js\"\n\n/**\n * Turns a task (that never fails or sends messages) into an effect of it's\n * result.\n *\n * @template T\n * @param {Task.Task} task\n * @returns {Task.Effect}\n */\nexport const effect = function* (task) {\n const message = yield* task\n yield* send(message)\n}\n\n/**\n * Gets a handle to the task that invoked it. Useful when task needs to\n * suspend execution until some outside event occurs, in which case handle\n * can be used resume execution (see `suspend` code example for more details)\n *\n * @template T, M, X\n * @returns {Task.Task, never>}\n */\nexport function* current() {\n return /** @type {Task.Controller} */ (yield CURRENT)\n}\n\n/**\n * Suspends the current task (task that invokes it), which can then be\n * resumed from another task or an outside event (e.g. `setTimeout` callback)\n * by calling the `resume` with an task's handle.\n *\n * Calling this in almost all cases is preceeded by call to `current()` in\n * order to obtain a `handle` which can be passed to `resume` function\n * to resume the execution.\n *\n * Note: This task never fails, although it may never resume either. However\n * you can utilize `finally` block to do a necessary cleanup in case execution\n * is aborted.\n *\n * @example\n * ```js\n * import { current, suspend, resume } from \"actor\"\n * function * sleep(duration) {\n * // get a reference to this task so we can resume it.\n * const self = yield * current()\n * // resume this task when timeout fires\n * const id = setTimeout(() => resume(self), duration)\n * try {\n * // suspend this task nothing below this line will run until task is\n * // resumed.\n * yield * suspend()\n * } finally {\n * // if task is aborted finally block will still run which given you\n * // chance to cleanup.\n * clearTimeout(id)\n * }\n * }\n * ```\n *\n * @returns {Task.Task}\n */\nexport const suspend = function* () {\n yield SUSPEND\n}\n\n/**\n * Suspends execution for the given duration in milliseconds, after which\n * execution is resumed (unless it was aborted in the meantime).\n *\n * @example\n * ```js\n * function * demo() {\n * console.log(\"I'm going to take small nap\")\n * yield * sleep(200)\n * console.log(\"I am back to work\")\n * }\n * ```\n *\n * @param {number} [duration]\n * @returns {Task.Task}\n */\nexport function* sleep(duration = 0) {\n const task = yield* current()\n const id = setTimeout(enqueue, duration, task)\n\n try {\n yield* suspend()\n } finally {\n clearTimeout(id)\n }\n}\n\n/**\n * Provides equivalent of `await` in async functions. Specifically it takes\n * a value that you can `await` on (that is `Promise|T`) and suspends\n * execution until promise is settled. If promise succeeds execution is resumed\n * with `T` otherwise an error of type `X` is thrown (which is by default\n * `unknown` since promises do not encode error type).\n *\n * It is useful when you need to deal with potentially async set of operations\n * without having to check if thing is a promise at every step.\n *\n * Please note: This that execution is suspended even if given value is not a\n * promise, however scheduler will still resume it in the same tick of the event\n * loop after, just processing other scheduled tasks. This avoids problematic\n * race condititions that can otherwise occur when values are sometimes promises\n * and other times are not.\n *\n * @example\n * ```js\n * function * fetchJSON (url, options) {\n * const response = yield * wait(fetch(url, options))\n * const json = yield * wait(response.json())\n * return json\n * }\n * ```\n *\n * @template T, [X=unknown]\n * @param {Task.Await} input\n * @returns {Task.Task}\n */\nexport const wait = function* (input) {\n const task = yield* current()\n if (isAsync(input)) {\n let failed = false\n /** @type {unknown} */\n let output = undefined\n input.then(\n value => {\n failed = false\n output = value\n enqueue(task)\n },\n error => {\n failed = true\n output = error\n enqueue(task)\n }\n )\n\n yield* suspend()\n if (failed) {\n throw output\n } else {\n return /** @type {T} */ (output)\n }\n } else {\n // This may seem redundunt but it is not, by enqueuing this task we allow\n // scheduler to perform other queued tasks first. This way many race\n // conditions can be avoided when values are sometimes promises and other\n // times aren't.\n // Unlike `await` however this will resume in the same tick.\n main(wake(task))\n yield* suspend()\n return input\n }\n}\n\n/**\n * @template T, X, M\n * @param {Task.Controller} task\n * @returns {Task.Task}\n */\nfunction* wake(task) {\n enqueue(task)\n}\n\n/**\n * Checks if value value is a promise (or it's lookalike).\n *\n * @template T\n * @param {any} node\n * @returns {node is PromiseLike}\n */\n\nconst isAsync = node =>\n node != null &&\n typeof (/** @type {{then?:unknown}} */ (node).then) === \"function\"\n\n/**\n * Task that sends given message (or rather an effect producing this message).\n * Please note, that while you could use `yield message` instead, but you'd risk\n * having to deal with potential breaking changes if library internals change\n * in the future, which in fact may happen as anticipated improvements in\n * TS generator inference could enable replace need for `yield *`.\n *\n * @see https://github.com/microsoft/TypeScript/issues/43632\n *\n * @template T\n * @param {T} message\n * @returns {Task.Effect}\n */\nexport const send = function* (message) {\n yield /** @type {Task.Message} */ (message)\n}\n\n/**\n * Takes several effects and merges them into a single effect of tagged\n * variants so that their source could be identified via `type` field.\n *\n * @example\n * ```js\n * listen({\n * read: Task.effect(dbRead),\n * write: Task.effect(dbWrite)\n * })\n * ```\n *\n * @template {string} Tag\n * @template T\n * @param {{ [K in Tag]: Task.Effect }} source\n * @returns {Task.Effect>}\n */\nexport const listen = function* (source) {\n /** @type {Task.Fork>[]} */\n const forks = []\n for (const entry of Object.entries(source)) {\n const [name, effect] = /** @type {[Tag, Task.Effect]} */ (entry)\n if (effect !== NONE) {\n forks.push(yield* fork(tag(effect, name)))\n }\n }\n\n yield* group(forks)\n}\n\n/**\n * Takes several tasks and creates an effect of them all.\n *\n * @example\n * ```js\n * Task.effects([\n * dbRead,\n * dbWrite\n * ])\n * ```\n *\n * @template {string} Tag\n * @template T\n * @param {Task.Task[]} tasks\n * @returns {Task.Effect}\n */\n\nexport const effects = tasks =>\n tasks.length > 0 ? batch(tasks.map(effect)) : NONE\n\n/**\n * Takes several effects and combines them into a one.\n *\n * @template T\n * @param {Task.Effect[]} effects\n * @returns {Task.Effect}\n */\nexport function* batch(effects) {\n const forks = []\n for (const effect of effects) {\n forks.push(yield* fork(effect))\n }\n\n yield* group(forks)\n}\n\n/**\n * @template {string} Tag\n * @template T\n * @typedef {{type: Tag} & {[K in Tag]: T}} Tagged\n */\n/**\n * Tags an effect by boxing each event with an object that has `type` field\n * corresponding to given tag and same named field holding original message\n * e.g. given `nums` effect that produces numbers, `tag(nums, \"inc\")` would\n * create an effect that produces events like `{type:'inc', inc:1}`.\n *\n * @template {string} Tag\n * @template T, M, X\n * @param {Task.Task} effect\n * @param {Tag} tag\n * @returns {Task.Task>}\n */\nexport const tag = (effect, tag) =>\n // @ts-ignore\n effect === NONE\n ? NONE\n : effect instanceof Tagger\n ? new Tagger([...effect.tags, tag], effect.source)\n : new Tagger([tag], effect)\n\n/**\n * @template {string} Tag\n * @template Success, Failure, Message\n *\n * @implements {Task.Task>}\n * @implements {Task.Controller>}\n */\nclass Tagger {\n /**\n * @param {Task.Task} source\n * @param {string[]} tags\n */\n constructor(tags, source) {\n this.tags = tags\n this.source = source\n /** @type {Task.Controller} */\n this.controller\n }\n /* c8 ignore next 3 */\n [Symbol.iterator]() {\n if (!this.controller) {\n this.controller = this.source[Symbol.iterator]()\n }\n return this\n }\n /**\n * @param {Task.TaskState} state\n * @returns {Task.TaskState>}\n */\n box(state) {\n if (state.done) {\n return state\n } else {\n switch (state.value) {\n case SUSPEND:\n case CURRENT:\n return /** @type {Task.TaskState>} */ (\n state\n )\n default: {\n // Instead of boxing result at each transform step we perform in-place\n // mutation as we know nothing else is accessing this value.\n const tagged = /** @type {{ done: false, value: any }} */ (state)\n let { value } = tagged\n for (const tag of this.tags) {\n value = withTag(tag, value)\n }\n tagged.value = value\n return tagged\n }\n }\n }\n }\n /**\n *\n * @param {Task.Instruction} instruction\n */\n next(instruction) {\n return this.box(this.controller.next(instruction))\n }\n /**\n *\n * @param {Failure} error\n */\n throw(error) {\n return this.box(this.controller.throw(error))\n }\n /**\n * @param {Success} value\n */\n return(value) {\n return this.box(this.controller.return(value))\n }\n\n get [Symbol.toStringTag]() {\n return \"TaggedEffect\"\n }\n}\n\n/**\n * Returns empty `Effect`, that is produces no messages. Kind of like `[]` or\n * `\"\"` but for effects.\n *\n * @type {() => Task.Effect}\n */\nexport const none = () => NONE\n\n/**\n * Takes iterable of tasks and runs them concurrently, returning array of\n * results in an order of tasks (not the order of completion). If any of the\n * tasks fail all the rest are aborted and error is throw into calling task.\n *\n * > This is basically equivalent of `Promise.all` except cancelation logic\n * because tasks unlike promises can be cancelled.\n *\n * @template T, X\n * @param {Iterable>} tasks\n * @returns {Task.Task}\n */\nexport const all = function* (tasks) {\n const self = yield* current()\n\n /** @type {(id:number) => (value:T) => void} */\n const succeed = id => value => {\n delete forks[id]\n results[id] = value\n count -= 1\n if (count === 0) {\n enqueue(self)\n }\n }\n\n /** @type {(error:X) => void} */\n const fail = error => {\n for (const handle of forks) {\n if (handle) {\n enqueue(abort(handle, error))\n }\n }\n\n enqueue(abort(self, error))\n }\n\n /** @type {Task.Fork[]} */\n let forks = []\n let count = 0\n for (const task of tasks) {\n forks.push(yield* fork(then(task, succeed(count++), fail)))\n }\n const results = new Array(count)\n\n if (count > 0) {\n yield* suspend()\n }\n\n return results\n}\n\n/**\n * @template {string} Tag\n * @template T\n * @param {Tag} tag\n * @param {Task.Message} value\n */\nconst withTag = (tag, value) =>\n /** @type {Tagged} */\n ({ type: tag, [tag]: value })\n\n/**\n * Kind of like promise.then which is handy when you want to extract result\n * from the given task from the outside.\n *\n * @template T, U, X, M\n * @param {Task.Task} task\n * @param {(value:T) => U} resolve\n * @param {(error:X) => U} reject\n * @returns {Task.Task}\n */\nexport function* then(task, resolve, reject) {\n try {\n return resolve(yield* task)\n } catch (error) {\n return reject(/** @type {X} */ (error))\n }\n}\n\n// Special control instructions recognized by a scheduler.\nconst CURRENT = Symbol(\"current\")\nconst SUSPEND = Symbol(\"suspend\")\n/** @typedef {typeof SUSPEND|typeof CURRENT} Control */\n\n/**\n * @template M\n * @param {Task.Instruction} value\n * @returns {value is M}\n */\nexport const isMessage = value => {\n switch (value) {\n case SUSPEND:\n case CURRENT:\n return false\n default:\n return true\n }\n}\n\n/**\n * @template M\n * @param {Task.Instruction} value\n * @returns {value is Control}\n */\nexport const isInstruction = value => !isMessage(value)\n\n/**\n * @template T, X, M\n * @implements {Task.TaskGroup}\n */\nclass Group {\n /**\n * @template T, X, M\n * @param {Task.Controller|Task.Fork} member\n * @returns {Task.Group}\n */\n static of(member) {\n return (\n /** @type {{group?:Task.TaskGroup}} */ (member).group || MAIN\n )\n }\n\n /**\n * @template T, X, M\n * @param {(Task.Controller|Task.Fork) & {group?:Task.TaskGroup}} member\n * @param {Task.TaskGroup} group\n */\n static enqueue(member, group) {\n member.group = group\n group.stack.active.push(member)\n }\n /**\n * @param {Task.Controller} driver\n * @param {Task.Controller[]} [active]\n * @param {Set>} [idle]\n * @param {Task.Stack} [stack]\n */\n constructor(\n driver,\n active = [],\n idle = new Set(),\n stack = new Stack(active, idle)\n ) {\n this.driver = driver\n this.parent = Group.of(driver)\n this.stack = stack\n this.id = ++ID\n }\n}\n\n/**\n * @template T, X, M\n * @implements {Task.Main}\n */\nclass Main {\n constructor() {\n this.status = IDLE\n this.stack = new Stack()\n this.id = /** @type {0} */ (0)\n }\n}\n\n/**\n * @template T, X, M\n */\nclass Stack {\n /**\n * @param {Task.Controller[]} [active]\n * @param {Set>} [idle]\n */\n constructor(active = [], idle = new Set()) {\n this.active = active\n this.idle = idle\n }\n\n /**\n *\n * @param {Task.Stack} stack\n * @returns\n */\n static size({ active, idle }) {\n return active.length + idle.size\n }\n}\n\n/**\n * Starts a main task.\n *\n * @param {Task.Task} task\n */\nexport const main = task => enqueue(task[Symbol.iterator]())\n\n/**\n * @template T, X, M\n * @param {Task.Controller} task\n */\nconst enqueue = task => {\n let group = Group.of(task)\n group.stack.active.push(task)\n group.stack.idle.delete(task)\n\n // then walk up the group chain and unblock their driver tasks.\n while (group.parent) {\n const { idle, active } = group.parent.stack\n if (idle.has(group.driver)) {\n idle.delete(group.driver)\n active.push(group.driver)\n } else {\n // if driver was not blocked it must have been unblocked by\n // other task so stop there.\n break\n }\n\n group = group.parent\n }\n\n if (MAIN.status === IDLE) {\n MAIN.status = ACTIVE\n while (true) {\n try {\n for (const _message of step(MAIN)) {\n }\n MAIN.status = IDLE\n break\n } catch (_error) {\n // Top level task may crash and throw an error, but given this is a main\n // group we do not want to interupt other unrelated tasks, which is why\n // we discard the error and the task that caused it.\n MAIN.stack.active.shift()\n }\n }\n }\n}\n\n/**\n * @template T, X, M\n * @param {Task.Controller} task\n */\nexport const resume = task => enqueue(task)\n\n/**\n * @template T, X, M\n * @param {Task.Group} group\n */\n\nconst step = function* (group) {\n const { active } = group.stack\n let task = active[0]\n group.stack.idle.delete(task)\n while (task) {\n /** @type {Task.TaskState} */\n let state = INIT\n // Keep processing insturctions until task is done, it send suspend request\n // or it's has been removed from the active queue.\n // ⚠️ Group changes require extra care so please make sure to understand\n // the detail here. It occurs when spawned task(s) are joined into a group\n // which will change the task driver, that is when `task === active[0]` will\n // became false and need to to drop the task immediately otherwise race\n // condition will occur due to task been driven by multiple concurrent\n // schedulers.\n loop: while (!state.done && task === active[0]) {\n const instruction = state.value\n switch (instruction) {\n // if task is suspended we add it to the idle list and break the loop\n // to move to a next task.\n case SUSPEND:\n group.stack.idle.add(task)\n break loop\n // if task requested a context (which is usually to suspend itself)\n // pass back a task reference and continue.\n case CURRENT:\n state = task.next(task)\n break\n default:\n // otherwise task sent a message which we yield to the driver and\n // continue\n state = task.next(\n yield /** @type {M & Task.Message}*/ (instruction)\n )\n break\n }\n }\n\n // If task is complete, or got suspended we move to a next task\n active.shift()\n task = active[0]\n group.stack.idle.delete(task)\n }\n}\n\n/**\n * Executes given task concurrently with a current task (task that spawned it).\n * Spawned task is detached from the task that spawned it and it can outlive it\n * and / or fail without affecting a task that spawned it. If you need to wait\n * on concurrent task completion consider using `fork` instead which can be\n * later `joined`. If you just want a to block on task execution you can just\n * `yield* work()` directly instead.\n *\n * @param {Task.Task} task\n * @returns {Task.Task}\n */\nexport function* spawn(task) {\n main(task)\n}\n\n/**\n * Executes given task concurrently with current task (the task that initiated\n * fork). Froked task is detached from the task that created it and it can\n * outlive it and / or fail without affecting it. You do however get a handle\n * for the fork which could be used to `join` the task, in which case `joining`\n * task will block until fork finishes execution.\n *\n * This is also a primary interface for executing tasks from the outside of the\n * task context. Function returns `Fork` which implements `Promise` interface\n * so it could be awaited. Please note that calling `fork` does not really do\n * anything, it lazily starts execution when you either `await fork(work())`\n * from arbitray context or `yield* fork(work())` in anothe task context.\n *\n * @template T, X, M\n * @param {Task.Task} task\n * @param {Task.ForkOptions} [options]\n * @returns {Task.Fork}\n */\nexport const fork = (task, options) => new Fork(task, options)\n\n/**\n * Exits task succesfully with a given return value.\n *\n * @template T, M, X\n * @param {Task.Controller} handle\n * @param {T} value\n * @returns {Task.Task}\n */\nexport const exit = (handle, value) => conclude(handle, { ok: true, value })\n\n/**\n * Terminates task execution execution. Only takes task that produces no\n * result, if your task has non `void` return type you should use `exit` instead.\n *\n * @template M, X\n * @param {Task.Controller} handle\n */\nexport const terminate = handle =>\n conclude(handle, { ok: true, value: undefined })\n\n/**\n * Aborts given task with an error. Task error type should match provided error.\n *\n * @template T, M, X\n * @param {Task.Controller} handle\n * @param {X} [error]\n */\nexport const abort = (handle, error) => conclude(handle, { ok: false, error })\n\n/**\n * Aborts given task with an given error.\n *\n * @template T, M, X\n * @param {Task.Controller} handle\n * @param {Task.Result} result\n * @returns {Task.Task & Task.Controller}\n */\nfunction* conclude(handle, result) {\n try {\n const task = handle\n const state = result.ok\n ? task.return(result.value)\n : task.throw(result.error)\n\n if (!state.done) {\n if (state.value === SUSPEND) {\n const { idle } = Group.of(task).stack\n idle.add(task)\n } else {\n enqueue(task)\n }\n }\n } catch (error) {}\n}\n\n/**\n * Groups multiple forks togather and joins joins them with current task.\n *\n * @template T, X, M\n * @param {Task.Fork[]} forks\n * @returns {Task.Task}\n */\nexport function* group(forks) {\n // Abort eraly if there'se no work todo.\n if (forks.length === 0) return\n\n const self = yield* current()\n /** @type {Task.TaskGroup} */\n const group = new Group(self)\n /** @type {Task.Failure|null} */\n let failure = null\n\n for (const fork of forks) {\n const { result } = fork\n if (result) {\n if (!result.ok && !failure) {\n failure = result\n }\n continue\n }\n move(fork, group)\n }\n\n // Keep work looping until there is nom more work to be done\n try {\n if (failure) {\n throw failure.error\n }\n\n while (true) {\n yield* step(group)\n if (Stack.size(group.stack) > 0) {\n yield* suspend()\n } else {\n break\n }\n }\n } catch (error) {\n for (const task of group.stack.active) {\n yield* abort(task, error)\n }\n\n for (const task of group.stack.idle) {\n yield* abort(task, error)\n enqueue(task)\n }\n\n throw error\n }\n}\n\n/**\n * @template T, X, M\n * @param {Task.Fork} fork\n * @param {Task.TaskGroup} group\n */\nconst move = (fork, group) => {\n const from = Group.of(fork)\n if (from !== group) {\n const { active, idle } = from.stack\n const target = group.stack\n fork.group = group\n // If it is idle just move from one group to the other\n // and update the group task thinks it belongs to.\n if (idle.has(fork)) {\n idle.delete(fork)\n target.idle.add(fork)\n } else {\n const index = active.indexOf(fork)\n // If task is in the job queue, we move it to a target job queue. Moving\n // top task in the queue requires extra care so it does not end up\n // processed by two groups which would lead to race. For that reason\n // `step` loop checks for group changes on each turn.\n if (index >= 0) {\n active.splice(index, 1)\n target.active.push(fork)\n }\n // otherwise task is complete\n }\n }\n}\n\n/**\n * @template T, X, M\n * @param {Task.Fork} fork\n * @returns {Task.Task}\n */\nexport function* join(fork) {\n // If fork is still idle activate it.\n if (fork.status === IDLE) {\n yield* fork\n }\n\n if (!fork.result) {\n yield* group([fork])\n }\n\n const result = /** @type {Task.Result} */ (fork.result)\n if (result.ok) {\n return result.value\n } else {\n throw result.error\n }\n}\n\n/**\n * @template T, X\n * @implements {Task.Future}\n */\nclass Future {\n /**\n * @param {Task.StateHandler} handler\n */\n constructor(handler) {\n this.handler = handler\n /**\n * @abstract\n * @type {Task.Result|void}\n */\n this.result\n }\n /**\n * @type {Promise}\n */\n get promise() {\n const { result } = this\n const promise =\n result == null\n ? new Promise((succeed, fail) => {\n this.handler.onsuccess = succeed\n this.handler.onfailure = fail\n })\n : result.ok\n ? Promise.resolve(result.value)\n : Promise.reject(result.error)\n Object.defineProperty(this, \"promise\", { value: promise })\n return promise\n }\n\n /**\n * @template U, [E=never]\n * @param {((value:T) => U | PromiseLike)|undefined|null} [onresolve]\n * @param {((error:X) => E|PromiseLike)|undefined|null} [onreject]\n * @returns {Promise}\n */\n then(onresolve, onreject) {\n return this.activate().promise.then(onresolve, onreject)\n }\n /**\n * @template [U=never]\n * @param {(error:X) => U} onreject\n */\n catch(onreject) {\n return /** @type {Task.Future} */ (\n this.activate().promise.catch(onreject)\n )\n }\n /**\n * @param {() => void} onfinally\n * @returns {Task.Future}\n */\n finally(onfinally) {\n return /** @type {Task.Future} */ (\n this.activate().promise.finally(onfinally)\n )\n }\n /**\n * @abstract\n */\n /* c8 ignore next 3 */\n activate() {\n return this\n }\n}\n\n/**\n * @template T, X, M\n * @implements {Task.Fork}\n * @implements {Task.Controller}\n * @implements {Task.Task, never>}\n * @implements {Task.Future}\n * @extends {Future}\n */\nclass Fork extends Future {\n /**\n * @param {Task.Task} task\n * @param {Task.ForkOptions} [options]\n * @param {Task.StateHandler} [handler]\n * @param {Task.TaskState} [state]\n */\n constructor(task, options = BLANK, handler = {}, state = INIT) {\n super(handler)\n this.id = ++ID\n this.name = options.name || \"\"\n /** @type {Task.Task} */\n this.task = task\n this.state = state\n this.status = IDLE\n /** @type {Task.Result} */\n this.result\n this.handler = handler\n\n /** @type {Task.Controller} */\n this.controller\n }\n\n *resume() {\n resume(this)\n }\n\n /**\n * @returns {Task.Task}\n */\n join() {\n return join(this)\n }\n\n /**\n * @param {X} error\n */\n abort(error) {\n return abort(this, error)\n }\n /**\n * @param {T} value\n */\n exit(value) {\n return exit(this, value)\n }\n get [Symbol.toStringTag]() {\n return \"Fork\"\n }\n\n /**\n * @returns {Task.Controller, never, never>}\n */\n *[Symbol.iterator]() {\n return this.activate()\n }\n\n activate() {\n this.controller = this.task[Symbol.iterator]()\n this.status = ACTIVE\n enqueue(this)\n return this\n }\n\n /**\n * @private\n * @param {any} error\n * @returns {never}\n */\n panic(error) {\n this.result = { ok: false, error }\n this.status = FINISHED\n const { handler } = this\n if (handler.onfailure) {\n handler.onfailure(error)\n }\n\n throw error\n }\n\n /**\n * @private\n * @param {Task.TaskState} state\n */\n step(state) {\n this.state = state\n if (state.done) {\n this.result = { ok: true, value: state.value }\n this.status = FINISHED\n const { handler } = this\n if (handler.onsuccess) {\n handler.onsuccess(state.value)\n }\n }\n\n return state\n }\n\n /**\n * @param {unknown} value\n */\n next(value) {\n try {\n return this.step(this.controller.next(value))\n } catch (error) {\n return this.panic(error)\n }\n }\n /**\n * @param {T} value\n */\n return(value) {\n try {\n return this.step(this.controller.return(value))\n } catch (error) {\n return this.panic(error)\n }\n }\n /**\n * @param {X} error\n */\n throw(error) {\n try {\n return this.step(this.controller.throw(error))\n } catch (error) {\n return this.panic(error)\n }\n }\n}\n\n/**\n * @template M\n * @param {Task.Effect} init\n * @param {(message:M) => Task.Effect} next\n * @returns {Task.Task}\n */\nexport const loop = function* (init, next) {\n /** @type {Task.Controller} */\n const controller = yield* current()\n const group = new Group(controller)\n Group.enqueue(init[Symbol.iterator](), group)\n\n while (true) {\n for (const message of step(group)) {\n Group.enqueue(next(message)[Symbol.iterator](), group)\n }\n\n if (Stack.size(group.stack) > 0) {\n yield* suspend()\n } else {\n break\n }\n }\n}\n\nlet ID = 0\n/** @type {Task.Status} */\nconst IDLE = \"idle\"\nconst ACTIVE = \"active\"\nconst FINISHED = \"finished\"\n/** @type {Task.TaskState} */\nconst INIT = { done: false, value: CURRENT }\n\nconst BLANK = {}\n\n/** @type {Task.Effect} */\nconst NONE = (function* none() {})()\n\n/** @type {Task.Main} */\nconst MAIN = new Main()\n","function Indexed() {}\n\nObject.defineProperties(Indexed, {\n prototype: {\n value: new Proxy(Object.prototype, {\n /**\n * @param {object} target\n * @param {PropertyKey} property\n * @param {{get(key:PropertyKey): any}} receiver\n */\n get(target, property, receiver) {\n return typeof property === \"symbol\"\n ? Reflect.get(target, property, receiver)\n : receiver.get(property)\n },\n }),\n },\n})\n\nexport { Indexed }\n","import { Indexed } from \"./indexed.js\"\n\n/**\n * @typedef {{\n * readonly byteOffset: number\n * readonly byteLength: number\n * readonly segments: Uint8Array[]\n * }} BufferSlice\n */\n\n/** @typedef {BufferView} View */\nexport const empty = () => new BufferView()\n\n/**\n * @param {Uint8Array[]} segments\n * @param {number} byteOffset\n * @param {number} byteLength\n */\nexport const create = (\n segments,\n byteOffset = 0,\n byteLength = totalByteLength(segments)\n) => new BufferView(segments, byteOffset, byteLength)\n\n/**\n *\n * @param {Uint8Array[]} segments\n * @returns\n */\nconst totalByteLength = segments => {\n let byteLength = 0\n for (const segment of segments) {\n byteLength += segment.byteLength\n }\n return byteLength\n}\n\n/**\n * @param {BufferSlice} buffer\n * @param {number} [startOffset]\n * @param {number} [endOffset]\n */\nexport const slice = (\n buffer,\n startOffset = 0,\n endOffset = buffer.byteLength\n) => {\n const segments = []\n const start = startOffset < 0 ? buffer.byteLength - startOffset : startOffset\n const end = endOffset < 0 ? buffer.byteLength - endOffset : endOffset\n\n // If start at 0 offset and end is past buffer range it is effectively\n // as same buffer.\n if (start === 0 && end >= buffer.byteLength) {\n return buffer\n }\n\n // If range is not within the current buffer just create an empty slice.\n if (start > end || start > buffer.byteLength || end <= 0) {\n return empty()\n }\n\n let byteLength = 0\n let offset = 0\n for (const segment of buffer.segments) {\n const nextOffset = offset + segment.byteLength\n // Have not found a start yet\n if (byteLength === 0) {\n // If end offset is within the current segment we know start is also,\n // because it preceeds the end & we had not found start yet.\n // In such case we create a view with only single segment of bytes\n // in the range.\n if (end <= nextOffset) {\n const range = segment.subarray(start - offset, end - offset)\n segments.push(range)\n byteLength = range.byteLength\n break\n }\n // If start offeset falls with in current range (but not the end)\n // we save matching buffer slice and update byteLength.\n else if (start < nextOffset) {\n const range =\n start === offset ? segment : segment.subarray(start - offset)\n segments.push(range)\n byteLength = range.byteLength\n }\n }\n // Otherwise we already started collecting matching segments and are looking\n // for the end end of the slice. If it is with in the current range capture\n // the segment and create a view.\n else if (end <= nextOffset) {\n const range =\n end === nextOffset ? segment : segment.subarray(0, end - offset)\n segments.push(range)\n byteLength += range.byteLength\n break\n }\n // If end is past current range we just save the segment and continue.\n else {\n segments.push(segment)\n byteLength += segment.byteLength\n }\n\n offset = nextOffset\n }\n\n return new BufferView(segments, buffer.byteOffset + start, byteLength)\n}\n\n/**\n * @param {BufferSlice} buffer\n * @param {Uint8Array} part\n */\n\nexport const push = (buffer, part) => {\n if (part.byteLength > 0) {\n // We MUTATE here but that is ok because it is out of bound for the passed\n // buffer view so there will be no visible side effects.\n buffer.segments.push(part)\n return new BufferView(\n buffer.segments,\n buffer.byteOffset,\n buffer.byteLength + part.byteLength\n )\n } else {\n return buffer\n }\n}\n\n/**\n * @param {BufferSlice} buffer\n * @param {number} n\n */\nexport const get = (buffer, n) => {\n if (n < buffer.byteLength) {\n let offset = 0\n for (const segment of buffer.segments) {\n if (n < offset + segment.byteLength) {\n return segment[n - offset]\n } else {\n offset += segment.byteLength\n }\n }\n }\n\n return undefined\n}\n\n/**\n *\n * @param {BufferView} buffer\n * @param {Uint8Array} target\n * @param {number} byteOffset\n */\nexport const copyTo = (buffer, target, byteOffset) => {\n let offset = byteOffset\n for (const segment of buffer.segments) {\n target.set(segment, offset)\n offset += segment.byteLength\n }\n\n return target\n}\n\n/**\n *\n * @param {BufferView} buffer\n */\nexport function* iterate(buffer) {\n for (const part of buffer.segments) {\n yield* part\n }\n}\n\n/**\n * @extends {Indexed}\n */\nclass BufferView extends Indexed {\n /**\n * @param {Uint8Array[]} segments\n * @param {number} byteOffset\n * @param {number} byteLength\n */\n constructor(segments = [], byteOffset = 0, byteLength = 0) {\n super()\n /** @hide */\n this.segments = segments\n /** @readonly */\n this.byteLength = byteLength\n /** @readonly */\n this.length = byteLength\n /** @readonly */\n this.byteOffset = byteOffset\n }\n\n [Symbol.iterator]() {\n return iterate(this)\n }\n\n /**\n * @param {number} [start]\n * @param {number} [end]\n */\n slice(start, end) {\n return /** @type {BufferView} */ (slice(this, start, end))\n }\n\n /**\n * @param {number} [start]\n * @param {number} [end]\n */\n subarray(start, end) {\n return /** @type {BufferView} */ (slice(this, start, end))\n }\n\n /**\n *\n * @param {Uint8Array} bytes\n */\n push(bytes) {\n return /** @type {BufferView} */ (push(this, bytes))\n }\n\n /**\n * @param {number} n\n */\n get(n) {\n return get(this, n)\n }\n\n /**\n *\n * @param {Uint8Array} target\n * @param {number} offset\n */\n copyTo(target, offset) {\n return copyTo(this, target, offset)\n }\n}\n","/**\n * @param {string} reason\n * @returns {never}\n */\nexport const panic = reason => {\n throw new Error(reason)\n}\n\n/**\n * @param {{ raw: readonly string[] | ArrayLike}} template\n * @param {never} [subject]\n * @param {unknown[]} substitutions\n * @returns {never}\n */\nexport const unreachable = (template, subject, ...substitutions) =>\n panic(String.raw(template, JSON.stringify(subject), ...substitutions))\n\nexport const EMPTY_BUFFER = new Uint8Array(0)\n/** @type {any[]} */\nexport const EMPTY = []\n","import * as BufferQueue from \"./chunker/buffer.js\"\nimport * as Chunker from \"./chunker/api.js\"\nimport { EMPTY } from \"../writer/util.js\"\nexport * from \"./chunker/api.js\"\n\n/**\n * @typedef {{\n * chunker: Chunker.Chunker\n * }} Config\n *\n *\n * @typedef {{\n * buffer: BufferQueue.View\n * config: Config\n * }} Chunker\n *\n * @typedef {Chunker & {chunks: Chunker.Chunk[]}} ChunkerWithChunks\n */\n\n/**\n * @param {Config} config\n * @returns {Chunker}\n */\nexport const open = config => ({\n config,\n buffer: BufferQueue.empty(),\n})\n\n/**\n * @param {Chunker} state\n * @param {Uint8Array} bytes\n * @returns {ChunkerWithChunks}\n */\nexport const write = (state, bytes) =>\n bytes.byteLength > 0\n ? split(state.config, state.buffer.push(bytes), false)\n : { ...state, chunks: EMPTY }\n\n/**\n * @param {Chunker} state\n * @returns {ChunkerWithChunks}\n */\nexport const close = state => split(state.config, state.buffer, true)\n\n/**\n * @param {Config} config\n * @param {BufferQueue.View} buffer\n * @param {boolean} end\n * @returns {ChunkerWithChunks}\n */\n\nexport const split = (config, buffer, end) => {\n const chunker = config.chunker\n const chunks = []\n\n let offset = 0\n for (const size of chunker.cut(chunker.context, buffer, end)) {\n // We may be splitting empty buffer in which case there will be no chunks\n // in it so we make sure that we do not emit empty buffer.\n if (size > 0) {\n const chunk = buffer.subarray(offset, offset + size)\n chunks.push(chunk)\n offset += size\n }\n }\n\n return { config, chunks, buffer: buffer.subarray(offset) }\n}\n","import * as Layout from \"./api.js\"\nimport * as Queue from \"./queue/api.js\"\nexport * from \"./queue/api.js\"\n\n/**\n * @returns {Queue.Result}\n */\nexport const empty = () => ({\n mutable: false,\n needs: {},\n nodes: {},\n links: {},\n linked: [],\n})\n\nexport const mutable = () => ({\n mutable: true,\n needs: {},\n nodes: {},\n links: {},\n linked: EMPTY,\n})\n\n/**\n * Adds given layout node to the layout queue. If links for all of the node\n * children are available correspnoding linked node is added (removing links\n * form the queue) otherwise `nood` is added to the wait queue until all the\n * needed links are added.\n *\n *\n * @param {Layout.Branch} node\n * @param {Queue.Queue} queue\n * @returns {Queue.Result}\n */\nexport const addNode = (node, queue) => addNodes([node], queue)\n\n/**\n *\n * @param {Layout.Branch[]} newNodes\n * @param {Queue.Queue} input\n * @returns {Queue.Result}\n */\nexport const addNodes = (newNodes, input) => {\n let queue = patch(input, {})\n for (const node of newNodes) {\n const { ready, has, wants } = collect(node.children, queue.links)\n // If node isn't waiting on any of the children it's ready to be linked\n // so we add linked node diretly.\n if (wants.length === 0) {\n queue = patch(queue, {\n links: assign(undefined, has),\n linked: [{ id: node.id, links: ready }],\n })\n } else {\n queue = patch(queue, {\n needs: assign(node.id, wants),\n nodes: {\n [node.id]: {\n children: node.children,\n count: wants.length,\n },\n },\n })\n }\n }\n\n return queue\n}\n\n/**\n * Adds link to the queue. If queue contains a node that needs this link it gets\n * updated. Either it's gets linked (when it was blocked only on this link) or\n * it's want could is reduced. If no node needed this link it just gets stored\n * for the future node that will need it.\n *\n *\n * @param {Queue.NodeID} id\n * @param {Queue.Link} link\n * @param {Queue.Queue} queue\n * @returns {Queue.Result}\n */\n\nexport const addLink = (id, link, queue) => {\n const nodeID = queue.needs[id]\n const node = queue.nodes[nodeID]\n // We have node than needs this link.\n if (node != null) {\n // This is the only link it needed so we materialize the node and remove\n // links and needs associated with it.\n if (node.count === 1) {\n const { ready, has } = collect(node.children, {\n ...queue.links,\n [id]: link,\n })\n\n return patch(queue, {\n needs: { [id]: undefined },\n links: assign(undefined, has),\n nodes: { [nodeID]: undefined },\n linked: [{ id: nodeID, links: ready }],\n })\n }\n // If node needs more links we just reduce a want count and remove this\n // need.\n else {\n return patch(queue, {\n needs: { [id]: undefined },\n links: { [id]: link },\n nodes: {\n [nodeID]: {\n ...node,\n count: node.count - 1,\n },\n },\n })\n }\n }\n // If we have no one waiting for this link just add it to the queue\n else {\n return patch(queue, {\n links: { [id]: link },\n })\n }\n}\n\n/**\n *\n * @param {Queue.Queue} queue\n * @param {Queue.Delta} delta\n */\n\nconst patch = (queue, { needs, nodes, links, linked }) => {\n const result = queue.mutable ? queue : { ...queue }\n const original = queue.mutable ? BLANK : undefined\n\n if (needs) {\n result.needs = patchDict(queue.needs, needs, original)\n }\n\n if (nodes) {\n result.nodes = patchDict(queue.nodes, nodes, original)\n }\n\n if (links) {\n result.links = patchDict(queue.links, links, original)\n }\n\n result.linked = linked\n ? append(queue.linked || EMPTY, linked, EMPTY)\n : queue.linked || []\n\n return /** @type {Queue.Result} */ (result)\n}\n\n/**\n * @template V\n * @template {PropertyKey} K\n * @param {V} value\n * @param {K[]} keys\n * @returns {Record}\n */\n\nconst assign = (value, keys) => {\n const delta = /** @type {Record} */ ({})\n for (const key of keys) {\n delta[key] = value\n }\n\n return delta\n}\n\n/**\n * @template {PropertyKey} K\n * @template V\n * @param {Record} target\n *\n * @param {Record} delta\n * @param {Record} original\n * @returns {Record}\n */\n\nconst patchDict = (target, delta, original = target) => {\n const result = target === original ? { ...target } : target\n for (const entry of Object.entries(delta)) {\n const [id, value] = /** @type {[K, V|void]} */ (entry)\n if (value == null) {\n delete result[id]\n } else {\n result[id] = value\n }\n }\n\n return result\n}\n/**\n *\n * @param {Iterable<[Queue.NodeID, Queue.Link]>} entries\n * @param {Queue.Queue} queue\n * @returns {Queue.Queue}\n */\nexport const addLinks = (entries, queue) => {\n for (const [id, link] of entries) {\n queue = addLink(id, link, queue)\n }\n return queue\n}\n\n/**\n * @param {Queue.Queue} queue\n */\n\nexport const isEmpty = queue =>\n Object.keys(queue.nodes).length === 0 && Object.keys(queue.links).length === 0\n\n/**\n * @template T\n * @param {T[]} target\n * @param {T[]} items\n * @param {T[]} original\n */\nconst append = (target, items, original = target) => {\n if (target === original) {\n return [...target, ...items]\n } else {\n for (const item of items) {\n target.push(item)\n }\n return target\n }\n}\n\n/**\n * @param {Queue.NodeID[]} children\n * @param {Record} source\n * @returns {{has:Queue.NodeID[], wants:Queue.NodeID[], ready:Queue.Link[]}}\n */\nconst collect = (children, source) => {\n const has = []\n const wants = []\n const ready = []\n for (const child of children) {\n const link = source[child]\n if (link) {\n has.push(child)\n ready.push(link)\n } else {\n wants.push(child)\n }\n }\n\n return { has, wants, ready }\n}\n\nconst EMPTY = /** @type {never[]} */ (Object.freeze([]))\n\nconst BLANK = /** @type {Record} */ (Object.freeze({}))\n","import * as Task from \"actor\"\nimport * as API from \"./api.js\"\nimport * as Layout from \"./layout/api.js\"\nimport * as UnixFS from \"../codec.js\"\nimport * as Chunker from \"./chunker.js\"\nimport { EMPTY_BUFFER, panic, unreachable } from \"../writer/util.js\"\nimport * as Queue from \"./layout/queue.js\"\n\n/**\n * @template Layout\n * @typedef {{\n * readonly status: 'open'\n * readonly metadata: UnixFS.Metadata\n * readonly config: API.EncoderSettings\n * readonly writer: API.BlockWriter\n * chunker: Chunker.Chunker\n * layout: Layout\n * nodeQueue: Queue.Queue\n * }} Open\n */\n/**\n * @template Layout\n * @typedef {{\n * readonly status: 'closed'\n * readonly metadata: UnixFS.Metadata\n * readonly config: API.EncoderSettings\n * readonly writer: API.BlockWriter\n * readonly rootID: Layout.NodeID\n * readonly end?: Task.Fork\n * chunker?: null\n * layout?: null\n * nodeQueue: Queue.Queue\n * }} Closed\n */\n/**\n * @template Layout\n * @typedef {{\n * readonly status: 'linked'\n * readonly metadata: UnixFS.Metadata\n * readonly config: API.EncoderSettings\n * readonly writer: API.BlockWriter\n * readonly link: Layout.Link\n * chunker?: null\n * layout?: null\n * nodeQueue: Queue.Queue\n * }} Linked\n */\n\n/**\n * @template Layout\n * @typedef {Open|Closed|Linked} State\n */\n\n/**\n * @template {object} Layout\n * @typedef {{\n * state: State\n * effect: Task.Effect\n * }} Update\n */\n/**\n * @typedef {never\n * |{type:\"write\", bytes:Uint8Array}\n * |{type:\"link\", link:API.EncodedFile}\n * |{type:\"block\"}\n * |{type: \"close\"}\n * |{type: \"end\"}\n * } Message\n */\n\n/**\n * @template Layout\n * @param {Message} message\n * @param {State} state\n */\nexport const update = (message, state) => {\n switch (message.type) {\n case \"write\":\n return write(state, message.bytes)\n case \"link\":\n return link(state, message.link)\n /* c8 ignore next 2 */\n case \"block\":\n return { state, effect: Task.none() }\n case \"close\":\n return close(state)\n case \"end\":\n return { state, effect: Task.none() }\n default:\n return unreachable`File Writer got unknown message ${message}`\n }\n}\n\n/**\n * @template Layout\n * @param {API.BlockWriter} writer\n * @param {UnixFS.Metadata} metadata\n * @param {API.EncoderSettings} config\n * @returns {State}\n */\nexport const init = (writer, metadata, config) => {\n return {\n status: \"open\",\n metadata,\n config,\n writer,\n chunker: Chunker.open({ chunker: config.chunker }),\n layout: config.fileLayout.open(),\n // Note: Writing in large slices e.g. 1GiB at a time creates large queues\n // with around `16353` items. Immutable version ends up copying it every\n // time state of the queue changes, which introduces significant overhead.\n // To avoid this overhead we use mutable implementation which is API\n // compatible but makes in place updates.\n // TODO: We should consider using Persistent bit-partitioned vector tries\n // instead of arrays which would provide immutable interface with neglegable\n // overhead.\n // @see https://github.com/Gozala/vectrie\n nodeQueue: Queue.mutable(),\n }\n}\n/**\n * @template Layout\n * @param {State} state\n * @param {Uint8Array} bytes\n * @returns {Update}\n */\nexport const write = (state, bytes) => {\n if (state.status === \"open\") {\n // Chunk up provided bytes\n const { chunks, ...chunker } = Chunker.write(state.chunker, bytes)\n\n // Pass chunks to layout engine to produce nodes\n const { nodes, leaves, layout } = state.config.fileLayout.write(\n state.layout,\n chunks\n )\n\n const { linked, ...nodeQueue } = Queue.addNodes(nodes, state.nodeQueue)\n\n // Create leaf encode tasks for all new leaves\n const tasks = [\n ...encodeLeaves(leaves, state.config),\n ...encodeBranches(linked, state.config),\n ]\n\n return {\n state: {\n ...state,\n chunker,\n layout,\n nodeQueue,\n },\n effect: Task.listen({\n link: Task.effects(tasks),\n }),\n }\n } else {\n return panic(\"Unable to perform write on closed file\")\n }\n}\n\n/**\n * @template Layout\n * @param {State} state\n * @param {API.EncodedFile} entry\n * @returns {Update}\n */\nexport const link = (state, { id, link, block }) => {\n let { linked, ...nodeQueue } = Queue.addLink(id, link, state.nodeQueue)\n\n const tasks = encodeBranches(linked, state.config)\n\n /** @type {State} */\n const newState =\n state.status === \"closed\" && id === state.rootID\n ? {\n ...state,\n status: \"linked\",\n link,\n nodeQueue,\n }\n : { ...state, nodeQueue }\n\n // If we just linked a root and there is a **suspended** \"end\" task we create\n // a task to resume it.\n const end =\n state.status === \"closed\" && id === state.rootID && state.end\n ? state.end.resume()\n : Task.none()\n\n return {\n state: newState,\n effect: Task.listen({\n link: Task.effects(tasks),\n block: writeBlock(state.writer, block),\n end,\n }),\n }\n}\n\n/**\n * @template Layout\n * @param {State} state\n * @returns {Update}\n */\nexport const close = state => {\n if (state.status === \"open\") {\n const { chunks } = Chunker.close(state.chunker)\n const { layout, ...write } = state.config.fileLayout.write(\n state.layout,\n chunks\n )\n\n const { root, ...close } = state.config.fileLayout.close(\n layout,\n state.metadata\n )\n\n const [nodes, leaves] = isLeafNode(root)\n ? [\n [...write.nodes, ...close.nodes],\n [...write.leaves, ...close.leaves, root],\n ]\n : [\n [...write.nodes, ...close.nodes, root],\n [...write.leaves, ...close.leaves],\n ]\n\n const { linked, ...nodeQueue } = Queue.addNodes(nodes, state.nodeQueue)\n\n const tasks = [\n ...encodeLeaves(leaves, state.config),\n ...encodeBranches(linked, state.config),\n ]\n\n // We want to keep run loop around until root node is linked. To\n // accomplish this we fork a task that suspends itself, which we will\n // resume when root is linked (see link function).\n // Below we join this forked task in our effect, this way effect is not\n // complete until task forked task is, which will do once we link the\n // root.\n const fork = Task.fork(Task.suspend())\n\n return {\n state: {\n ...state,\n chunker: null,\n layout: null,\n rootID: root.id,\n status: \"closed\",\n end: fork,\n nodeQueue,\n },\n effect: Task.listen({\n link: Task.effects(tasks),\n end: Task.join(fork),\n }),\n }\n } else {\n return { state, effect: Task.none() }\n }\n}\n\n/**\n * Creates concurrent leaf encode tasks. Each one will have an ID corresponding\n * to index in the queue.\n *\n * @param {Layout.Leaf[]} leaves\n * @param {API.EncoderSettings} config\n */\nconst encodeLeaves = (leaves, config) =>\n leaves.map(leaf => encodeLeaf(config, leaf, config.fileChunkEncoder))\n\n/**\n * @param {API.EncoderSettings} config\n * @param {Layout.Leaf} leaf\n * @param {API.FileChunkEncoder} encoder\n * @returns {Task.Task}\n */\nconst encodeLeaf = function* ({ hasher, linker }, { id, content }, encoder) {\n const bytes = encoder.encode(content ? asUint8Array(content) : EMPTY_BUFFER)\n const hash = yield* Task.wait(hasher.digest(bytes))\n const cid = linker.createLink(encoder.code, hash)\n\n const block = { cid, bytes }\n const link = /** @type {UnixFS.FileLink} */ ({\n cid,\n contentByteLength: content ? content.byteLength : 0,\n dagByteLength: bytes.byteLength,\n })\n\n return { id, block, link }\n}\n\n/**\n * @param {Queue.LinkedNode[]} nodes\n * @param {API.EncoderSettings} config\n */\nconst encodeBranches = (nodes, config) =>\n nodes.map(node => encodeBranch(config, node))\n\n/**\n * @template Layout\n * @param {API.EncoderSettings} config\n * @param {Queue.LinkedNode} node\n * @param {UnixFS.Metadata} [metadata]\n * @returns {Task.Task}\n */\nexport const encodeBranch = function* (config, { id, links }, metadata) {\n const bytes = config.fileEncoder.encode({\n type: UnixFS.NodeType.File,\n layout: \"advanced\",\n parts: links,\n metadata,\n })\n const hash = yield* Task.wait(Promise.resolve(config.hasher.digest(bytes)))\n const cid = config.linker.createLink(config.fileEncoder.code, hash)\n const block = { bytes, cid }\n const link = /** @type {UnixFS.FileLink} */ ({\n cid,\n contentByteLength: UnixFS.cumulativeContentByteLength(links),\n dagByteLength: UnixFS.cumulativeDagByteLength(bytes, links),\n })\n\n return { id, block, link }\n}\n\n/**\n * @param {API.BlockWriter} writer\n * @param {UnixFS.Block} block\n * @returns {Task.Task}\n */\n\nexport const writeBlock = function* (writer, block) {\n if ((writer.desiredSize || 0) <= 0) {\n yield* Task.wait(writer.ready)\n }\n writer.write(block)\n}\n\n/**\n *\n * @param {Uint8Array|Chunker.Chunk} buffer\n * @returns\n */\n\nconst asUint8Array = buffer =>\n buffer instanceof Uint8Array\n ? buffer\n : buffer.copyTo(new Uint8Array(buffer.byteLength), 0)\n\n/**\n * @param {Layout.Node} node\n * @returns {node is Layout.Leaf}\n */\nconst isLeafNode = node => node.children == null\n","import * as API from \"./api.js\"\n\nexport const name = \"fixed\"\n/**\n * @typedef {Object} FixedSize\n * @property {number} maxChunkSize\n */\n\n/** @type {FixedSize} */\nexport const context = {\n maxChunkSize: 262144,\n}\n\nexport const type = \"Stateless\"\n\n/**\n * @param {number} maxChunkSize\n * @returns {API.StatelessChunker}\n */\nexport const withMaxChunkSize = maxChunkSize => ({\n type: \"Stateless\",\n context: { maxChunkSize },\n name,\n cut,\n})\n\n/**\n * @param {FixedSize} maxChunkSize\n * @param {API.Chunk} buffer\n * @param {boolean} end\n * @returns {number[]}\n */\nexport const cut = ({ maxChunkSize }, { byteLength }, end) => {\n // number of fixed size chunks that would fit\n const n = (byteLength / maxChunkSize) | 0\n const chunks = new Array(n).fill(maxChunkSize)\n const lastChunkSize = end ? byteLength - n * maxChunkSize : 0\n if (lastChunkSize > 0) {\n chunks.push(lastChunkSize)\n }\n return chunks\n}\n","import * as Digest from './digest.js';\nexport function from({ name, code, encode }) {\n return new Hasher(name, code, encode);\n}\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher {\n name;\n code;\n encode;\n constructor(name, code, encode) {\n this.name = name;\n this.code = code;\n this.encode = encode;\n }\n digest(input) {\n if (input instanceof Uint8Array) {\n const result = this.encode(input);\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest));\n }\n else {\n throw Error('Unknown type, must be binary type');\n /* c8 ignore next 1 */\n }\n }\n}\n//# sourceMappingURL=hasher.js.map","/* global crypto */\nimport { from } from './hasher.js';\nfunction sha(name) {\n return async (data) => new Uint8Array(await crypto.subtle.digest(name, data));\n}\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n});\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n});\n//# sourceMappingURL=sha2-browser.js.map","import * as Layout from \"./api.js\"\nimport * as Chunker from \"./../chunker/api.js\"\n\n/**\n * Type representing a state of the balanced tree. First row hold leaves coming\n * into a builder, once number of leaves in the stack reaches `maxChildren` they\n * are moved into `RootNode` instance which is pushed into the next row of nodes.\n * If next row now contains `maxChildren` nodes from there are again moved into\n * a new `RootNode` and pushed into next row etc...\n *\n * For illustration let's assume we have `maxChildren: 3`, after 3 leafs were\n * added tree will have following layout\n *\n * ```\n * (root1)\n * |\n * ----------------------\n * | | |\n * (leaf1) (leaf2) (leaf3)\n * ```\n *\n * Which in our model before flushing is represented as follows:\n *\n * ```js\n * {\n * width: 3\n * leafIndex: [leaf1, leaf2, leaf3]\n * nodeIndex: []\n * nodes: []\n * }\n * ```\n *\n * After flushing 3 leaves (which is width) are moved into a `RootNode` that\n * is added to `nodes` array (and returned so that caller can create a block).\n * Additionally position of the added node is captured in the `index` at an\n * appropriate depth `0` (that is because we don't count leaves into depth).\n *\n * ```js\n * {\n * width: 3\n * leafIndex: []\n * nodeIndex: [[0]]\n * nodes: [new RootNode([leaf1, leaf2, leaf3])]\n * }\n * ```\n *\n * Increasing number of leaves to 10 would produce following tree layout\n *\n *```\n * (root7)\n * |\n * ------------------------------------------\n * | |\n * (root4) (root6)\n * | |\n * ------------------------------------------------- |\n * | | | |\n * (root1) (root2) (root3) (root5)\n * | | | |\n * --------|-------- --------|-------- --------|-------- |\n * | | | | | | | | | |\n * (leaf1) (leaf2) (leaf3) (leaf4) (leaf5) (leaf6) (leaf7) (leaf8) (leaf9) (leaf10)\n * ```\n *\n * Which in our model will look as follows (note we do not have root5 - root7\n * in model because they are build once width is reached or once builder is\n * closed)\n *\n * ```js\n * {\n * width: 3\n * leafIndex: [leaf10]\n * nodeIndex: [\n * [0, 1, 2], // [r1, r2, r3]\n * [3] // [r4]\n * ]\n * nodes: [\n * new Node([leaf1, leaf2, leaf3]), // r1\n * new Node([leaf4, leaf5, leaf6]), // r2\n * new Node([leaf7, leaf8, leaf9]), // r3\n * new Node([ // r4\n * new Node([leaf1, leaf2, leaf3]), // r1\n * new Node([leaf4, leaf5, leaf6]), // r2\n * new Node([leaf7, leaf8, leaf9]), // r3\n * ])\n * ]\n * }\n * ```\n *\n * @typedef {{\n * width: number\n * head: Chunker.Chunk | null\n * leafIndex: number[]\n * nodeIndex: number[][]\n * lastID: number\n * }} Balanced\n */\n\nclass Node {\n /**\n *\n * @param {number} id\n * @param {number[]} children\n * @param {Layout.Metadata} [metadata]\n */\n constructor(id, children, metadata) {\n this.id = id\n this.children = children\n this.metadata = metadata\n }\n}\n\n/**\n * @typedef Options\n * @property {number} width - Max children per node.\n *\n * @param {number} width\n * @returns {Layout.LayoutEngine}\n */\nexport const withWidth = width => ({\n open: () => open({ width }),\n write,\n close,\n})\n\nexport const defaults = { width: 174 }\n\n/**\n * @param {Options} options\n * @returns {Balanced}\n */\nexport const open = ({ width } = defaults) => ({\n width,\n\n head: null,\n leafIndex: [],\n nodeIndex: [],\n lastID: 0,\n})\n\n/**\n *\n * @param {Balanced} layout\n * @param {Chunker.Chunk[]} chunks\n * @returns {Layout.WriteResult}\n */\nexport const write = (layout, chunks) => {\n if (chunks.length === 0) {\n return { layout, nodes: EMPTY, leaves: EMPTY }\n } else {\n let { lastID } = layout\n // We need to hold on to the first chunk until we either get a second chunk\n // (at which point we know our layout will have branches) or until we close\n // (at which point our layout will be single leaf or node depneding on\n // metadata)\n const [head, slices] = layout.head\n ? // If we had a head we have more then two chunks (we already checked\n // chunks weren't empty) so we process head along with other chunks.\n [null, (chunks.unshift(layout.head), chunks)]\n : // If we have no head no leaves and got only one chunk we have to save it\n // until we can decide what to do with it.\n chunks.length === 1 && layout.leafIndex.length === 0\n ? [chunks[0], EMPTY]\n : // Otherwise we have no head but got enough chunks to know we'll have a\n // node.\n [null, chunks]\n\n if (slices.length === 0) {\n return { layout: { ...layout, head }, nodes: EMPTY, leaves: EMPTY }\n } else {\n const leafIndex = [...layout.leafIndex]\n const leaves = []\n for (const chunk of slices) {\n const leaf = { id: ++lastID, content: chunk }\n leaves.push(leaf)\n leafIndex.push(leaf.id)\n }\n\n if (leafIndex.length > layout.width) {\n return flush({ ...layout, leafIndex, head, lastID }, leaves)\n } else {\n return {\n layout: { ...layout, head, leafIndex, lastID },\n leaves,\n nodes: EMPTY,\n }\n }\n }\n }\n}\n\n/**\n * @param {Balanced} state\n * @param {Layout.Leaf[]} leaves\n * @param {Layout.Branch[]} [nodes]\n * @param {boolean} [close]\n * @returns {Layout.WriteResult}\n */\nexport const flush = (state, leaves = EMPTY, nodes = [], close = false) => {\n let { lastID } = state\n const nodeIndex = state.nodeIndex.map(row => [...row])\n const leafIndex = [...state.leafIndex]\n const { width } = state\n\n // Move leaves into nodes\n while (leafIndex.length > width || (leafIndex.length > 0 && close)) {\n grow(nodeIndex, 1)\n const node = new Node(++lastID, leafIndex.splice(0, width))\n nodeIndex[0].push(node.id)\n nodes.push(node)\n }\n\n let depth = 0\n while (depth < nodeIndex.length) {\n const row = nodeIndex[depth]\n depth++\n\n while (\n row.length > width ||\n (row.length > 0 && close && depth < nodeIndex.length)\n ) {\n const node = new Node(++lastID, row.splice(0, width))\n grow(nodeIndex, depth + 1)\n nodeIndex[depth].push(node.id)\n nodes.push(node)\n }\n }\n\n return { layout: { ...state, lastID, leafIndex, nodeIndex }, leaves, nodes }\n}\n\n/**\n * @param {Balanced} layout\n * @param {Layout.Metadata} [metadata]\n * @returns {Layout.CloseResult}\n */\nexport const close = (layout, metadata) => {\n const state = layout\n if (layout.head) {\n return {\n root: { id: 1, content: layout.head, metadata },\n leaves: EMPTY,\n nodes: EMPTY,\n }\n } else if (layout.leafIndex.length === 0) {\n return {\n root: { id: 1, metadata },\n leaves: EMPTY,\n nodes: EMPTY,\n }\n } else {\n // Flush with width 1 so all the items will be propagate up the tree\n // and height of `depth-1` so we propagate nodes all but from the top\n // most level\n const { nodes, layout } = flush(state, EMPTY, [], true)\n\n const { nodeIndex } = layout\n const height = nodeIndex.length - 1\n\n const top = nodeIndex[height]\n if (top.length === 1) {\n const root = nodes[nodes.length - 1]\n nodes.length = nodes.length - 1\n return { root, nodes, leaves: EMPTY }\n } else {\n const root = new Node(layout.lastID + 1, top, metadata)\n return { root, nodes, leaves: EMPTY }\n }\n }\n}\n\n/**\n * @template T\n * @param {T[][]} index\n * @param {number} length\n */\nconst grow = (index, length) => {\n while (index.length < length) {\n index.push([])\n }\n return index\n}\n\n/** @type {never[]} */\nconst EMPTY = []\n","import * as API from \"./file/api.js\"\nimport * as UnixFS from \"./codec.js\"\nimport * as Writer from \"./file/writer.js\"\nimport * as Task from \"actor\"\nimport { panic } from \"./writer/util.js\"\nimport * as FixedSize from \"./file/chunker/fixed.js\"\nimport { sha256 } from \"multiformats/hashes/sha2\"\nimport { CID } from \"multiformats/cid\"\nimport * as Balanced from \"./file/layout/balanced.js\"\n\nexport * from \"./file/api.js\"\n\n/**\n * @returns {API.EncoderSettings}\n */\nexport const defaults = () => ({\n chunker: FixedSize,\n fileChunkEncoder: UnixFSLeaf,\n smallFileEncoder: UnixFSLeaf,\n fileEncoder: UnixFS,\n fileLayout: Balanced.withWidth(174),\n hasher: sha256,\n linker: { createLink: CID.createV1 },\n})\n\n/**\n * @template {unknown} Layout\n * @param {Partial>} config\n * @returns {API.EncoderSettings}\n */\nexport const configure = config => ({\n ...defaults(),\n ...config,\n})\n\nexport const UnixFSLeaf = {\n code: UnixFS.code,\n name: UnixFS.name,\n encode: UnixFS.encodeFileChunk,\n}\n\nexport const UnixFSRawLeaf = {\n code: UnixFS.code,\n name: UnixFS.name,\n encode: UnixFS.encodeRaw,\n}\n\n/**\n * @template Layout\n * @param {API.Options} options\n * @returns {API.View}\n */\nexport const create = ({ writer, metadata = {}, settings = defaults() }) =>\n new FileWriterView(Writer.init(writer, metadata, configure(settings)))\n\n/**\n * @template T\n * @param {API.View} view\n * @param {Uint8Array} bytes\n * @return {Promise>}\n */\n\nexport const write = async (view, bytes) => {\n await perform(view, Task.send({ type: \"write\", bytes }))\n return view\n}\n\n/**\n * @template T\n * @param {API.View} view\n * @param {API.CloseOptions} options\n */\nexport const close = async (\n view,\n { releaseLock = false, closeWriter = false } = {}\n) => {\n await perform(view, Task.send({ type: \"close\" }))\n const { state } = view\n if (state.status === \"linked\") {\n if (closeWriter) {\n await view.state.writer.close()\n } else if (releaseLock) {\n view.state.writer.releaseLock()\n }\n return state.link\n /* c8 ignore next 5 */\n } else {\n panic(\n `Expected writer to be in 'linked' state after close, but it is in \"${state.status}\" instead`\n )\n }\n}\n\n/**\n * @template T\n * @param {API.View} view\n * @param {Task.Effect} effect\n */\nconst perform = (view, effect) =>\n Task.fork(\n Task.loop(effect, message => {\n const { state, effect } = Writer.update(message, view.state)\n view.state = state\n return effect\n })\n )\n\n/**\n * @template Layout\n * @implements {API.View}\n */\nclass FileWriterView {\n /**\n * @param {Writer.State} state\n */\n constructor(state) {\n this.state = state\n }\n get writer() {\n return this.state.writer\n }\n get settings() {\n return this.state.config\n }\n /**\n * @param {Uint8Array} bytes\n * @returns {Promise>}\n */\n write(bytes) {\n return write(this, bytes)\n }\n /**\n * @param {API.CloseOptions} [options]\n * @returns {Promise}\n */\n close(options) {\n return close(this, options)\n }\n}\n","import * as API from \"./directory/api.js\"\nimport * as File from \"./file.js\"\nimport * as UnixFS from \"./codec.js\"\nexport * from \"./directory/api.js\"\n\nexport const configure = File.configure\nexport const defaults = File.defaults\n\n/**\n * @template [Layout=unknown]\n * @param {API.Options} config\n * @returns {API.View}\n */\nexport const create = ({ writer, settings = defaults(), metadata = {} }) =>\n new DirectoryWriter({\n writer,\n metadata,\n settings,\n entries: new Map(),\n closed: false,\n })\n\n/**\n * @template {unknown} L\n * @template {{ state: API.State }} View\n * @param {View} view\n * @param {string} name\n * @param {API.EntryLink} link\n * @param {API.WriteOptions} options\n */\nexport const set = (view, name, link, { overwrite = false } = {}) => {\n const writable = asWritable(view.state)\n if (name.includes(\"/\")) {\n throw new Error(\n `Directory entry name \"${name}\" contains forbidden \"/\" character`\n )\n }\n if (!overwrite && writable.entries.has(name)) {\n throw new Error(`Directory already contains entry with name \"${name}\"`)\n } else {\n writable.entries.set(name, link)\n return view\n }\n}\n\n/**\n * @template {unknown} L\n * @template {{ state: API.State }} View\n * @param {View} view\n * @param {string} name\n */\nexport const remove = (view, name) => {\n const writer = asWritable(view.state)\n writer.entries.delete(name)\n return view\n}\n\n/**\n * @template {API.State} Writer\n * @param {Writer} writer\n * @returns {Writer}\n */\nconst asWritable = writer => {\n if (!writer.closed) {\n return writer\n } else {\n throw new Error(\n `Can not change written directory, but you can .fork() and make changes to it`\n )\n }\n}\n\n/**\n * @template {unknown} Layout\n * @param {{ state: API.State }} view\n * @param {API.CloseOptions} options\n * @returns {Promise}\n */\nexport const close = async (\n view,\n { closeWriter = false, releaseLock = false } = {}\n) => {\n const { writer, settings, metadata } = asWritable(view.state)\n view.state.closed = true\n const entries = [...links(view)]\n const node = UnixFS.createFlatDirectory(entries, metadata)\n const bytes = UnixFS.encodeDirectory(node)\n const digest = await settings.hasher.digest(bytes)\n /** @type {UnixFS.Link} */\n const cid = settings.linker.createLink(UnixFS.code, digest)\n\n // we make sure that writer has some capacity for this write. If it\n // does not we await.\n if ((writer.desiredSize || 0) <= 0) {\n await writer.ready\n }\n // once writer has some capacity we write a block, however we do not\n // await completion as we don't care when it's taken off the stream.\n writer.write({ cid, bytes })\n\n if (closeWriter) {\n await writer.close()\n } else if (releaseLock) {\n writer.releaseLock()\n }\n\n return {\n cid,\n dagByteLength: UnixFS.cumulativeDagByteLength(bytes, entries),\n }\n}\n\n/**\n * @template {unknown} Layout\n * @param {{ state: API.State }} view\n * @returns {IterableIterator}\n */\nexport const links = function* ({ state }) {\n for (const [name, { dagByteLength, cid }] of state.entries) {\n yield /** @type {UnixFS.DirectoryEntryLink} */ ({\n name,\n dagByteLength,\n cid,\n })\n }\n}\n\n/**\n * @template L1, L2\n * @param {API.View} state\n * @param {Partial>} options\n * @returns {API.View}\n */\nexport const fork = (\n { state },\n {\n writer = state.writer,\n metadata = state.metadata,\n settings = state.settings,\n } = {}\n) =>\n new DirectoryWriter({\n writer,\n metadata,\n settings,\n entries: new Map(state.entries.entries()),\n closed: false,\n })\n\n/**\n * @template [Layout=unknown]\n * @implements {API.View}\n */\nclass DirectoryWriter {\n /**\n * @param {API.State} state\n */\n constructor(state) {\n this.state = state\n }\n get writer() {\n return this.state.writer\n }\n get settings() {\n return this.state.settings\n }\n\n links() {\n return links(this)\n }\n\n /**\n * @param {string} name\n * @param {UnixFS.FileLink | UnixFS.DirectoryLink} link\n * @param {API.WriteOptions} [options]\n */\n\n set(name, link, options) {\n return set(this, name, link, options)\n }\n\n /**\n * @param {string} name\n */\n remove(name) {\n return remove(this, name)\n }\n\n /**\n * @template L\n * @param {Partial>} [options]\n * @returns {API.View}\n */\n fork(options) {\n return fork(this, options)\n }\n\n /**\n * @param {API.CloseOptions} [options]\n * @returns {Promise}\n */\n close(options) {\n return close(this, options)\n }\n\n entries() {\n return this.state.entries.entries()\n }\n /**\n * @param {string} name\n */\n has(name) {\n return this.state.entries.has(name)\n }\n get size() {\n return this.state.entries.size\n }\n}\n","import * as API from \"./api.js\"\n\nexport { API }\n\n/**\n * @param {API.Uint32} size\n */\nexport const empty = (size = 32) => {\n // We could support < 32, but it seems impractical and would negatively affect\n // performance as we would have to do extra bound checks.\n if (size !== 32) {\n throw new Error(`Uint32 BitField does not support size: ${size}`)\n }\n\n return 0\n}\n\n/**\n * @param {API.Uint32[]} bits\n * @param {API.Uint32} [size]\n */\nexport const from = (bits, size) => {\n let bitfield = empty(size)\n for (const bit of bits) {\n bitfield = set(bitfield, bit)\n }\n return bitfield\n}\n\n/**\n * @param {API.Uint32} _bitField\n */\nexport const size = _bitField => 32\n\n/**\n * Reads out 5 bits at the given bit offset.\n *\n * @param {API.Uint32} bitField - Bitfield in Uint32 representation.\n * @param {API.Uint32} index - Index with-in `bitField` to read bits from.\n * @returns {API.Uint32}\n */\nconst mask = (bitField, index) => (bitField >>> index) & 0b11111\n\n/**\n * Creates mask that can be used to check a bit in nodes bitmap for the give\n * key (hash) at given depth.\n *\n * @param {API.Uint32} bitField - Key hash as 32 bit integer.\n * @param {API.Uint32} index - Index with-in the 32bit bitfield\n */\nconst offset = (bitField, index) => 1 << mask(bitField, index)\n\n/**\n * Maps numbers [0, 31] to powers of two. Creates mask that can be used\n * to check a bit in nodes bitmap for the give key (hash) at given depth.\n *\n * @param {API.Uint32} bitField - Key hash as 32 bit integer.\n * @param {API.Uint32} index - Index with-in the 32bit bitfield\n */\nexport const popcount = (bitField, index = 31) =>\n bitCount(bitField & (offset(index, 0) - 1))\n\n/**\n * @param {API.Uint32} bitField\n * @param {API.Uint32} index\n */\nexport const set = (bitField, index) => bitField | (1 << index)\n\n/**\n * @param {API.Uint32} bitField\n * @param {API.Uint32} index\n */\nexport const unset = (bitField, index) => bitField & (0xff ^ (1 << index))\n\n/**\n * @param {API.Uint32} bitField\n * @param {API.Uint32} index\n */\nexport const get = (bitField, index) => ((bitField >> index) & 0x1) !== 0\n\n/**\n * Counts the number of bits set in n\n * @param {API.Uint32} bitField\n */\nexport const bitCount = bitField => {\n const n1 = bitField - ((bitField >> 1) & 0x55555555)\n const n2 = (n1 & 0x33333333) + ((n1 >> 2) & 0x33333333)\n const n3 = ((n2 + (n2 >> 4)) & 0xf0f0f0f) * 0x1010101\n return n3 >> 24\n}\n\n/**\n * @param {API.Uint32} left\n * @param {API.Uint32} right\n * @returns {API.Uint32}\n */\nexport const and = (left, right) => left & right\n\n/**\n * @param {API.Uint32} left\n * @param {API.Uint32} right\n * @returns {API.Uint32}\n */\nexport const or = (left, right) => left | right\n\n/**\n * Counts the number of bits set in n\n * @param {API.Uint32} bitField\n * @returns {Uint8Array}\n */\nexport const toBytes = bitField =>\n Uint8Array.of(\n (bitField >> 24) & 0b1111_1111,\n (bitField >> 16) & 0b1111_1111,\n (bitField >> 8) & 0b1111_1111,\n bitField & 0b1111_1111\n )\n\n/**\n *\n * @param {Uint8Array} bytes\n * @returns {API.Uint32}\n */\nexport const fromBytes = bytes => {\n if (bytes.length !== 4) {\n throw new Error(`Expected 4 bytes instead got ${bytes.length}`)\n }\n return (bytes[0] << 24) + (bytes[1] << 16) + (bytes[2] << 8) + bytes[3]\n}\n","/* jshint -W086: true */\n// +----------------------------------------------------------------------+\n// | murmurHash3js.js v3.0.1 // https://github.com/pid/murmurHash3js\n// | A javascript implementation of MurmurHash3's x86 hashing algorithms. |\n// |----------------------------------------------------------------------|\n// | Copyright (c) 2012-2015 Karan Lyons |\n// | https://github.com/karanlyons/murmurHash3.js/blob/c1778f75792abef7bdd74bc85d2d4e1a3d25cfe9/murmurHash3.js |\n// | Freely distributable under the MIT license. |\n// +----------------------------------------------------------------------+\n\n;(function (root, undefined) {\n 'use strict';\n\n // Create a local object that'll be exported or referenced globally.\n var library = {\n 'version': '3.0.0',\n 'x86': {},\n 'x64': {},\n 'inputValidation': true\n };\n\n // PRIVATE FUNCTIONS\n // -----------------\n\n function _validBytes(bytes) {\n // check the input is an array or a typed array\n if (!Array.isArray(bytes) && !ArrayBuffer.isView(bytes)) {\n return false;\n }\n\n // check all bytes are actually bytes\n for (var i = 0; i < bytes.length; i++) {\n if (!Number.isInteger(bytes[i]) || bytes[i] < 0 || bytes[i] > 255) {\n return false;\n }\n }\n return true;\n }\n\n function _x86Multiply(m, n) {\n //\n // Given two 32bit ints, returns the two multiplied together as a\n // 32bit int.\n //\n\n return ((m & 0xffff) * n) + ((((m >>> 16) * n) & 0xffff) << 16);\n }\n\n function _x86Rotl(m, n) {\n //\n // Given a 32bit int and an int representing a number of bit positions,\n // returns the 32bit int rotated left by that number of positions.\n //\n\n return (m << n) | (m >>> (32 - n));\n }\n\n function _x86Fmix(h) {\n //\n // Given a block, returns murmurHash3's final x86 mix of that block.\n //\n\n h ^= h >>> 16;\n h = _x86Multiply(h, 0x85ebca6b);\n h ^= h >>> 13;\n h = _x86Multiply(h, 0xc2b2ae35);\n h ^= h >>> 16;\n\n return h;\n }\n\n function _x64Add(m, n) {\n //\n // Given two 64bit ints (as an array of two 32bit ints) returns the two\n // added together as a 64bit int (as an array of two 32bit ints).\n //\n\n m = [m[0] >>> 16, m[0] & 0xffff, m[1] >>> 16, m[1] & 0xffff];\n n = [n[0] >>> 16, n[0] & 0xffff, n[1] >>> 16, n[1] & 0xffff];\n var o = [0, 0, 0, 0];\n\n o[3] += m[3] + n[3];\n o[2] += o[3] >>> 16;\n o[3] &= 0xffff;\n\n o[2] += m[2] + n[2];\n o[1] += o[2] >>> 16;\n o[2] &= 0xffff;\n\n o[1] += m[1] + n[1];\n o[0] += o[1] >>> 16;\n o[1] &= 0xffff;\n\n o[0] += m[0] + n[0];\n o[0] &= 0xffff;\n\n return [(o[0] << 16) | o[1], (o[2] << 16) | o[3]];\n }\n\n function _x64Multiply(m, n) {\n //\n // Given two 64bit ints (as an array of two 32bit ints) returns the two\n // multiplied together as a 64bit int (as an array of two 32bit ints).\n //\n\n m = [m[0] >>> 16, m[0] & 0xffff, m[1] >>> 16, m[1] & 0xffff];\n n = [n[0] >>> 16, n[0] & 0xffff, n[1] >>> 16, n[1] & 0xffff];\n var o = [0, 0, 0, 0];\n\n o[3] += m[3] * n[3];\n o[2] += o[3] >>> 16;\n o[3] &= 0xffff;\n\n o[2] += m[2] * n[3];\n o[1] += o[2] >>> 16;\n o[2] &= 0xffff;\n\n o[2] += m[3] * n[2];\n o[1] += o[2] >>> 16;\n o[2] &= 0xffff;\n\n o[1] += m[1] * n[3];\n o[0] += o[1] >>> 16;\n o[1] &= 0xffff;\n\n o[1] += m[2] * n[2];\n o[0] += o[1] >>> 16;\n o[1] &= 0xffff;\n\n o[1] += m[3] * n[1];\n o[0] += o[1] >>> 16;\n o[1] &= 0xffff;\n\n o[0] += (m[0] * n[3]) + (m[1] * n[2]) + (m[2] * n[1]) + (m[3] * n[0]);\n o[0] &= 0xffff;\n\n return [(o[0] << 16) | o[1], (o[2] << 16) | o[3]];\n }\n\n function _x64Rotl(m, n) {\n //\n // Given a 64bit int (as an array of two 32bit ints) and an int\n // representing a number of bit positions, returns the 64bit int (as an\n // array of two 32bit ints) rotated left by that number of positions.\n //\n\n n %= 64;\n\n if (n === 32) {\n return [m[1], m[0]];\n } else if (n < 32) {\n return [(m[0] << n) | (m[1] >>> (32 - n)), (m[1] << n) | (m[0] >>> (32 - n))];\n } else {\n n -= 32;\n return [(m[1] << n) | (m[0] >>> (32 - n)), (m[0] << n) | (m[1] >>> (32 - n))];\n }\n }\n\n function _x64LeftShift(m, n) {\n //\n // Given a 64bit int (as an array of two 32bit ints) and an int\n // representing a number of bit positions, returns the 64bit int (as an\n // array of two 32bit ints) shifted left by that number of positions.\n //\n\n n %= 64;\n\n if (n === 0) {\n return m;\n } else if (n < 32) {\n return [(m[0] << n) | (m[1] >>> (32 - n)), m[1] << n];\n } else {\n return [m[1] << (n - 32), 0];\n }\n }\n\n function _x64Xor(m, n) {\n //\n // Given two 64bit ints (as an array of two 32bit ints) returns the two\n // xored together as a 64bit int (as an array of two 32bit ints).\n //\n\n return [m[0] ^ n[0], m[1] ^ n[1]];\n }\n\n function _x64Fmix(h) {\n //\n // Given a block, returns murmurHash3's final x64 mix of that block.\n // (`[0, h[0] >>> 1]` is a 33 bit unsigned right shift. This is the\n // only place where we need to right shift 64bit ints.)\n //\n\n h = _x64Xor(h, [0, h[0] >>> 1]);\n h = _x64Multiply(h, [0xff51afd7, 0xed558ccd]);\n h = _x64Xor(h, [0, h[0] >>> 1]);\n h = _x64Multiply(h, [0xc4ceb9fe, 0x1a85ec53]);\n h = _x64Xor(h, [0, h[0] >>> 1]);\n\n return h;\n }\n\n // PUBLIC FUNCTIONS\n // ----------------\n\n library.x86.hash32 = function (bytes, seed) {\n //\n // Given a string and an optional seed as an int, returns a 32 bit hash\n // using the x86 flavor of MurmurHash3, as an unsigned int.\n //\n if (library.inputValidation && !_validBytes(bytes)) {\n return undefined;\n }\n seed = seed || 0;\n\n var remainder = bytes.length % 4;\n var blocks = bytes.length - remainder;\n\n var h1 = seed;\n\n var k1 = 0;\n\n var c1 = 0xcc9e2d51;\n var c2 = 0x1b873593;\n\n for (var i = 0; i < blocks; i = i + 4) {\n k1 = (bytes[i]) | (bytes[i + 1] << 8) | (bytes[i + 2] << 16) | (bytes[i + 3] << 24);\n\n k1 = _x86Multiply(k1, c1);\n k1 = _x86Rotl(k1, 15);\n k1 = _x86Multiply(k1, c2);\n\n h1 ^= k1;\n h1 = _x86Rotl(h1, 13);\n h1 = _x86Multiply(h1, 5) + 0xe6546b64;\n }\n\n k1 = 0;\n\n switch (remainder) {\n case 3:\n k1 ^= bytes[i + 2] << 16;\n\n case 2:\n k1 ^= bytes[i + 1] << 8;\n\n case 1:\n k1 ^= bytes[i];\n k1 = _x86Multiply(k1, c1);\n k1 = _x86Rotl(k1, 15);\n k1 = _x86Multiply(k1, c2);\n h1 ^= k1;\n }\n\n h1 ^= bytes.length;\n h1 = _x86Fmix(h1);\n\n return h1 >>> 0;\n };\n\n library.x86.hash128 = function (bytes, seed) {\n //\n // Given a string and an optional seed as an int, returns a 128 bit\n // hash using the x86 flavor of MurmurHash3, as an unsigned hex.\n //\n if (library.inputValidation && !_validBytes(bytes)) {\n return undefined;\n }\n\n seed = seed || 0;\n var remainder = bytes.length % 16;\n var blocks = bytes.length - remainder;\n\n var h1 = seed;\n var h2 = seed;\n var h3 = seed;\n var h4 = seed;\n\n var k1 = 0;\n var k2 = 0;\n var k3 = 0;\n var k4 = 0;\n\n var c1 = 0x239b961b;\n var c2 = 0xab0e9789;\n var c3 = 0x38b34ae5;\n var c4 = 0xa1e38b93;\n\n for (var i = 0; i < blocks; i = i + 16) {\n k1 = (bytes[i]) | (bytes[i + 1] << 8) | (bytes[i + 2] << 16) | (bytes[i + 3] << 24);\n k2 = (bytes[i + 4]) | (bytes[i + 5] << 8) | (bytes[i + 6] << 16) | (bytes[i + 7] << 24);\n k3 = (bytes[i + 8]) | (bytes[i + 9] << 8) | (bytes[i + 10] << 16) | (bytes[i + 11] << 24);\n k4 = (bytes[i + 12]) | (bytes[i + 13] << 8) | (bytes[i + 14] << 16) | (bytes[i + 15] << 24);\n\n k1 = _x86Multiply(k1, c1);\n k1 = _x86Rotl(k1, 15);\n k1 = _x86Multiply(k1, c2);\n h1 ^= k1;\n\n h1 = _x86Rotl(h1, 19);\n h1 += h2;\n h1 = _x86Multiply(h1, 5) + 0x561ccd1b;\n\n k2 = _x86Multiply(k2, c2);\n k2 = _x86Rotl(k2, 16);\n k2 = _x86Multiply(k2, c3);\n h2 ^= k2;\n\n h2 = _x86Rotl(h2, 17);\n h2 += h3;\n h2 = _x86Multiply(h2, 5) + 0x0bcaa747;\n\n k3 = _x86Multiply(k3, c3);\n k3 = _x86Rotl(k3, 17);\n k3 = _x86Multiply(k3, c4);\n h3 ^= k3;\n\n h3 = _x86Rotl(h3, 15);\n h3 += h4;\n h3 = _x86Multiply(h3, 5) + 0x96cd1c35;\n\n k4 = _x86Multiply(k4, c4);\n k4 = _x86Rotl(k4, 18);\n k4 = _x86Multiply(k4, c1);\n h4 ^= k4;\n\n h4 = _x86Rotl(h4, 13);\n h4 += h1;\n h4 = _x86Multiply(h4, 5) + 0x32ac3b17;\n }\n\n k1 = 0;\n k2 = 0;\n k3 = 0;\n k4 = 0;\n\n switch (remainder) {\n case 15:\n k4 ^= bytes[i + 14] << 16;\n\n case 14:\n k4 ^= bytes[i + 13] << 8;\n\n case 13:\n k4 ^= bytes[i + 12];\n k4 = _x86Multiply(k4, c4);\n k4 = _x86Rotl(k4, 18);\n k4 = _x86Multiply(k4, c1);\n h4 ^= k4;\n\n case 12:\n k3 ^= bytes[i + 11] << 24;\n\n case 11:\n k3 ^= bytes[i + 10] << 16;\n\n case 10:\n k3 ^= bytes[i + 9] << 8;\n\n case 9:\n k3 ^= bytes[i + 8];\n k3 = _x86Multiply(k3, c3);\n k3 = _x86Rotl(k3, 17);\n k3 = _x86Multiply(k3, c4);\n h3 ^= k3;\n\n case 8:\n k2 ^= bytes[i + 7] << 24;\n\n case 7:\n k2 ^= bytes[i + 6] << 16;\n\n case 6:\n k2 ^= bytes[i + 5] << 8;\n\n case 5:\n k2 ^= bytes[i + 4];\n k2 = _x86Multiply(k2, c2);\n k2 = _x86Rotl(k2, 16);\n k2 = _x86Multiply(k2, c3);\n h2 ^= k2;\n\n case 4:\n k1 ^= bytes[i + 3] << 24;\n\n case 3:\n k1 ^= bytes[i + 2] << 16;\n\n case 2:\n k1 ^= bytes[i + 1] << 8;\n\n case 1:\n k1 ^= bytes[i];\n k1 = _x86Multiply(k1, c1);\n k1 = _x86Rotl(k1, 15);\n k1 = _x86Multiply(k1, c2);\n h1 ^= k1;\n }\n\n h1 ^= bytes.length;\n h2 ^= bytes.length;\n h3 ^= bytes.length;\n h4 ^= bytes.length;\n\n h1 += h2;\n h1 += h3;\n h1 += h4;\n h2 += h1;\n h3 += h1;\n h4 += h1;\n\n h1 = _x86Fmix(h1);\n h2 = _x86Fmix(h2);\n h3 = _x86Fmix(h3);\n h4 = _x86Fmix(h4);\n\n h1 += h2;\n h1 += h3;\n h1 += h4;\n h2 += h1;\n h3 += h1;\n h4 += h1;\n\n return (\"00000000\" + (h1 >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h2 >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h3 >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h4 >>> 0).toString(16)).slice(-8);\n };\n\n library.x64.hash128 = function (bytes, seed) {\n //\n // Given a string and an optional seed as an int, returns a 128 bit\n // hash using the x64 flavor of MurmurHash3, as an unsigned hex.\n //\n if (library.inputValidation && !_validBytes(bytes)) {\n return undefined;\n }\n seed = seed || 0;\n\n var remainder = bytes.length % 16;\n var blocks = bytes.length - remainder;\n\n var h1 = [0, seed];\n var h2 = [0, seed];\n\n var k1 = [0, 0];\n var k2 = [0, 0];\n\n var c1 = [0x87c37b91, 0x114253d5];\n var c2 = [0x4cf5ad43, 0x2745937f];\n\n for (var i = 0; i < blocks; i = i + 16) {\n k1 = [(bytes[i + 4]) | (bytes[i + 5] << 8) | (bytes[i + 6] << 16) | (bytes[i + 7] << 24), (bytes[i]) |\n (bytes[i + 1] << 8) | (bytes[i + 2] << 16) | (bytes[i + 3] << 24)];\n k2 = [(bytes[i + 12]) | (bytes[i + 13] << 8) | (bytes[i + 14] << 16) | (bytes[i + 15] << 24), (bytes[i + 8]) |\n (bytes[i + 9] << 8) | (bytes[i + 10] << 16) | (bytes[i + 11] << 24)];\n\n k1 = _x64Multiply(k1, c1);\n k1 = _x64Rotl(k1, 31);\n k1 = _x64Multiply(k1, c2);\n h1 = _x64Xor(h1, k1);\n\n h1 = _x64Rotl(h1, 27);\n h1 = _x64Add(h1, h2);\n h1 = _x64Add(_x64Multiply(h1, [0, 5]), [0, 0x52dce729]);\n\n k2 = _x64Multiply(k2, c2);\n k2 = _x64Rotl(k2, 33);\n k2 = _x64Multiply(k2, c1);\n h2 = _x64Xor(h2, k2);\n\n h2 = _x64Rotl(h2, 31);\n h2 = _x64Add(h2, h1);\n h2 = _x64Add(_x64Multiply(h2, [0, 5]), [0, 0x38495ab5]);\n }\n\n k1 = [0, 0];\n k2 = [0, 0];\n\n switch (remainder) {\n case 15:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 14]], 48));\n\n case 14:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 13]], 40));\n\n case 13:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 12]], 32));\n\n case 12:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 11]], 24));\n\n case 11:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 10]], 16));\n\n case 10:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 9]], 8));\n\n case 9:\n k2 = _x64Xor(k2, [0, bytes[i + 8]]);\n k2 = _x64Multiply(k2, c2);\n k2 = _x64Rotl(k2, 33);\n k2 = _x64Multiply(k2, c1);\n h2 = _x64Xor(h2, k2);\n\n case 8:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 7]], 56));\n\n case 7:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 6]], 48));\n\n case 6:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 5]], 40));\n\n case 5:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 4]], 32));\n\n case 4:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 3]], 24));\n\n case 3:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 2]], 16));\n\n case 2:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 1]], 8));\n\n case 1:\n k1 = _x64Xor(k1, [0, bytes[i]]);\n k1 = _x64Multiply(k1, c1);\n k1 = _x64Rotl(k1, 31);\n k1 = _x64Multiply(k1, c2);\n h1 = _x64Xor(h1, k1);\n }\n\n h1 = _x64Xor(h1, [0, bytes.length]);\n h2 = _x64Xor(h2, [0, bytes.length]);\n\n h1 = _x64Add(h1, h2);\n h2 = _x64Add(h2, h1);\n\n h1 = _x64Fmix(h1);\n h2 = _x64Fmix(h2);\n\n h1 = _x64Add(h1, h2);\n h2 = _x64Add(h2, h1);\n\n return (\"00000000\" + (h1[0] >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h1[1] >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h2[0] >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h2[1] >>> 0).toString(16)).slice(-8);\n };\n\n // INITIALIZATION\n // --------------\n\n // Export murmurHash3 for CommonJS, either as an AMD module or just as part\n // of the global object.\n if (typeof exports !== 'undefined') {\n\n if (typeof module !== 'undefined' && module.exports) {\n exports = module.exports = library;\n }\n\n exports.murmurHash3 = library;\n\n } else if (typeof define === 'function' && define.amd) {\n\n define([], function () {\n return library;\n });\n } else {\n\n // Use murmurHash3.noConflict to restore `murmurHash3` back to its\n // original value. Returns a reference to the library object, to allow\n // it to be used under a different name.\n library._murmurHash3 = root.murmurHash3;\n\n library.noConflict = function () {\n root.murmurHash3 = library._murmurHash3;\n library._murmurHash3 = undefined;\n library.noConflict = undefined;\n\n return library;\n };\n\n root.murmurHash3 = library;\n }\n})(this);\n","module.exports = require('./lib/murmurHash3js');\n","import * as API from \"./api.js\"\n// @ts-expect-error - has no types\nimport murmur from \"murmurhash3js-revisited\"\n\nconst utf8 = new TextEncoder()\n\n/**\n * @typedef {(bytes:Uint8Array) => API.Uint32} Hasher\n * @type {Hasher}\n */\nexport const hash32 = murmur.x64.hash126\n\n/**\n * @param {Partial>} options\n * @returns {API.Path