@helia/car 4.1.3 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../node_modules/varint/encode.js", "../../../node_modules/varint/decode.js", "../../../node_modules/varint/length.js", "../../../node_modules/varint/index.js", "../../../node_modules/eventemitter3/index.js", "../src/index.ts", "../../../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/cborg/lib/decode.js", "../../../node_modules/multiformats/src/bases/base32.ts", "../../../node_modules/multiformats/src/bytes.ts", "../../../node_modules/multiformats/src/vendor/base-x.js", "../../../node_modules/multiformats/src/bases/base.ts", "../../../node_modules/multiformats/src/bases/base36.ts", "../../../node_modules/multiformats/src/bases/base58.ts", "../../../node_modules/multiformats/src/vendor/varint.js", "../../../node_modules/multiformats/src/varint.ts", "../../../node_modules/multiformats/src/hashes/digest.ts", "../../../node_modules/multiformats/src/cid.ts", "../../../node_modules/@ipld/dag-cbor/src/index.js", "../../../node_modules/@ipld/car/src/decoder-common.js", "../../../node_modules/@ipld/car/src/header-validator.js", "../../../node_modules/cborg/lib/length.js", "../../../node_modules/@ipld/car/src/buffer-writer.js", "../../../node_modules/@ipld/car/src/decoder.js", "../../../node_modules/@ipld/car/src/encoder.js", "../../../node_modules/@ipld/car/src/iterator-channel.js", "../../../node_modules/@ipld/car/src/writer-browser.js", "../../../node_modules/it-drain/src/index.ts", "../../../node_modules/it-peekable/src/index.ts", "../../../node_modules/it-map/src/index.ts", "../../../node_modules/multiformats/src/hashes/hasher.ts", "../../../node_modules/multiformats/src/block.ts", "../../../node_modules/p-defer/index.js", "../../../node_modules/eventemitter3/index.mjs", "../../../node_modules/p-timeout/index.js", "../../../node_modules/p-queue/dist/lower-bound.js", "../../../node_modules/p-queue/dist/priority-queue.js", "../../../node_modules/p-queue/dist/index.js", "../src/export-strategies/subgraph-exporter.ts", "../src/traversal-strategies/graph-search.ts", "../src/car.ts", "../src/export-strategies/block-exporter.ts", "../src/errors.ts", "../src/export-strategies/unixfs-exporter.ts", "../src/traversal-strategies/cid-path.ts", "../../../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/ipfs-unixfs/src/errors.ts", "../../../node_modules/uint8arrays/src/alloc.ts", "../../../node_modules/uint8-varint/src/index.ts", "../../../node_modules/protons-runtime/src/utils/float.ts", "../../../node_modules/protons-runtime/src/utils/longbits.ts", "../../../node_modules/protons-runtime/src/utils/utf8.ts", "../../../node_modules/protons-runtime/src/utils/reader.ts", "../../../node_modules/protons-runtime/src/decode.ts", "../../../node_modules/multiformats/src/bases/base10.ts", "../../../node_modules/multiformats/src/bases/base16.ts", "../../../node_modules/multiformats/src/bases/base2.ts", "../../../node_modules/multiformats/src/bases/base256emoji.ts", "../../../node_modules/multiformats/src/bases/base64.ts", "../../../node_modules/multiformats/src/bases/base8.ts", "../../../node_modules/multiformats/src/bases/identity.ts", "../../../node_modules/multiformats/src/codecs/json.ts", "../../../node_modules/multiformats/src/hashes/identity.ts", "../../../node_modules/multiformats/src/hashes/sha2-browser.ts", "../../../node_modules/multiformats/src/basics.ts", "../../../node_modules/uint8arrays/src/util/bases.ts", "../../../node_modules/uint8arrays/src/from-string.ts", "../../../node_modules/protons-runtime/src/utils/pool.ts", "../../../node_modules/protons-runtime/src/utils/writer.ts", "../../../node_modules/protons-runtime/src/encode.ts", "../../../node_modules/protons-runtime/src/codec.ts", "../../../node_modules/protons-runtime/src/codecs/enum.ts", "../../../node_modules/protons-runtime/src/codecs/message.ts", "../../../node_modules/ipfs-unixfs/src/unixfs.ts", "../../../node_modules/ipfs-unixfs/src/index.ts", "../src/traversal-strategies/unixfs-path.ts"],
4
- "sourcesContent": ["module.exports = encode\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31)\n\nfunction encode(num, out, offset) {\n if (Number.MAX_SAFE_INTEGER && num > Number.MAX_SAFE_INTEGER) {\n encode.bytes = 0\n throw new RangeError('Could not encode varint')\n }\n out = out || []\n offset = offset || 0\n var oldOffset = offset\n\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 \n encode.bytes = offset - oldOffset + 1\n \n return out\n}\n", "module.exports = read\n\nvar MSB = 0x80\n , REST = 0x7F\n\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length\n\n do {\n if (counter >= l || shift > 49) {\n read.bytes = 0\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++]\n res += shift < 28\n ? (b & REST) << shift\n : (b & REST) * Math.pow(2, shift)\n shift += 7\n } while (b >= MSB)\n\n read.bytes = counter - offset\n\n return res\n}\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)\n\nmodule.exports = function (value) {\n return (\n 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 )\n}\n", "module.exports = {\n encode: require('./encode.js')\n , decode: require('./decode.js')\n , encodingLength: require('./length.js')\n}\n", "'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n", "/**\n * @packageDocumentation\n *\n * `@helia/car` provides `import` and `export` methods to read/write Car files\n * to {@link https://github.com/ipfs/helia Helia}'s blockstore.\n *\n * See the {@link Car} interface for all available operations.\n *\n * By default it supports `dag-pb`, `dag-cbor`, `dag-json` and `raw` CIDs, more\n * esoteric DAG walkers can be passed as an init option.\n *\n * @example Exporting a DAG as a CAR file\n *\n * ```typescript\n * import { createHelia } from 'helia'\n * import { car } from '@helia/car'\n * import { CID } from 'multiformats/cid'\n * import nodeFs from 'node:fs'\n *\n * const helia = await createHelia()\n * const cid = CID.parse('QmFoo...')\n *\n * const c = car(helia)\n * const out = nodeFs.createWriteStream('example.car')\n *\n * for await (const buf of c.stream(cid)) {\n * out.write(buf)\n * }\n *\n * out.end()\n * ```\n *\n * @example Exporting a part of a UnixFS DAG as a CAR file\n *\n * ```typescript\n * import { createHelia } from 'helia'\n * import { car, UnixFSPath } from '@helia/car'\n * import { CID } from 'multiformats/cid'\n * import nodeFs from 'node:fs'\n *\n * const helia = await createHelia()\n * const cid = CID.parse('QmFoo...')\n *\n * const c = car(helia)\n * const out = nodeFs.createWriteStream('example.car')\n *\n * for await (const buf of c.stream(cid, {\n * traversal: new UnixFSPath('/foo/bar/baz.txt')\n * })) {\n * out.write(buf)\n * }\n *\n * out.end()\n * ```\n *\n * @example Importing all blocks from a CAR file\n *\n * ```typescript\n * import { createHelia } from 'helia'\n * import { unixfs } from '@helia/unixfs'\n * import { car } from '@helia/car'\n * import { CarReader } from '@ipld/car'\n * import { Readable } from 'node:stream'\n * import nodeFs from 'node:fs'\n *\n * const helia = await createHelia({\n * // ... helia config\n * })\n *\n * // import the car\n * const inStream = nodeFs.createReadStream('example.car')\n * const reader = await CarReader.fromIterable(inStream)\n *\n * const c = car(helia)\n * await c.import(reader)\n * ```\n */\n\nimport { Car as CarClass } from './car.js'\nimport type { CodecLoader } from '@helia/interface'\nimport type { PutManyBlocksProgressEvents, GetBlockProgressEvents } from '@helia/interface/blocks'\nimport type { CarWriter, CarReader } from '@ipld/car'\nimport type { AbortOptions, ComponentLogger } from '@libp2p/interface'\nimport type { Filter } from '@libp2p/utils/filters'\nimport type { Blockstore } from 'interface-blockstore'\nimport type { BlockView } from 'multiformats/block/interface'\nimport type { CID } from 'multiformats/cid'\nimport type { ProgressOptions } from 'progress-events'\n\nexport interface CarComponents {\n logger: ComponentLogger\n blockstore: Blockstore\n getCodec: CodecLoader\n}\n\n/**\n * Interface for different traversal strategies.\n *\n * While traversing the DAG, it will yield blocks that it has traversed.\n */\nexport interface TraversalStrategy {\n /**\n * Traverse the DAG and yield the next CID to traverse\n */\n traverse<T extends BlockView<any, any, any, 0 | 1>>(cid: CID, block: T): AsyncGenerator<CID, void, undefined>\n\n /**\n * Returns true if the current CID is the target and we should switch to the\n * export strategy\n */\n isTarget(cid: CID): boolean\n}\n\n/**\n * Interface for different export strategies.\n *\n * When traversal has ended the export begins starting at the target CID, and\n * the export strategy may do further traversal and writing to the car file.\n */\nexport interface ExportStrategy {\n /**\n * Export the DAG and yield the next CID to traverse\n */\n export<T extends BlockView<any, any, any, 0 | 1>>(cid: CID, block: T): AsyncGenerator<CID, void, undefined>\n}\n\nexport * from './export-strategies/index.js'\nexport * from './traversal-strategies/index.js'\n\nexport interface ExportCarOptions extends AbortOptions, ProgressOptions<GetBlockProgressEvents> {\n\n /**\n * If true, the blockstore will not do any network requests.\n *\n * @default false\n */\n offline?: boolean\n\n /**\n * If a filter is passed it will be used to deduplicate blocks exported in the\n * car file\n */\n blockFilter?: Filter\n\n /**\n * The traversal strategy to use for the export. This determines how the dag\n * is traversed: either depth first, breadth first, or a custom strategy.\n */\n traversal?: TraversalStrategy\n\n /**\n * Export strategy to use for the export. This should be used to change the\n * blocks included in the exported car file. (e.g. https://specs.ipfs.tech/http-gateways/trustless-gateway/#dag-scope-request-query-parameter)\n */\n exporter?: ExportStrategy\n}\n\n/**\n * The Car interface provides operations for importing and exporting Car files\n * from Helia's underlying blockstore.\n */\nexport interface Car {\n /**\n * Add all blocks in the passed CarReader to the blockstore.\n *\n * @example\n *\n * ```typescript\n * import fs from 'node:fs'\n * import { createHelia } from 'helia'\n * import { car } from '@helia/car\n * import { CarReader } from '@ipld/car'\n *\n * const helia = await createHelia()\n *\n * const inStream = fs.createReadStream('example.car')\n * const reader = await CarReader.fromIterable(inStream)\n *\n * const c = car(helia)\n * await c.import(reader)\n * ```\n */\n import(reader: Pick<CarReader, 'blocks'>, options?: AbortOptions & ProgressOptions<PutManyBlocksProgressEvents>): Promise<void>\n\n /**\n * Store all blocks that make up one or more DAGs in a car file.\n *\n * @example\n *\n * ```typescript\n * import fs from 'node:fs'\n * import { Readable } from 'node:stream'\n * import { car } from '@helia/car'\n * import { CarWriter } from '@ipld/car'\n * import { createHelia } from 'helia'\n * import { CID } from 'multiformats/cid'\n * import { pEvent } from 'p-event'\n *\n * const helia = await createHelia()\n * const cid = CID.parse('QmFoo...')\n *\n * const c = car(helia)\n * const { writer, out } = CarWriter.create(cid)\n * const output = fs.createWriteStream('example.car')\n * const stream = Readable.from(out).pipe(output)\n *\n * await Promise.all([\n * c.export(cid, writer),\n * pEvent(stream, 'close')\n * ])\n * ```\n *\n * @deprecated Use `stream` instead. In a future release `stream` will be renamed `export`.\n */\n export(root: CID | CID[], writer: Pick<CarWriter, 'put' | 'close'>, options?: ExportCarOptions): Promise<void>\n\n /**\n * Returns an AsyncGenerator that yields CAR file bytes.\n *\n * @example\n *\n * ```typescript\n * import { createHelia } from 'helia'\n * import { car } from '@helia/car'\n * import { CID } from 'multiformats/cid'\n *\n * const helia = await createHelia()\n * const cid = CID.parse('QmFoo...')\n *\n * const c = car(helia)\n *\n * for (const buf of c.stream(cid)) {\n * // store or send `buf` somewhere\n * }\n * ```\n */\n stream(root: CID | CID[], options?: ExportCarOptions): AsyncGenerator<Uint8Array, void, undefined>\n}\n\n/**\n * Create a {@link Car} instance for use with {@link https://github.com/ipfs/helia Helia}\n */\nexport function car (helia: CarComponents, init: any = {}): Car {\n return new CarClass(helia, init)\n}\n", "// This is an unfortunate replacement for @sindresorhus/is that we need to\n// re-implement for performance purposes. In particular the is.observable()\n// check is expensive, and unnecessary for our purposes. The values returned\n// are compatible with @sindresorhus/is, however.\n\nconst typeofs = [\n 'string',\n 'number',\n 'bigint',\n 'symbol'\n]\n\nconst objectTypeNames = [\n 'Function',\n 'Generator',\n 'AsyncGenerator',\n 'GeneratorFunction',\n 'AsyncGeneratorFunction',\n 'AsyncFunction',\n 'Observable',\n 'Array',\n 'Buffer',\n 'Object',\n 'RegExp',\n 'Date',\n 'Error',\n 'Map',\n 'Set',\n 'WeakMap',\n 'WeakSet',\n 'ArrayBuffer',\n 'SharedArrayBuffer',\n 'DataView',\n 'Promise',\n 'URL',\n 'HTMLElement',\n 'Int8Array',\n 'Uint8Array',\n 'Uint8ClampedArray',\n 'Int16Array',\n 'Uint16Array',\n 'Int32Array',\n 'Uint32Array',\n 'Float32Array',\n 'Float64Array',\n 'BigInt64Array',\n 'BigUint64Array'\n]\n\n/**\n * @param {any} value\n * @returns {string}\n */\nexport function is (value) {\n if (value === null) {\n return 'null'\n }\n if (value === undefined) {\n return 'undefined'\n }\n if (value === true || value === false) {\n return 'boolean'\n }\n const typeOf = typeof value\n if (typeofs.includes(typeOf)) {\n return typeOf\n }\n /* c8 ignore next 4 */\n // not going to bother testing this, it's not going to be valid anyway\n if (typeOf === 'function') {\n return 'Function'\n }\n if (Array.isArray(value)) {\n return 'Array'\n }\n if (isBuffer(value)) {\n return 'Buffer'\n }\n const objectType = getObjectType(value)\n if (objectType) {\n return objectType\n }\n /* c8 ignore next */\n return 'Object'\n}\n\n/**\n * @param {any} value\n * @returns {boolean}\n */\nfunction isBuffer (value) {\n return value && value.constructor && value.constructor.isBuffer && value.constructor.isBuffer.call(null, value)\n}\n\n/**\n * @param {any} value\n * @returns {string|undefined}\n */\nfunction getObjectType (value) {\n const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)\n if (objectTypeNames.includes(objectTypeName)) {\n return objectTypeName\n }\n /* c8 ignore next */\n return undefined\n}\n", "class Type {\n /**\n * @param {number} major\n * @param {string} name\n * @param {boolean} terminal\n */\n constructor (major, name, terminal) {\n this.major = major\n this.majorEncoded = major << 5\n this.name = name\n this.terminal = terminal\n }\n\n /* c8 ignore next 3 */\n toString () {\n return `Type[${this.major}].${this.name}`\n }\n\n /**\n * @param {Type} typ\n * @returns {number}\n */\n compare (typ) {\n /* c8 ignore next 1 */\n return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0\n }\n}\n\n// convert to static fields when better supported\nType.uint = new Type(0, 'uint', true)\nType.negint = new Type(1, 'negint', true)\nType.bytes = new Type(2, 'bytes', true)\nType.string = new Type(3, 'string', true)\nType.array = new Type(4, 'array', false)\nType.map = new Type(5, 'map', false)\nType.tag = new Type(6, 'tag', false) // terminal?\nType.float = new Type(7, 'float', true)\nType.false = new Type(7, 'false', true)\nType.true = new Type(7, 'true', true)\nType.null = new Type(7, 'null', true)\nType.undefined = new Type(7, 'undefined', true)\nType.break = new Type(7, 'break', true)\n// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)\n\nclass Token {\n /**\n * @param {Type} type\n * @param {any} [value]\n * @param {number} [encodedLength]\n */\n constructor (type, value, encodedLength) {\n this.type = type\n this.value = value\n this.encodedLength = encodedLength\n /** @type {Uint8Array|undefined} */\n this.encodedBytes = undefined\n /** @type {Uint8Array|undefined} */\n this.byteValue = undefined\n }\n\n /* c8 ignore next 3 */\n toString () {\n return `Token[${this.type}].${this.value}`\n }\n}\n\nexport { Type, Token }\n", "// Use Uint8Array directly in the browser, use Buffer in Node.js but don't\n// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill\n\n// @ts-ignore\nexport const useBuffer = globalThis.process &&\n // @ts-ignore\n !globalThis.process.browser &&\n // @ts-ignore\n globalThis.Buffer &&\n // @ts-ignore\n typeof globalThis.Buffer.isBuffer === 'function'\n\nconst textDecoder = new TextDecoder()\nconst textEncoder = new TextEncoder()\n\n/**\n * @param {Uint8Array} buf\n * @returns {boolean}\n */\nfunction isBuffer (buf) {\n // @ts-ignore\n return useBuffer && globalThis.Buffer.isBuffer(buf)\n}\n\n/**\n * @param {Uint8Array|number[]} buf\n * @returns {Uint8Array}\n */\nexport function asU8A (buf) {\n /* c8 ignore next */\n if (!(buf instanceof Uint8Array)) {\n return Uint8Array.from(buf)\n }\n return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf\n}\n\nexport const toString = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n (bytes, start, end) => {\n return end - start > 64\n ? // eslint-disable-line operator-linebreak\n // @ts-ignore\n globalThis.Buffer.from(bytes.subarray(start, end)).toString('utf8')\n : utf8Slice(bytes, start, end)\n }\n /* c8 ignore next 11 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n (bytes, start, end) => {\n return end - start > 64\n ? textDecoder.decode(bytes.subarray(start, end))\n : utf8Slice(bytes, start, end)\n }\n\nexport const fromString = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {string} string\n */\n (string) => {\n return string.length > 64\n ? // eslint-disable-line operator-linebreak\n // @ts-ignore\n globalThis.Buffer.from(string)\n : utf8ToBytes(string)\n }\n /* c8 ignore next 7 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {string} string\n */\n (string) => {\n return string.length > 64 ? textEncoder.encode(string) : utf8ToBytes(string)\n }\n\n/**\n * Buffer variant not fast enough for what we need\n * @param {number[]} arr\n * @returns {Uint8Array}\n */\nexport const fromArray = (arr) => {\n return Uint8Array.from(arr)\n}\n\nexport const slice = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n (bytes, start, end) => {\n if (isBuffer(bytes)) {\n return new Uint8Array(bytes.subarray(start, end))\n }\n return bytes.slice(start, end)\n }\n /* c8 ignore next 9 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n (bytes, start, end) => {\n return bytes.slice(start, end)\n }\n\nexport const concat = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array[]} chunks\n * @param {number} length\n * @returns {Uint8Array}\n */\n (chunks, length) => {\n // might get a stray plain Array here\n /* c8 ignore next 1 */\n chunks = chunks.map((c) => c instanceof Uint8Array\n ? c\n // this case is occasionally missed during test runs so becomes coverage-flaky\n /* c8 ignore next 4 */\n : // eslint-disable-line operator-linebreak\n // @ts-ignore\n globalThis.Buffer.from(c))\n // @ts-ignore\n return asU8A(globalThis.Buffer.concat(chunks, length))\n }\n /* c8 ignore next 19 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array[]} chunks\n * @param {number} length\n * @returns {Uint8Array}\n */\n (chunks, length) => {\n const out = new Uint8Array(length)\n let off = 0\n for (let b of chunks) {\n if (off + b.length > out.length) {\n // final chunk that's bigger than we need\n b = b.subarray(0, out.length - off)\n }\n out.set(b, off)\n off += b.length\n }\n return out\n }\n\nexport const alloc = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {number} size\n * @returns {Uint8Array}\n */\n (size) => {\n // we always write over the contents we expose so this should be safe\n // @ts-ignore\n return globalThis.Buffer.allocUnsafe(size)\n }\n /* c8 ignore next 8 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {number} size\n * @returns {Uint8Array}\n */\n (size) => {\n return new Uint8Array(size)\n }\n\nexport const toHex = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} d\n * @returns {string}\n */\n (d) => {\n if (typeof d === 'string') {\n return d\n }\n // @ts-ignore\n return globalThis.Buffer.from(toBytes(d)).toString('hex')\n }\n /* c8 ignore next 12 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} d\n * @returns {string}\n */\n (d) => {\n if (typeof d === 'string') {\n return d\n }\n // @ts-ignore not smart enough to figure this out\n return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')\n }\n\nexport const fromHex = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {string|Uint8Array} hex\n * @returns {Uint8Array}\n */\n (hex) => {\n if (hex instanceof Uint8Array) {\n return hex\n }\n // @ts-ignore\n return globalThis.Buffer.from(hex, 'hex')\n }\n /* c8 ignore next 17 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {string|Uint8Array} hex\n * @returns {Uint8Array}\n */\n (hex) => {\n if (hex instanceof Uint8Array) {\n return hex\n }\n if (!hex.length) {\n return new Uint8Array(0)\n }\n return new Uint8Array(hex.split('')\n .map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')\n .filter(Boolean)\n .map((/** @type {string} */ e) => parseInt(e, 16)))\n }\n\n/**\n * @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj\n * @returns {Uint8Array}\n */\nfunction toBytes (obj) {\n if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {\n return obj\n }\n if (obj instanceof ArrayBuffer) {\n return new Uint8Array(obj)\n }\n if (ArrayBuffer.isView(obj)) {\n return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)\n }\n /* c8 ignore next */\n throw new Error('Unknown type, must be binary type')\n}\n\n/**\n * @param {Uint8Array} b1\n * @param {Uint8Array} b2\n * @returns {number}\n */\nexport function compare (b1, b2) {\n /* c8 ignore next 5 */\n if (isBuffer(b1) && isBuffer(b2)) {\n // probably not possible to get here in the current API\n // @ts-ignore Buffer\n return b1.compare(b2)\n }\n for (let i = 0; i < b1.length; i++) {\n if (b1[i] === b2[i]) {\n continue\n }\n return b1[i] < b2[i] ? -1 : 1\n } /* c8 ignore next 3 */\n return 0\n}\n\n// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143\n// Licensed Apache-2.0.\n\n/**\n * @param {string} str\n * @returns {number[]}\n */\nfunction utf8ToBytes (str) {\n const out = []\n let p = 0\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i)\n if (c < 128) {\n out[p++] = c\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192\n out[p++] = (c & 63) | 128\n } else if (\n ((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&\n ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {\n // Surrogate Pair\n c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)\n out[p++] = (c >> 18) | 240\n out[p++] = ((c >> 12) & 63) | 128\n out[p++] = ((c >> 6) & 63) | 128\n out[p++] = (c & 63) | 128\n } else {\n out[p++] = (c >> 12) | 224\n out[p++] = ((c >> 6) & 63) | 128\n out[p++] = (c & 63) | 128\n }\n }\n return out\n}\n\n// The below code is mostly taken from https://github.com/feross/buffer\n// Licensed MIT. Copyright (c) Feross Aboukhadijeh\n\n/**\n * @param {Uint8Array} buf\n * @param {number} offset\n * @param {number} end\n * @returns {string}\n */\nfunction utf8Slice (buf, offset, end) {\n const res = []\n\n while (offset < end) {\n const firstByte = buf[offset]\n let codePoint = null\n let bytesPerSequence = (firstByte > 0xef) ? 4 : (firstByte > 0xdf) ? 3 : (firstByte > 0xbf) ? 2 : 1\n\n if (offset + bytesPerSequence <= end) {\n let secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[offset + 1]\n if ((secondByte & 0xc0) === 0x80) {\n tempCodePoint = (firstByte & 0x1f) << 0x6 | (secondByte & 0x3f)\n if (tempCodePoint > 0x7f) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[offset + 1]\n thirdByte = buf[offset + 2]\n if ((secondByte & 0xc0) === 0x80 && (thirdByte & 0xc0) === 0x80) {\n tempCodePoint = (firstByte & 0xf) << 0xc | (secondByte & 0x3f) << 0x6 | (thirdByte & 0x3f)\n /* c8 ignore next 3 */\n if (tempCodePoint > 0x7ff && (tempCodePoint < 0xd800 || tempCodePoint > 0xdfff)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[offset + 1]\n thirdByte = buf[offset + 2]\n fourthByte = buf[offset + 3]\n if ((secondByte & 0xc0) === 0x80 && (thirdByte & 0xc0) === 0x80 && (fourthByte & 0xc0) === 0x80) {\n tempCodePoint = (firstByte & 0xf) << 0x12 | (secondByte & 0x3f) << 0xc | (thirdByte & 0x3f) << 0x6 | (fourthByte & 0x3f)\n if (tempCodePoint > 0xffff && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n /* c8 ignore next 5 */\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xfffd\n bytesPerSequence = 1\n } else if (codePoint > 0xffff) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3ff | 0xd800)\n codePoint = 0xdc00 | codePoint & 0x3ff\n }\n\n res.push(codePoint)\n offset += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nconst MAX_ARGUMENTS_LENGTH = 0x1000\n\n/**\n * @param {number[]} codePoints\n * @returns {string}\n */\nexport function decodeCodePointsArray (codePoints) {\n const len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n /* c8 ignore next 10 */\n // Decode in chunks to avoid \"call stack size exceeded\".\n let res = ''\n let i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n", "/**\n * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for\n * writing rather than reading.\n * A Bl object accepts set() operations for individual bytes and copyTo() for\n * inserting byte arrays. These write operations don't automatically increment\n * the internal cursor so its \"length\" won't be changed. Instead, increment()\n * must be called to extend its length to cover the inserted data.\n * The toBytes() call will convert all internal memory to a single Uint8Array of\n * the correct length, truncating any data that is stored but hasn't been\n * included by an increment().\n * get() can retrieve a single byte.\n * All operations (except toBytes()) take an \"offset\" argument that will perform\n * the write at the offset _from the current cursor_. For most operations this\n * will be `0` to write at the current cursor position but it can be ahead of\n * the current cursor. Negative offsets probably work but are untested.\n */\n\n// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39\nimport { alloc, concat, slice } from './byte-utils.js'\n\n// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists\n// for perf reasons. Consider better approaches to this or removing it entirely, it is quite\n// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.\n\nconst defaultChunkSize = 256\n\nexport class Bl {\n /**\n * @param {number} [chunkSize]\n */\n constructor (chunkSize = defaultChunkSize) {\n this.chunkSize = chunkSize\n /** @type {number} */\n this.cursor = 0\n /** @type {number} */\n this.maxCursor = -1\n /** @type {(Uint8Array|number[])[]} */\n this.chunks = []\n // keep the first chunk around if we can to save allocations for future encodes\n /** @type {Uint8Array|number[]|null} */\n this._initReuseChunk = null\n }\n\n reset () {\n this.cursor = 0\n this.maxCursor = -1\n if (this.chunks.length) {\n this.chunks = []\n }\n if (this._initReuseChunk !== null) {\n this.chunks.push(this._initReuseChunk)\n this.maxCursor = this._initReuseChunk.length - 1\n }\n }\n\n /**\n * @param {Uint8Array|number[]} bytes\n */\n push (bytes) {\n let topChunk = this.chunks[this.chunks.length - 1]\n const newMax = this.cursor + bytes.length\n if (newMax <= this.maxCursor + 1) {\n // we have at least one chunk and we can fit these bytes into that chunk\n const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1\n // @ts-ignore\n topChunk.set(bytes, chunkPos)\n } else {\n // can't fit it in\n if (topChunk) {\n // trip the last chunk to `cursor` if we need to\n const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1\n if (chunkPos < topChunk.length) {\n // @ts-ignore\n this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)\n this.maxCursor = this.cursor - 1\n }\n }\n if (bytes.length < 64 && bytes.length < this.chunkSize) {\n // make a new chunk and copy the new one into it\n topChunk = alloc(this.chunkSize)\n this.chunks.push(topChunk)\n this.maxCursor += topChunk.length\n if (this._initReuseChunk === null) {\n this._initReuseChunk = topChunk\n }\n // @ts-ignore\n topChunk.set(bytes, 0)\n } else {\n // push the new bytes in as its own chunk\n this.chunks.push(bytes)\n this.maxCursor += bytes.length\n }\n }\n this.cursor += bytes.length\n }\n\n /**\n * @param {boolean} [reset]\n * @returns {Uint8Array}\n */\n toBytes (reset = false) {\n let byts\n if (this.chunks.length === 1) {\n const chunk = this.chunks[0]\n if (reset && this.cursor > chunk.length / 2) {\n /* c8 ignore next 2 */\n // @ts-ignore\n byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)\n this._initReuseChunk = null\n this.chunks = []\n } else {\n // @ts-ignore\n byts = slice(chunk, 0, this.cursor)\n }\n } else {\n // @ts-ignore\n byts = concat(this.chunks, this.cursor)\n }\n if (reset) {\n this.reset()\n }\n return byts\n }\n}\n", "const decodeErrPrefix = 'CBOR decode error:'\nconst encodeErrPrefix = 'CBOR encode error:'\n\nconst uintMinorPrefixBytes = []\nuintMinorPrefixBytes[23] = 1\nuintMinorPrefixBytes[24] = 2\nuintMinorPrefixBytes[25] = 3\nuintMinorPrefixBytes[26] = 5\nuintMinorPrefixBytes[27] = 9\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} need\n */\nfunction assertEnoughData (data, pos, need) {\n if (data.length - pos < need) {\n throw new Error(`${decodeErrPrefix} not enough data for type`)\n }\n}\n\nexport {\n decodeErrPrefix,\n encodeErrPrefix,\n uintMinorPrefixBytes,\n assertEnoughData\n}\n", "/* globals BigInt */\n\nimport { Token, Type } from './token.js'\nimport { decodeErrPrefix, assertEnoughData } from './common.js'\n\nexport const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint8 (data, offset, options) {\n assertEnoughData(data, offset, 1)\n const value = data[offset]\n if (options.strict === true && value < uintBoundaries[0]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint16 (data, offset, options) {\n assertEnoughData(data, offset, 2)\n const value = (data[offset] << 8) | data[offset + 1]\n if (options.strict === true && value < uintBoundaries[1]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint32 (data, offset, options) {\n assertEnoughData(data, offset, 4)\n const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]\n if (options.strict === true && value < uintBoundaries[2]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number|bigint}\n */\nexport function readUint64 (data, offset, options) {\n // assume BigInt, convert back to Number if within safe range\n assertEnoughData(data, offset, 8)\n const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]\n const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]\n const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)\n if (options.strict === true && value < uintBoundaries[3]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n if (value <= Number.MAX_SAFE_INTEGER) {\n return Number(value)\n }\n if (options.allowBigInt === true) {\n return value\n }\n throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)\n}\n\n/* not required thanks to quick[] list\nconst oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))\nexport function decodeUintCompact (data, pos, minor, options) {\n return oneByteTokens[minor]\n}\n*/\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint8 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint16 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint32 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint32(data, pos + 1, options), 5)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint64 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint64(data, pos + 1, options), 9)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeUint (buf, token) {\n return encodeUintValue(buf, 0, token.value)\n}\n\n/**\n * @param {Bl} buf\n * @param {number} major\n * @param {number|bigint} uint\n */\nexport function encodeUintValue (buf, major, uint) {\n if (uint < uintBoundaries[0]) {\n const nuint = Number(uint)\n // pack into one byte, minor=0, additional=value\n buf.push([major | nuint])\n } else if (uint < uintBoundaries[1]) {\n const nuint = Number(uint)\n // pack into two byte, minor=0, additional=24\n buf.push([major | 24, nuint])\n } else if (uint < uintBoundaries[2]) {\n const nuint = Number(uint)\n // pack into three byte, minor=0, additional=25\n buf.push([major | 25, nuint >>> 8, nuint & 0xff])\n } else if (uint < uintBoundaries[3]) {\n const nuint = Number(uint)\n // pack into five byte, minor=0, additional=26\n buf.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])\n } else {\n const buint = BigInt(uint)\n if (buint < uintBoundaries[4]) {\n // pack into nine byte, minor=0, additional=27\n const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]\n // simulate bitwise above 32 bits\n let lo = Number(buint & BigInt(0xffffffff))\n let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))\n set[8] = lo & 0xff\n lo = lo >> 8\n set[7] = lo & 0xff\n lo = lo >> 8\n set[6] = lo & 0xff\n lo = lo >> 8\n set[5] = lo & 0xff\n set[4] = hi & 0xff\n hi = hi >> 8\n set[3] = hi & 0xff\n hi = hi >> 8\n set[2] = hi & 0xff\n hi = hi >> 8\n set[1] = hi & 0xff\n buf.push(set)\n } else {\n throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`)\n }\n }\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeUint.encodedSize = function encodedSize (token) {\n return encodeUintValue.encodedSize(token.value)\n}\n\n/**\n * @param {number} uint\n * @returns {number}\n */\nencodeUintValue.encodedSize = function encodedSize (uint) {\n if (uint < uintBoundaries[0]) {\n return 1\n }\n if (uint < uintBoundaries[1]) {\n return 2\n }\n if (uint < uintBoundaries[2]) {\n return 3\n }\n if (uint < uintBoundaries[3]) {\n return 5\n }\n return 9\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeUint.compareTokens = function compareTokens (tok1, tok2) {\n return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : /* c8 ignore next */ 0\n}\n", "/* eslint-env es2020 */\n\nimport { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint8 (data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint16 (data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint32 (data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5)\n}\n\nconst neg1b = BigInt(-1)\nconst pos1b = BigInt(1)\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint64 (data, pos, _minor, options) {\n const int = uint.readUint64(data, pos + 1, options)\n if (typeof int !== 'bigint') {\n const value = -1 - int\n if (value >= Number.MIN_SAFE_INTEGER) {\n return new Token(Type.negint, value, 9)\n }\n }\n if (options.allowBigInt !== true) {\n throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)\n }\n return new Token(Type.negint, neg1b - BigInt(int), 9)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeNegint (buf, token) {\n const negint = token.value\n const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))\n uint.encodeUintValue(buf, token.type.majorEncoded, unsigned)\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeNegint.encodedSize = function encodedSize (token) {\n const negint = token.value\n const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))\n /* c8 ignore next 4 */\n // handled by quickEncode, we shouldn't get here but it's included for completeness\n if (unsigned < uint.uintBoundaries[0]) {\n return 1\n }\n if (unsigned < uint.uintBoundaries[1]) {\n return 2\n }\n if (unsigned < uint.uintBoundaries[2]) {\n return 3\n }\n if (unsigned < uint.uintBoundaries[3]) {\n return 5\n }\n return 9\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeNegint.compareTokens = function compareTokens (tok1, tok2) {\n // opposite of the uint comparison since we store the uint version in bytes\n return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : /* c8 ignore next */ 0\n}\n", "import { Token, Type } from './token.js'\nimport { assertEnoughData, decodeErrPrefix } from './common.js'\nimport * as uint from './0uint.js'\nimport { compare, fromString, slice } from './byte-utils.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (data, pos, prefix, length) {\n assertEnoughData(data, pos, prefix + length)\n const buf = slice(data, pos + prefix, pos + prefix + length)\n return new Token(Type.bytes, buf, prefix + length)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeBytesCompact (data, pos, minor, _options) {\n return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`)\n }\n return toToken(data, pos, 9, l)\n}\n\n/**\n * `encodedBytes` allows for caching when we do a byte version of a string\n * for key sorting purposes\n * @param {Token} token\n * @returns {Uint8Array}\n */\nfunction tokenBytes (token) {\n if (token.encodedBytes === undefined) {\n token.encodedBytes = token.type === Type.string ? fromString(token.value) : token.value\n }\n // @ts-ignore c'mon\n return token.encodedBytes\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeBytes (buf, token) {\n const bytes = tokenBytes(token)\n uint.encodeUintValue(buf, token.type.majorEncoded, bytes.length)\n buf.push(bytes)\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeBytes.encodedSize = function encodedSize (token) {\n const bytes = tokenBytes(token)\n return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeBytes.compareTokens = function compareTokens (tok1, tok2) {\n return compareBytes(tokenBytes(tok1), tokenBytes(tok2))\n}\n\n/**\n * @param {Uint8Array} b1\n * @param {Uint8Array} b2\n * @returns {number}\n */\nexport function compareBytes (b1, b2) {\n return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2)\n}\n", "import { Token, Type } from './token.js'\nimport { assertEnoughData, decodeErrPrefix } from './common.js'\nimport * as uint from './0uint.js'\nimport { encodeBytes } from './2bytes.js'\nimport { toString, slice } from './byte-utils.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} prefix\n * @param {number} length\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nfunction toToken (data, pos, prefix, length, options) {\n const totLength = prefix + length\n assertEnoughData(data, pos, totLength)\n const tok = new Token(Type.string, toString(data, pos + prefix, pos + totLength), totLength)\n if (options.retainStringBytes === true) {\n tok.byteValue = slice(data, pos + prefix, pos + totLength)\n }\n return tok\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeStringCompact (data, pos, minor, options) {\n return toToken(data, pos, 1, minor, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options)\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`)\n }\n return toToken(data, pos, 9, l, options)\n}\n\nexport const encodeString = encodeBytes\n", "import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (_data, _pos, prefix, length) {\n return new Token(Type.array, length, prefix)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeArrayCompact (data, pos, minor, _options) {\n return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`)\n }\n return toToken(data, pos, 9, l)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArrayIndefinite (data, pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n }\n return toToken(data, pos, 1, Infinity)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeArray (buf, token) {\n uint.encodeUintValue(buf, Type.array.majorEncoded, token.value)\n}\n\n// using an array as a map key, are you sure about this? we can only sort\n// by map length here, it's up to the encoder to decide to look deeper\nencodeArray.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeArray.encodedSize = function encodedSize (token) {\n return uint.encodeUintValue.encodedSize(token.value)\n}\n", "import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (_data, _pos, prefix, length) {\n return new Token(Type.map, length, prefix)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeMapCompact (data, pos, minor, _options) {\n return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`)\n }\n return toToken(data, pos, 9, l)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMapIndefinite (data, pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n }\n return toToken(data, pos, 1, Infinity)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeMap (buf, token) {\n uint.encodeUintValue(buf, Type.map.majorEncoded, token.value)\n}\n\n// using a map as a map key, are you sure about this? we can only sort\n// by map length here, it's up to the encoder to decide to look deeper\nencodeMap.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeMap.encodedSize = function encodedSize (token) {\n return uint.encodeUintValue.encodedSize(token.value)\n}\n", "import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeTagCompact (_data, _pos, minor, _options) {\n return new Token(Type.tag, minor, 1)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag8 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag16 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag32 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag64 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeTag (buf, token) {\n uint.encodeUintValue(buf, Type.tag.majorEncoded, token.value)\n}\n\nencodeTag.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeTag.encodedSize = function encodedSize (token) {\n return uint.encodeUintValue.encodedSize(token.value)\n}\n", "// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer\n// where possible\n\nimport { Token, Type } from './token.js'\nimport { decodeErrPrefix } from './common.js'\nimport { encodeUint } from './0uint.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n * @typedef {import('../interface').EncodeOptions} EncodeOptions\n */\n\nconst MINOR_FALSE = 20\nconst MINOR_TRUE = 21\nconst MINOR_NULL = 22\nconst MINOR_UNDEFINED = 23\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUndefined (_data, _pos, _minor, options) {\n if (options.allowUndefined === false) {\n throw new Error(`${decodeErrPrefix} undefined values are not supported`)\n } else if (options.coerceUndefinedToNull === true) {\n return new Token(Type.null, null, 1)\n }\n return new Token(Type.undefined, undefined, 1)\n}\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBreak (_data, _pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n }\n return new Token(Type.break, undefined, 1)\n}\n\n/**\n * @param {number} value\n * @param {number} bytes\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nfunction createToken (value, bytes, options) {\n if (options) {\n if (options.allowNaN === false && Number.isNaN(value)) {\n throw new Error(`${decodeErrPrefix} NaN values are not supported`)\n }\n if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {\n throw new Error(`${decodeErrPrefix} Infinity values are not supported`)\n }\n }\n return new Token(Type.float, value, bytes)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat16 (data, pos, _minor, options) {\n return createToken(readFloat16(data, pos + 1), 3, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat32 (data, pos, _minor, options) {\n return createToken(readFloat32(data, pos + 1), 5, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat64 (data, pos, _minor, options) {\n return createToken(readFloat64(data, pos + 1), 9, options)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n * @param {EncodeOptions} options\n */\nexport function encodeFloat (buf, token, options) {\n const float = token.value\n\n if (float === false) {\n buf.push([Type.float.majorEncoded | MINOR_FALSE])\n } else if (float === true) {\n buf.push([Type.float.majorEncoded | MINOR_TRUE])\n } else if (float === null) {\n buf.push([Type.float.majorEncoded | MINOR_NULL])\n } else if (float === undefined) {\n buf.push([Type.float.majorEncoded | MINOR_UNDEFINED])\n } else {\n let decoded\n let success = false\n if (!options || options.float64 !== true) {\n encodeFloat16(float)\n decoded = readFloat16(ui8a, 1)\n if (float === decoded || Number.isNaN(float)) {\n ui8a[0] = 0xf9\n buf.push(ui8a.slice(0, 3))\n success = true\n } else {\n encodeFloat32(float)\n decoded = readFloat32(ui8a, 1)\n if (float === decoded) {\n ui8a[0] = 0xfa\n buf.push(ui8a.slice(0, 5))\n success = true\n }\n }\n }\n if (!success) {\n encodeFloat64(float)\n decoded = readFloat64(ui8a, 1)\n ui8a[0] = 0xfb\n buf.push(ui8a.slice(0, 9))\n }\n }\n}\n\n/**\n * @param {Token} token\n * @param {EncodeOptions} options\n * @returns {number}\n */\nencodeFloat.encodedSize = function encodedSize (token, options) {\n const float = token.value\n\n if (float === false || float === true || float === null || float === undefined) {\n return 1\n }\n\n if (!options || options.float64 !== true) {\n encodeFloat16(float)\n let decoded = readFloat16(ui8a, 1)\n if (float === decoded || Number.isNaN(float)) {\n return 3\n }\n encodeFloat32(float)\n decoded = readFloat32(ui8a, 1)\n if (float === decoded) {\n return 5\n }\n }\n return 9\n}\n\nconst buffer = new ArrayBuffer(9)\nconst dataView = new DataView(buffer, 1)\nconst ui8a = new Uint8Array(buffer, 0)\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat16 (inp) {\n if (inp === Infinity) {\n dataView.setUint16(0, 0x7c00, false)\n } else if (inp === -Infinity) {\n dataView.setUint16(0, 0xfc00, false)\n } else if (Number.isNaN(inp)) {\n dataView.setUint16(0, 0x7e00, false)\n } else {\n dataView.setFloat32(0, inp)\n const valu32 = dataView.getUint32(0)\n const exponent = (valu32 & 0x7f800000) >> 23\n const mantissa = valu32 & 0x7fffff\n\n /* c8 ignore next 6 */\n if (exponent === 0xff) {\n // too big, Infinity, but this should be hard (impossible?) to trigger\n dataView.setUint16(0, 0x7c00, false)\n } else if (exponent === 0x00) {\n // 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int\n dataView.setUint16(0, ((inp & 0x80000000) >> 16) | (mantissa >> 13), false)\n } else { // standard numbers\n // chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127\n const logicalExponent = exponent - 127\n // Now we know that 2^exponent <= 0 logically\n /* c8 ignore next 6 */\n if (logicalExponent < -24) {\n /* No unambiguous representation exists, this float is not a half float\n and is too small to be represented using a half, round off to zero.\n Consistent with the reference implementation. */\n // should be difficult (impossible?) to get here in JS\n dataView.setUint16(0, 0)\n } else if (logicalExponent < -14) {\n /* Offset the remaining decimal places by shifting the significand, the\n value is lost. This is an implementation decision that works around the\n absence of standard half-float in the language. */\n dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)\n } else {\n dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)\n }\n }\n }\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat16 (ui8a, pos) {\n if (ui8a.length - pos < 2) {\n throw new Error(`${decodeErrPrefix} not enough data for float16`)\n }\n\n const half = (ui8a[pos] << 8) + ui8a[pos + 1]\n if (half === 0x7c00) {\n return Infinity\n }\n if (half === 0xfc00) {\n return -Infinity\n }\n if (half === 0x7e00) {\n return NaN\n }\n const exp = (half >> 10) & 0x1f\n const mant = half & 0x3ff\n let val\n if (exp === 0) {\n val = mant * (2 ** -24)\n } else if (exp !== 31) {\n val = (mant + 1024) * (2 ** (exp - 25))\n /* c8 ignore next 4 */\n } else {\n // may not be possible to get here\n val = mant === 0 ? Infinity : NaN\n }\n return (half & 0x8000) ? -val : val\n}\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat32 (inp) {\n dataView.setFloat32(0, inp, false)\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat32 (ui8a, pos) {\n if (ui8a.length - pos < 4) {\n throw new Error(`${decodeErrPrefix} not enough data for float32`)\n }\n const offset = (ui8a.byteOffset || 0) + pos\n return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)\n}\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat64 (inp) {\n dataView.setFloat64(0, inp, false)\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat64 (ui8a, pos) {\n if (ui8a.length - pos < 8) {\n throw new Error(`${decodeErrPrefix} not enough data for float64`)\n }\n const offset = (ui8a.byteOffset || 0) + pos\n return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)\n}\n\n/**\n * @param {Token} _tok1\n * @param {Token} _tok2\n * @returns {number}\n */\nencodeFloat.compareTokens = encodeUint.compareTokens\n/*\nencodeFloat.compareTokens = function compareTokens (_tok1, _tok2) {\n return _tok1\n throw new Error(`${encodeErrPrefix} cannot use floats as map keys`)\n}\n*/\n", "import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport * as negint from './1negint.js'\nimport * as bytes from './2bytes.js'\nimport * as string from './3string.js'\nimport * as array from './4array.js'\nimport * as map from './5map.js'\nimport * as tag from './6tag.js'\nimport * as float from './7float.js'\nimport { decodeErrPrefix } from './common.js'\nimport { fromArray } from './byte-utils.js'\n\n/**\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n */\nfunction invalidMinor (data, pos, minor) {\n throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)\n}\n\n/**\n * @param {string} msg\n * @returns {()=>any}\n */\nfunction errorer (msg) {\n return () => { throw new Error(`${decodeErrPrefix} ${msg}`) }\n}\n\n/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */\nexport const jump = []\n\n// unsigned integer, 0x00..0x17 (0..23)\nfor (let i = 0; i <= 0x17; i++) {\n jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]\n}\njump[0x18] = uint.decodeUint8 // unsigned integer, one-byte uint8_t follows\njump[0x19] = uint.decodeUint16 // unsigned integer, two-byte uint16_t follows\njump[0x1a] = uint.decodeUint32 // unsigned integer, four-byte uint32_t follows\njump[0x1b] = uint.decodeUint64 // unsigned integer, eight-byte uint64_t follows\njump[0x1c] = invalidMinor\njump[0x1d] = invalidMinor\njump[0x1e] = invalidMinor\njump[0x1f] = invalidMinor\n// negative integer, -1-0x00..-1-0x17 (-1..-24)\nfor (let i = 0x20; i <= 0x37; i++) {\n jump[i] = invalidMinor // negintDecode, handled by quick[]\n}\njump[0x38] = negint.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows\njump[0x39] = negint.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows\njump[0x3a] = negint.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows\njump[0x3b] = negint.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows\njump[0x3c] = invalidMinor\njump[0x3d] = invalidMinor\njump[0x3e] = invalidMinor\njump[0x3f] = invalidMinor\n// byte string, 0x00..0x17 bytes follow\nfor (let i = 0x40; i <= 0x57; i++) {\n jump[i] = bytes.decodeBytesCompact\n}\njump[0x58] = bytes.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow\njump[0x59] = bytes.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow\njump[0x5a] = bytes.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow\njump[0x5b] = bytes.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow\njump[0x5c] = invalidMinor\njump[0x5d] = invalidMinor\njump[0x5e] = invalidMinor\njump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by \"break\"\n// UTF-8 string 0x00..0x17 bytes follow\nfor (let i = 0x60; i <= 0x77; i++) {\n jump[i] = string.decodeStringCompact\n}\njump[0x78] = string.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow\njump[0x79] = string.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow\njump[0x7a] = string.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow\njump[0x7b] = string.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow\njump[0x7c] = invalidMinor\njump[0x7d] = invalidMinor\njump[0x7e] = invalidMinor\njump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by \"break\"\n// array, 0x00..0x17 data items follow\nfor (let i = 0x80; i <= 0x97; i++) {\n jump[i] = array.decodeArrayCompact\n}\njump[0x98] = array.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow\njump[0x99] = array.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow\njump[0x9a] = array.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow\njump[0x9b] = array.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow\njump[0x9c] = invalidMinor\njump[0x9d] = invalidMinor\njump[0x9e] = invalidMinor\njump[0x9f] = array.decodeArrayIndefinite // array, data items follow, terminated by \"break\"\n// map, 0x00..0x17 pairs of data items follow\nfor (let i = 0xa0; i <= 0xb7; i++) {\n jump[i] = map.decodeMapCompact\n}\njump[0xb8] = map.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow\njump[0xb9] = map.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow\njump[0xba] = map.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow\njump[0xbb] = map.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow\njump[0xbc] = invalidMinor\njump[0xbd] = invalidMinor\njump[0xbe] = invalidMinor\njump[0xbf] = map.decodeMapIndefinite // map, pairs of data items follow, terminated by \"break\"\n// tags\nfor (let i = 0xc0; i <= 0xd7; i++) {\n jump[i] = tag.decodeTagCompact\n}\njump[0xd8] = tag.decodeTag8\njump[0xd9] = tag.decodeTag16\njump[0xda] = tag.decodeTag32\njump[0xdb] = tag.decodeTag64\njump[0xdc] = invalidMinor\njump[0xdd] = invalidMinor\njump[0xde] = invalidMinor\njump[0xdf] = invalidMinor\n// 0xe0..0xf3 simple values, unsupported\nfor (let i = 0xe0; i <= 0xf3; i++) {\n jump[i] = errorer('simple values are not supported')\n}\njump[0xf4] = invalidMinor // false, handled by quick[]\njump[0xf5] = invalidMinor // true, handled by quick[]\njump[0xf6] = invalidMinor // null, handled by quick[]\njump[0xf7] = float.decodeUndefined // undefined\njump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported\njump[0xf9] = float.decodeFloat16 // half-precision float (two-byte IEEE 754)\njump[0xfa] = float.decodeFloat32 // single-precision float (four-byte IEEE 754)\njump[0xfb] = float.decodeFloat64 // double-precision float (eight-byte IEEE 754)\njump[0xfc] = invalidMinor\njump[0xfd] = invalidMinor\njump[0xfe] = invalidMinor\njump[0xff] = float.decodeBreak // \"break\" stop code\n\n/** @type {Token[]} */\nexport const quick = []\n// ints <24\nfor (let i = 0; i < 24; i++) {\n quick[i] = new Token(Type.uint, i, 1)\n}\n// negints >= -24\nfor (let i = -1; i >= -24; i--) {\n quick[31 - i] = new Token(Type.negint, i, 1)\n}\n// empty bytes\nquick[0x40] = new Token(Type.bytes, new Uint8Array(0), 1)\n// empty string\nquick[0x60] = new Token(Type.string, '', 1)\n// empty list\nquick[0x80] = new Token(Type.array, 0, 1)\n// empty map\nquick[0xa0] = new Token(Type.map, 0, 1)\n// false\nquick[0xf4] = new Token(Type.false, false, 1)\n// true\nquick[0xf5] = new Token(Type.true, true, 1)\n// null\nquick[0xf6] = new Token(Type.null, null, 1)\n\n/**\n * @param {Token} token\n * @returns {Uint8Array|undefined}\n */\nexport function quickEncodeToken (token) {\n switch (token.type) {\n case Type.false:\n return fromArray([0xf4])\n case Type.true:\n return fromArray([0xf5])\n case Type.null:\n return fromArray([0xf6])\n case Type.bytes:\n if (!token.value.length) {\n return fromArray([0x40])\n }\n return\n case Type.string:\n if (token.value === '') {\n return fromArray([0x60])\n }\n return\n case Type.array:\n if (token.value === 0) {\n return fromArray([0x80])\n }\n /* c8 ignore next 2 */\n // shouldn't be possible if this were called when there was only one token\n return\n case Type.map:\n if (token.value === 0) {\n return fromArray([0xa0])\n }\n /* c8 ignore next 2 */\n // shouldn't be possible if this were called when there was only one token\n return\n case Type.uint:\n if (token.value < 24) {\n return fromArray([Number(token.value)])\n }\n return\n case Type.negint:\n if (token.value >= -24) {\n return fromArray([31 - Number(token.value)])\n }\n }\n}\n", "import { is } from './is.js'\nimport { Token, Type } from './token.js'\nimport { Bl } from './bl.js'\nimport { encodeErrPrefix } from './common.js'\nimport { quickEncodeToken } from './jump.js'\nimport { asU8A } from './byte-utils.js'\n\nimport { encodeUint } from './0uint.js'\nimport { encodeNegint } from './1negint.js'\nimport { encodeBytes } from './2bytes.js'\nimport { encodeString } from './3string.js'\nimport { encodeArray } from './4array.js'\nimport { encodeMap } from './5map.js'\nimport { encodeTag } from './6tag.js'\nimport { encodeFloat } from './7float.js'\n\n/**\n * @typedef {import('../interface').EncodeOptions} EncodeOptions\n * @typedef {import('../interface').OptionalTypeEncoder} OptionalTypeEncoder\n * @typedef {import('../interface').Reference} Reference\n * @typedef {import('../interface').StrictTypeEncoder} StrictTypeEncoder\n * @typedef {import('../interface').TokenTypeEncoder} TokenTypeEncoder\n * @typedef {import('../interface').TokenOrNestedTokens} TokenOrNestedTokens\n */\n\n/** @type {EncodeOptions} */\nconst defaultEncodeOptions = {\n float64: false,\n mapSorter,\n quickEncodeToken\n}\n\n/** @returns {TokenTypeEncoder[]} */\nexport function makeCborEncoders () {\n const encoders = []\n encoders[Type.uint.major] = encodeUint\n encoders[Type.negint.major] = encodeNegint\n encoders[Type.bytes.major] = encodeBytes\n encoders[Type.string.major] = encodeString\n encoders[Type.array.major] = encodeArray\n encoders[Type.map.major] = encodeMap\n encoders[Type.tag.major] = encodeTag\n encoders[Type.float.major] = encodeFloat\n return encoders\n}\n\nconst cborEncoders = makeCborEncoders()\n\nconst buf = new Bl()\n\n/** @implements {Reference} */\nclass Ref {\n /**\n * @param {object|any[]} obj\n * @param {Reference|undefined} parent\n */\n constructor (obj, parent) {\n this.obj = obj\n this.parent = parent\n }\n\n /**\n * @param {object|any[]} obj\n * @returns {boolean}\n */\n includes (obj) {\n /** @type {Reference|undefined} */\n let p = this\n do {\n if (p.obj === obj) {\n return true\n }\n } while (p = p.parent) // eslint-disable-line\n return false\n }\n\n /**\n * @param {Reference|undefined} stack\n * @param {object|any[]} obj\n * @returns {Reference}\n */\n static createCheck (stack, obj) {\n if (stack && stack.includes(obj)) {\n throw new Error(`${encodeErrPrefix} object contains circular references`)\n }\n return new Ref(obj, stack)\n }\n}\n\nconst simpleTokens = {\n null: new Token(Type.null, null),\n undefined: new Token(Type.undefined, undefined),\n true: new Token(Type.true, true),\n false: new Token(Type.false, false),\n emptyArray: new Token(Type.array, 0),\n emptyMap: new Token(Type.map, 0)\n}\n\n/** @type {{[typeName: string]: StrictTypeEncoder}} */\nconst typeEncoders = {\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n number (obj, _typ, _options, _refStack) {\n if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {\n return new Token(Type.float, obj)\n } else if (obj >= 0) {\n return new Token(Type.uint, obj)\n } else {\n return new Token(Type.negint, obj)\n }\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n bigint (obj, _typ, _options, _refStack) {\n if (obj >= BigInt(0)) {\n return new Token(Type.uint, obj)\n } else {\n return new Token(Type.negint, obj)\n }\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n Uint8Array (obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, obj)\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n string (obj, _typ, _options, _refStack) {\n return new Token(Type.string, obj)\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n boolean (obj, _typ, _options, _refStack) {\n return obj ? simpleTokens.true : simpleTokens.false\n },\n\n /**\n * @param {any} _obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n null (_obj, _typ, _options, _refStack) {\n return simpleTokens.null\n },\n\n /**\n * @param {any} _obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n undefined (_obj, _typ, _options, _refStack) {\n return simpleTokens.undefined\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n ArrayBuffer (obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, new Uint8Array(obj))\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n DataView (obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} options\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\n Array (obj, _typ, options, refStack) {\n if (!obj.length) {\n if (options.addBreakTokens === true) {\n return [simpleTokens.emptyArray, new Token(Type.break)]\n }\n return simpleTokens.emptyArray\n }\n refStack = Ref.createCheck(refStack, obj)\n const entries = []\n let i = 0\n for (const e of obj) {\n entries[i++] = objectToTokens(e, options, refStack)\n }\n if (options.addBreakTokens) {\n return [new Token(Type.array, obj.length), entries, new Token(Type.break)]\n }\n return [new Token(Type.array, obj.length), entries]\n },\n\n /**\n * @param {any} obj\n * @param {string} typ\n * @param {EncodeOptions} options\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\n Object (obj, typ, options, refStack) {\n // could be an Object or a Map\n const isMap = typ !== 'Object'\n // it's slightly quicker to use Object.keys() than Object.entries()\n const keys = isMap ? obj.keys() : Object.keys(obj)\n const length = isMap ? obj.size : keys.length\n if (!length) {\n if (options.addBreakTokens === true) {\n return [simpleTokens.emptyMap, new Token(Type.break)]\n }\n return simpleTokens.emptyMap\n }\n refStack = Ref.createCheck(refStack, obj)\n /** @type {TokenOrNestedTokens[]} */\n const entries = []\n let i = 0\n for (const key of keys) {\n entries[i++] = [\n objectToTokens(key, options, refStack),\n objectToTokens(isMap ? obj.get(key) : obj[key], options, refStack)\n ]\n }\n sortMapEntries(entries, options)\n if (options.addBreakTokens) {\n return [new Token(Type.map, length), entries, new Token(Type.break)]\n }\n return [new Token(Type.map, length), entries]\n }\n}\n\ntypeEncoders.Map = typeEncoders.Object\ntypeEncoders.Buffer = typeEncoders.Uint8Array\nfor (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {\n typeEncoders[`${typ}Array`] = typeEncoders.DataView\n}\n\n/**\n * @param {any} obj\n * @param {EncodeOptions} [options]\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\nfunction objectToTokens (obj, options = {}, refStack) {\n const typ = is(obj)\n const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]\n if (typeof customTypeEncoder === 'function') {\n const tokens = customTypeEncoder(obj, typ, options, refStack)\n if (tokens != null) {\n return tokens\n }\n }\n const typeEncoder = typeEncoders[typ]\n if (!typeEncoder) {\n throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)\n }\n return typeEncoder(obj, typ, options, refStack)\n}\n\n/*\nCBOR key sorting is a mess.\n\nThe canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9\nincludes the wording:\n\n> The keys in every map must be sorted lowest value to highest.\n> Sorting is performed on the bytes of the representation of the key\n> data items without paying attention to the 3/5 bit splitting for\n> major types.\n> ...\n> * If two keys have different lengths, the shorter one sorts\n earlier;\n> * If two keys have the same length, the one with the lower value\n in (byte-wise) lexical order sorts earlier.\n\n1. It is not clear what \"bytes of the representation of the key\" means: is it\n the CBOR representation, or the binary representation of the object itself?\n Consider the int and uint difference here.\n2. It is not clear what \"without paying attention to\" means: do we include it\n and compare on that? Or do we omit the special prefix byte, (mostly) treating\n the key in its plain binary representation form.\n\nThe FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR\nwording and clarifies it according to their understanding.\nhttps://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding\n\n> The keys in every map must be sorted lowest value to highest. Sorting is\n> performed on the bytes of the representation of the key data items without\n> paying attention to the 3/5 bit splitting for major types. The sorting rules\n> are:\n> * If the major types are different, the one with the lower value in numerical\n> order sorts earlier.\n> * If two keys have different lengths, the shorter one sorts earlier;\n> * If two keys have the same length, the one with the lower value in\n> (byte-wise) lexical order sorts earlier.\n\nSome other implementations, such as borc, do a full encode then do a\nlength-first, byte-wise-second comparison:\nhttps://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358\nhttps://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151\n\nThis has the benefit of being able to easily handle arbitrary keys, including\ncomplex types (maps and arrays).\n\nWe'll opt for the FIDO approach, since it affords some efficies since we don't\nneed a full encode of each key to determine order and can defer to the types\nto determine how to most efficiently order their values (i.e. int and uint\nordering can be done on the numbers, no need for byte-wise, for example).\n\nRecommendation: stick to single key types or you'll get into trouble, and prefer\nstring keys because it's much simpler that way.\n*/\n\n/*\n(UPDATE, Dec 2020)\nhttps://tools.ietf.org/html/rfc8949 is the updated CBOR spec and clarifies some\nof the questions above with a new recommendation for sorting order being much\ncloser to what would be expected in other environments (i.e. no length-first\nweirdness).\nThis new sorting order is not yet implemented here but could be added as an\noption. \"Determinism\" (canonicity) is system dependent and it's difficult to\nchange existing systems that are built with existing expectations. So if a new\nordering is introduced here, the old needs to be kept as well with the user\nhaving the option.\n*/\n\n/**\n * @param {TokenOrNestedTokens[]} entries\n * @param {EncodeOptions} options\n */\nfunction sortMapEntries (entries, options) {\n if (options.mapSorter) {\n entries.sort(options.mapSorter)\n }\n}\n\n/**\n * @param {(Token|Token[])[]} e1\n * @param {(Token|Token[])[]} e2\n * @returns {number}\n */\nfunction mapSorter (e1, e2) {\n // the key position ([0]) could have a single token or an array\n // almost always it'll be a single token but complex key might get involved\n /* c8 ignore next 2 */\n const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]\n const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]\n\n // different key types\n if (keyToken1.type !== keyToken2.type) {\n return keyToken1.type.compare(keyToken2.type)\n }\n\n const major = keyToken1.type.major\n // TODO: handle case where cmp === 0 but there are more keyToken e. complex type)\n const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2)\n /* c8 ignore next 5 */\n if (tcmp === 0) {\n // duplicate key or complex type where the first token matched,\n // i.e. a map or array and we're only comparing the opening token\n console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')\n }\n return tcmp\n}\n\n/**\n * @param {Bl} buf\n * @param {TokenOrNestedTokens} tokens\n * @param {TokenTypeEncoder[]} encoders\n * @param {EncodeOptions} options\n */\nfunction tokensToEncoded (buf, tokens, encoders, options) {\n if (Array.isArray(tokens)) {\n for (const token of tokens) {\n tokensToEncoded(buf, token, encoders, options)\n }\n } else {\n encoders[tokens.type.major](buf, tokens, options)\n }\n}\n\n/**\n * @param {any} data\n * @param {TokenTypeEncoder[]} encoders\n * @param {EncodeOptions} options\n * @returns {Uint8Array}\n */\nfunction encodeCustom (data, encoders, options) {\n const tokens = objectToTokens(data, options)\n if (!Array.isArray(tokens) && options.quickEncodeToken) {\n const quickBytes = options.quickEncodeToken(tokens)\n if (quickBytes) {\n return quickBytes\n }\n const encoder = encoders[tokens.type.major]\n if (encoder.encodedSize) {\n const size = encoder.encodedSize(tokens, options)\n const buf = new Bl(size)\n encoder(buf, tokens, options)\n /* c8 ignore next 4 */\n // this would be a problem with encodedSize() functions\n if (buf.chunks.length !== 1) {\n throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)\n }\n return asU8A(buf.chunks[0])\n }\n }\n buf.reset()\n tokensToEncoded(buf, tokens, encoders, options)\n return buf.toBytes(true)\n}\n\n/**\n * @param {any} data\n * @param {EncodeOptions} [options]\n * @returns {Uint8Array}\n */\nfunction encode (data, options) {\n options = Object.assign({}, defaultEncodeOptions, options)\n return encodeCustom(data, cborEncoders, options)\n}\n\nexport { objectToTokens, encode, encodeCustom, Ref }\n", "import { decodeErrPrefix } from './common.js'\nimport { Type } from './token.js'\nimport { jump, quick } from './jump.js'\n\n/**\n * @typedef {import('./token.js').Token} Token\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n * @typedef {import('../interface').DecodeTokenizer} DecodeTokenizer\n */\n\nconst defaultDecodeOptions = {\n strict: false,\n allowIndefinite: true,\n allowUndefined: true,\n allowBigInt: true\n}\n\n/**\n * @implements {DecodeTokenizer}\n */\nclass Tokeniser {\n /**\n * @param {Uint8Array} data\n * @param {DecodeOptions} options\n */\n constructor (data, options = {}) {\n this._pos = 0\n this.data = data\n this.options = options\n }\n\n pos () {\n return this._pos\n }\n\n done () {\n return this._pos >= this.data.length\n }\n\n next () {\n const byt = this.data[this._pos]\n let token = quick[byt]\n if (token === undefined) {\n const decoder = jump[byt]\n /* c8 ignore next 4 */\n // if we're here then there's something wrong with our jump or quick lists!\n if (!decoder) {\n throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)\n }\n const minor = byt & 31\n token = decoder(this.data, this._pos, minor, this.options)\n }\n // @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)\n this._pos += token.encodedLength\n return token\n }\n}\n\nconst DONE = Symbol.for('DONE')\nconst BREAK = Symbol.for('BREAK')\n\n/**\n * @param {Token} token\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|BREAK|DONE}\n */\nfunction tokenToArray (token, tokeniser, options) {\n const arr = []\n for (let i = 0; i < token.value; i++) {\n const value = tokensToObject(tokeniser, options)\n if (value === BREAK) {\n if (token.value === Infinity) {\n // normal end to indefinite length array\n break\n }\n throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`)\n }\n if (value === DONE) {\n throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)\n }\n arr[i] = value\n }\n return arr\n}\n\n/**\n * @param {Token} token\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|BREAK|DONE}\n */\nfunction tokenToMap (token, tokeniser, options) {\n const useMaps = options.useMaps === true\n const obj = useMaps ? undefined : {}\n const m = useMaps ? new Map() : undefined\n for (let i = 0; i < token.value; i++) {\n const key = tokensToObject(tokeniser, options)\n if (key === BREAK) {\n if (token.value === Infinity) {\n // normal end to indefinite length map\n break\n }\n throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)\n }\n if (key === DONE) {\n throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)\n }\n if (useMaps !== true && typeof key !== 'string') {\n throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)\n }\n if (options.rejectDuplicateMapKeys === true) {\n // @ts-ignore\n if ((useMaps && m.has(key)) || (!useMaps && (key in obj))) {\n throw new Error(`${decodeErrPrefix} found repeat map key \"${key}\"`)\n }\n }\n const value = tokensToObject(tokeniser, options)\n if (value === DONE) {\n throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)\n }\n if (useMaps) {\n // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types\n m.set(key, value)\n } else {\n // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types\n obj[key] = value\n }\n }\n // @ts-ignore c'mon man\n return useMaps ? m : obj\n}\n\n/**\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|BREAK|DONE}\n */\nfunction tokensToObject (tokeniser, options) {\n // should we support array as an argument?\n // check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?\n if (tokeniser.done()) {\n return DONE\n }\n\n const token = tokeniser.next()\n\n if (token.type === Type.break) {\n return BREAK\n }\n\n if (token.type.terminal) {\n return token.value\n }\n\n if (token.type === Type.array) {\n return tokenToArray(token, tokeniser, options)\n }\n\n if (token.type === Type.map) {\n return tokenToMap(token, tokeniser, options)\n }\n\n if (token.type === Type.tag) {\n if (options.tags && typeof options.tags[token.value] === 'function') {\n const tagged = tokensToObject(tokeniser, options)\n return options.tags[token.value](tagged)\n }\n throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`)\n }\n /* c8 ignore next */\n throw new Error('unsupported')\n}\n\n/**\n * @param {Uint8Array} data\n * @param {DecodeOptions} [options]\n * @returns {[any, Uint8Array]}\n */\nfunction decodeFirst (data, options) {\n if (!(data instanceof Uint8Array)) {\n throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`)\n }\n options = Object.assign({}, defaultDecodeOptions, options)\n const tokeniser = options.tokenizer || new Tokeniser(data, options)\n const decoded = tokensToObject(tokeniser, options)\n if (decoded === DONE) {\n throw new Error(`${decodeErrPrefix} did not find any content to decode`)\n }\n if (decoded === BREAK) {\n throw new Error(`${decodeErrPrefix} got unexpected break`)\n }\n return [decoded, data.subarray(tokeniser.pos())]\n}\n\n/**\n * @param {Uint8Array} data\n * @param {DecodeOptions} [options]\n * @returns {any}\n */\nfunction decode (data, options) {\n const [decoded, remainder] = decodeFirst(data, options)\n if (remainder.length > 0) {\n throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`)\n }\n return decoded\n}\n\nexport { Tokeniser, tokensToObject, decode, decodeFirst }\n", "import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n", "export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) { return true }\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') { return o }\n if (o instanceof ArrayBuffer) { 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}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n", "/* 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) { throw new TypeError('Alphabet too long') }\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) { throw new TypeError(x + ' is ambiguous') }\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<number>} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\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) { throw new Error('Non-zero carry') }\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) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\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) { return }\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) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\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) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n", "import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\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<Base extends string, Prefix extends string> implements MultibaseEncoder<Prefix>, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase<Prefix> {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\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<Base extends string, Prefix extends string> implements MultibaseDecoder<Prefix>, UnibaseDecoder<Prefix>, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n const prefixCodePoint = prefix.codePointAt(0)\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefixCodePoint\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\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 } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or<OtherPrefix extends string> (decoder: UnibaseDecoder<OtherPrefix> | ComposedDecoder<OtherPrefix>): ComposedDecoder<Prefix | OtherPrefix> {\n return or(this, decoder)\n }\n}\n\ntype Decoders<Prefix extends string> = Record<Prefix, UnibaseDecoder<Prefix>>\n\nclass ComposedDecoder<Prefix extends string> implements MultibaseDecoder<Prefix>, CombobaseDecoder<Prefix> {\n readonly decoders: Decoders<Prefix>\n\n constructor (decoders: Decoders<Prefix>) {\n this.decoders = decoders\n }\n\n or <OtherPrefix extends string> (decoder: UnibaseDecoder<OtherPrefix> | ComposedDecoder<OtherPrefix>): ComposedDecoder<Prefix | OtherPrefix> {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\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}\n\nexport function or <L extends string, R extends string> (left: UnibaseDecoder<L> | CombobaseDecoder<L>, right: UnibaseDecoder<R> | CombobaseDecoder<R>): ComposedDecoder<L | R> {\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder<L>).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder<R>).prefix]: right })\n } as Decoders<L | R>)\n}\n\nexport class Codec<Base extends string, Prefix extends string> implements MultibaseCodec<Prefix>, MultibaseEncoder<Prefix>, MultibaseDecoder<Prefix>, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder<Base, Prefix>\n readonly decoder: Decoder<Base, Prefix>\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\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\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from <Base extends string, Prefix extends string> ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec<Base, Prefix> {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX <Base extends string, Prefix extends string> ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec<Base, Prefix> {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabetIdx: Record<string, number>, bitsPerChar: number, name: string): Uint8Array {\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\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 = alphabetIdx[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\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\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\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\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\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\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\n return out\n}\n\nfunction createAlphabetIdx (alphabet: string): Record<string, number> {\n // Build the character lookup table:\n const alphabetIdx: Record<string, number> = {}\n for (let i = 0; i < alphabet.length; ++i) {\n alphabetIdx[alphabet[i]] = i\n }\n return alphabetIdx\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 <Base extends string, Prefix extends string> ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec<Base, Prefix> {\n const alphabetIdx = createAlphabetIdx(alphabet)\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabetIdx, bitsPerChar, name)\n }\n })\n}\n", "import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n", "import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n", "/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\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\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 \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\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\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\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);\n\nvar length = function (/** @type {number} */ value) {\n return (\n 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 )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n", "import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n", "import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create <Code extends number> (code: Code, digest: Uint8Array): Digest<Code, number> {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\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\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\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\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\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<Code extends number, Size extends number> implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n\n/**\n * Used to check that the passed multihash has the passed code\n */\nexport function hasCode <T extends number> (digest: MultihashDigest, code: T): digest is MultihashDigest<T> {\n return digest.code === code\n}\n", "import { base32 } from './bases/base32.js'\nimport { base36 } from './bases/base36.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'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format <T extends API.Link<unknown, number, number, API.Version>, Prefix extends string> (link: T, base?: API.MultibaseEncoder<Prefix>): API.ToString<T, Prefix> {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder<Prefix>\n )\n }\n}\n\nexport function toJSON <Link extends API.UnknownLink> (link: Link): API.LinkJSON<Link> {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON <Link extends API.UnknownLink> (json: API.LinkJSON<Link>): CID<unknown, number, number, API.Version> {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap<API.UnknownLink, Map<string, string>>()\n\nfunction baseCache (cid: API.UnknownLink): Map<string, string> {\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}\n\nexport class CID<Data = unknown, Format extends number = number, Alg extends number = number, Version extends API.Version = API.Version> implements API.Link<Data, Format, Alg, Version> {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest<Alg>\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\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: Version, code: Format, multihash: API.MultihashDigest<Alg>, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\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 (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID<Data, API.DAG_PB, API.SHA_256, 0> {\n switch (this.version) {\n case 0: {\n return this as CID<Data, API.DAG_PB, API.SHA_256, 0>\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\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\n return (\n CID.createV0(\n multihash as API.MultihashDigest<API.SHA_256>\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID<Data, Format, Alg, 1> {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID<Data, Format, Alg, 1>\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID<Data, Format, Alg, Version> {\n return CID.equals(this, other)\n }\n\n static equals <Data, Format extends number, Alg extends number, Version extends API.Version>(self: API.Link<Data, Format, Alg, Version>, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder<string>): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON<this> {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\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 <Data, Format extends number, Alg extends number, Version extends API.Version, U>(input: API.Link<Data, Format, Alg, Version> | U): CID<Data, Format, Alg, Version> | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\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(\n version,\n code,\n multihash as API.MultihashDigest<Alg>,\n 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) as API.MultihashDigest<Alg>\n return CID.create(version, code, digest)\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 /**\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 <Data, Format extends number, Alg extends number, Version extends API.Version>(version: Version, code: Format, digest: API.MultihashDigest<Alg>): CID<Data, Format, Alg, Version> {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `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 /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 <T = unknown>(digest: API.MultihashDigest<typeof SHA_256_CODE>): CID<T, typeof DAG_PB_CODE, typeof SHA_256_CODE, 0> {\n return CID.create(0, DAG_PB_CODE, digest)\n }\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 <Data, Code extends number, Alg extends number>(code: Code, digest: API.MultihashDigest<Alg>): CID<Data, Code, Alg, 1> {\n return CID.create(1, code, digest)\n }\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 <Data, Code extends number, Alg extends number, Version extends API.Version>(bytes: API.ByteView<API.Link<Data, Code, Alg, Version>>): CID<Data, Code, Alg, Version> {\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 /**\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 <T, C extends number, A extends number, V extends API.Version>(bytes: API.ByteView<API.Link<T, C, A, V>>): [CID<T, C, A, V>, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest<API.SHA_256>)\n : CID.createV1(specs.codec, digest)\n return [cid as CID<T, C, A, V>, bytes.subarray(specs.size)]\n }\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 <T, C extends number, A extends number, V extends API.Version>(initialBytes: API.ByteView<API.Link<T, C, A, V>>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\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 <Prefix extends string, Data, Code extends number, Alg extends number, Version extends API.Version>(source: API.ToString<API.Link<Data, Code, Alg, Version>, Prefix>, base?: API.MultibaseDecoder<Prefix>): CID<Data, Code, Alg, Version> {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes <Prefix extends string, Data, Code extends number, Alg extends number, Version extends API.Version> (source: API.ToString<API.Link<Data, Code, Alg, Version>, Prefix>, base?: API.MultibaseDecoder<Prefix>): [Prefix, API.ByteView<API.Link<Data, Code, Alg, Version>>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n case base36.prefix: {\n const decoder = base ?? base36\n return [base36.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map<string, string>, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\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 } else {\n return cid\n }\n}\n\nfunction toStringV1 <Prefix extends string> (bytes: Uint8Array, cache: Map<string, string>, base: API.MultibaseEncoder<Prefix>): string {\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 } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\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}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n", "import * as cborg from 'cborg'\nimport { CID } from 'multiformats/cid'\n\n// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692\nconst CID_CBOR_TAG = 42\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ByteView<T>} ByteView\n */\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ArrayBufferView<T>} ArrayBufferView\n */\n\n/**\n * @template T\n * @param {ByteView<T> | ArrayBufferView<T>} buf\n * @returns {ByteView<T>}\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\n/**\n * cidEncoder will receive all Objects during encode, it needs to filter out\n * anything that's not a CID and return `null` for that so it's encoded as\n * normal.\n *\n * @param {any} obj\n * @returns {cborg.Token[]|null}\n */\nfunction cidEncoder (obj) {\n if (obj.asCID !== obj && obj['/'] !== obj.bytes) {\n return null // any other kind of object\n }\n const cid = CID.asCID(obj)\n /* c8 ignore next 4 */\n // very unlikely case, and it'll probably throw a recursion error in cborg\n if (!cid) {\n return null\n }\n const bytes = new Uint8Array(cid.bytes.byteLength + 1)\n bytes.set(cid.bytes, 1) // prefix is 0x00, for historical reasons\n return [\n new cborg.Token(cborg.Type.tag, CID_CBOR_TAG),\n new cborg.Token(cborg.Type.bytes, bytes)\n ]\n}\n\n// eslint-disable-next-line jsdoc/require-returns-check\n/**\n * Intercept all `undefined` values from an object walk and reject the entire\n * object if we find one.\n *\n * @returns {null}\n */\nfunction undefinedEncoder () {\n throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')\n}\n\n/**\n * Intercept all `number` values from an object walk and reject the entire\n * object if we find something that doesn't fit the IPLD data model (NaN &\n * Infinity).\n *\n * @param {number} num\n * @returns {null}\n */\nfunction numberEncoder (num) {\n if (Number.isNaN(num)) {\n throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')\n }\n if (num === Infinity || num === -Infinity) {\n throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')\n }\n return null\n}\n\nconst _encodeOptions = {\n float64: true,\n typeEncoders: {\n Object: cidEncoder,\n undefined: undefinedEncoder,\n number: numberEncoder\n }\n}\n\nexport const encodeOptions = {\n ..._encodeOptions,\n typeEncoders: {\n ..._encodeOptions.typeEncoders\n }\n}\n\n/**\n * @param {Uint8Array} bytes\n * @returns {CID}\n */\nfunction cidDecoder (bytes) {\n if (bytes[0] !== 0) {\n throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00')\n }\n return CID.decode(bytes.subarray(1)) // ignore leading 0x00\n}\n\nconst _decodeOptions = {\n allowIndefinite: false,\n coerceUndefinedToNull: true,\n allowNaN: false,\n allowInfinity: false,\n allowBigInt: true, // this will lead to BigInt for ints outside of\n // safe-integer range, which may surprise users\n strict: true,\n useMaps: false,\n rejectDuplicateMapKeys: true,\n /** @type {import('cborg').TagDecoder[]} */\n tags: []\n}\n_decodeOptions.tags[CID_CBOR_TAG] = cidDecoder\n\nexport const decodeOptions = {\n ..._decodeOptions,\n tags: _decodeOptions.tags.slice()\n}\n\nexport const name = 'dag-cbor'\nexport const code = 0x71\n\n/**\n * @template T\n * @param {T} node\n * @returns {ByteView<T>}\n */\nexport const encode = (node) => cborg.encode(node, _encodeOptions)\n\n/**\n * @template T\n * @param {ByteView<T> | ArrayBufferView<T>} data\n * @returns {T}\n */\nexport const decode = (data) => cborg.decode(toByteView(data), _decodeOptions)\n", "import varint from 'varint'\n\nexport const CIDV0_BYTES = {\n SHA2_256: 0x12,\n LENGTH: 0x20,\n DAG_PB: 0x70\n}\n\nexport const V2_HEADER_LENGTH = /* characteristics */ 16 /* v1 offset */ + 8 /* v1 size */ + 8 /* index offset */ + 8\n\n/**\n * Decodes varint and seeks the buffer\n *\n * ```js\n * // needs bytes to be read first\n * const bytes = reader.upTo(8) // maybe async\n * ```\n *\n * @param {Uint8Array} bytes\n * @param {import('./coding.js').Seekable} seeker\n * @returns {number}\n */\nexport function decodeVarint (bytes, seeker) {\n if (!bytes.length) {\n throw new Error('Unexpected end of data')\n }\n const i = varint.decode(bytes)\n seeker.seek(/** @type {number} */(varint.decode.bytes))\n return i\n}\n\n/**\n * Decode v2 header\n *\n * ```js\n * // needs bytes to be read first\n * const bytes = reader.exactly(V2_HEADER_LENGTH, true) // maybe async\n * ```\n *\n * @param {Uint8Array} bytes\n * @returns {import('./coding.js').CarV2FixedHeader}\n */\nexport function decodeV2Header (bytes) {\n const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n let offset = 0\n const header = {\n version: 2,\n /** @type {[bigint, bigint]} */\n characteristics: [\n dv.getBigUint64(offset, true),\n dv.getBigUint64(offset += 8, true)\n ],\n dataOffset: Number(dv.getBigUint64(offset += 8, true)),\n dataSize: Number(dv.getBigUint64(offset += 8, true)),\n indexOffset: Number(dv.getBigUint64(offset += 8, true))\n }\n return header\n}\n\n/**\n * Checks the length of the multihash to be read afterwards\n *\n * ```js\n * // needs bytes to be read first\n * const bytes = reader.upTo(8) // maybe async\n * ```\n *\n * @param {Uint8Array} bytes\n */\nexport function getMultihashLength (bytes) {\n // | code | length | .... |\n // where both code and length are varints, so we have to decode\n // them first before we can know total length\n\n varint.decode(bytes) // code\n const codeLength = /** @type {number} */(varint.decode.bytes)\n const length = varint.decode(bytes.subarray(varint.decode.bytes))\n const lengthLength = /** @type {number} */(varint.decode.bytes)\n const mhLength = codeLength + lengthLength + length\n\n return mhLength\n}\n", "/* eslint-disable jsdoc/check-indentation, max-depth */\n\n/**\n * Auto-generated with @ipld/schema@v4.2.0 at Thu Sep 14 2023 from IPLD Schema:\n *\n * # CarV1HeaderOrV2Pragma is a more relaxed form, and can parse {version:x} where\n * # roots are optional. This is typically useful for the {verison:2} CARv2\n * # pragma.\n *\n * type CarV1HeaderOrV2Pragma struct {\n * roots optional [&Any]\n * # roots is _not_ optional for CarV1 but we defer that check within code to\n * # gracefully handle the V2 case where it's just {version:X}\n * version Int\n * }\n *\n * # CarV1Header is the strict form of the header, and requires roots to be\n * # present. This is compatible with the CARv1 specification.\n *\n * # type CarV1Header struct {\n * # roots [&Any]\n * # version Int\n * # }\n *\n */\n\nconst Kinds = {\n Null: /**\n * @param obj\n * @returns {undefined|null}\n */ (/** @type {any} */ obj) => obj === null ? obj : undefined,\n Int: /**\n * @param obj\n * @returns {undefined|number}\n */ (/** @type {any} */ obj) => Number.isInteger(obj) ? obj : undefined,\n Float: /**\n * @param obj\n * @returns {undefined|number}\n */ (/** @type {any} */ obj) => typeof obj === 'number' && Number.isFinite(obj) ? obj : undefined,\n String: /**\n * @param obj\n * @returns {undefined|string}\n */ (/** @type {any} */ obj) => typeof obj === 'string' ? obj : undefined,\n Bool: /**\n * @param obj\n * @returns {undefined|boolean}\n */ (/** @type {any} */ obj) => typeof obj === 'boolean' ? obj : undefined,\n Bytes: /**\n * @param obj\n * @returns {undefined|Uint8Array}\n */ (/** @type {any} */ obj) => obj instanceof Uint8Array ? obj : undefined,\n Link: /**\n * @param obj\n * @returns {undefined|object}\n */ (/** @type {any} */ obj) => obj !== null && typeof obj === 'object' && obj.asCID === obj ? obj : undefined,\n List: /**\n * @param obj\n * @returns {undefined|Array<any>}\n */ (/** @type {any} */ obj) => Array.isArray(obj) ? obj : undefined,\n Map: /**\n * @param obj\n * @returns {undefined|object}\n */ (/** @type {any} */ obj) => obj !== null && typeof obj === 'object' && obj.asCID !== obj && !Array.isArray(obj) && !(obj instanceof Uint8Array) ? obj : undefined\n}\n/** @type {{ [k in string]: (obj:any)=>undefined|any}} */\nconst Types = {\n 'CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)': Kinds.Link,\n 'CarV1HeaderOrV2Pragma > roots (anon)': /**\n * @param obj\n * @returns {undefined|any}\n */ (/** @type {any} */ obj) => {\n if (Kinds.List(obj) === undefined) {\n return undefined\n }\n for (let i = 0; i < obj.length; i++) {\n let v = obj[i]\n v = Types['CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)'](v)\n if (v === undefined) {\n return undefined\n }\n if (v !== obj[i]) {\n const ret = obj.slice(0, i)\n for (let j = i; j < obj.length; j++) {\n let v = obj[j]\n v = Types['CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)'](v)\n if (v === undefined) {\n return undefined\n }\n ret.push(v)\n }\n return ret\n }\n }\n return obj\n },\n Int: Kinds.Int,\n CarV1HeaderOrV2Pragma: /**\n * @param obj\n * @returns {undefined|any}\n */ (/** @type {any} */ obj) => {\n if (Kinds.Map(obj) === undefined) {\n return undefined\n }\n const entries = Object.entries(obj)\n /** @type {{[k in string]: any}} */\n let ret = obj\n let requiredCount = 1\n for (let i = 0; i < entries.length; i++) {\n const [key, value] = entries[i]\n switch (key) {\n case 'roots':\n {\n const v = Types['CarV1HeaderOrV2Pragma > roots (anon)'](obj[key])\n if (v === undefined) {\n return undefined\n }\n if (v !== value || ret !== obj) {\n if (ret === obj) {\n /** @type {{[k in string]: any}} */\n ret = {}\n for (let j = 0; j < i; j++) {\n ret[entries[j][0]] = entries[j][1]\n }\n }\n ret.roots = v\n }\n }\n break\n case 'version':\n {\n requiredCount--\n const v = Types.Int(obj[key])\n if (v === undefined) {\n return undefined\n }\n if (v !== value || ret !== obj) {\n if (ret === obj) {\n /** @type {{[k in string]: any}} */\n ret = {}\n for (let j = 0; j < i; j++) {\n ret[entries[j][0]] = entries[j][1]\n }\n }\n ret.version = v\n }\n }\n break\n default:\n return undefined\n }\n }\n\n if (requiredCount > 0) {\n return undefined\n }\n return ret\n }\n}\n/** @type {{ [k in string]: (obj:any)=>undefined|any}} */\nconst Reprs = {\n 'CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)': Kinds.Link,\n 'CarV1HeaderOrV2Pragma > roots (anon)': /**\n * @param obj\n * @returns {undefined|any}\n */ (/** @type {any} */ obj) => {\n if (Kinds.List(obj) === undefined) {\n return undefined\n }\n for (let i = 0; i < obj.length; i++) {\n let v = obj[i]\n v = Reprs['CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)'](v)\n if (v === undefined) {\n return undefined\n }\n if (v !== obj[i]) {\n const ret = obj.slice(0, i)\n for (let j = i; j < obj.length; j++) {\n let v = obj[j]\n v = Reprs['CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)'](v)\n if (v === undefined) {\n return undefined\n }\n ret.push(v)\n }\n return ret\n }\n }\n return obj\n },\n Int: Kinds.Int,\n CarV1HeaderOrV2Pragma: /**\n * @param obj\n * @returns {undefined|any}\n */ (/** @type {any} */ obj) => {\n if (Kinds.Map(obj) === undefined) {\n return undefined\n }\n const entries = Object.entries(obj)\n /** @type {{[k in string]: any}} */\n let ret = obj\n let requiredCount = 1\n for (let i = 0; i < entries.length; i++) {\n const [key, value] = entries[i]\n switch (key) {\n case 'roots':\n {\n const v = Reprs['CarV1HeaderOrV2Pragma > roots (anon)'](value)\n if (v === undefined) {\n return undefined\n }\n if (v !== value || ret !== obj) {\n if (ret === obj) {\n /** @type {{[k in string]: any}} */\n ret = {}\n for (let j = 0; j < i; j++) {\n ret[entries[j][0]] = entries[j][1]\n }\n }\n ret.roots = v\n }\n }\n break\n case 'version':\n {\n requiredCount--\n const v = Reprs.Int(value)\n if (v === undefined) {\n return undefined\n }\n if (v !== value || ret !== obj) {\n if (ret === obj) {\n /** @type {{[k in string]: any}} */\n ret = {}\n for (let j = 0; j < i; j++) {\n ret[entries[j][0]] = entries[j][1]\n }\n }\n ret.version = v\n }\n }\n break\n default:\n return undefined\n }\n }\n if (requiredCount > 0) {\n return undefined\n }\n return ret\n }\n}\n\nexport const CarV1HeaderOrV2Pragma = {\n toTyped: Types.CarV1HeaderOrV2Pragma,\n toRepresentation: Reprs.CarV1HeaderOrV2Pragma\n}\n", "import { makeCborEncoders, objectToTokens } from './encode.js'\nimport { quickEncodeToken } from './jump.js'\n\n/**\n * @typedef {import('../interface').EncodeOptions} EncodeOptions\n * @typedef {import('../interface').TokenTypeEncoder} TokenTypeEncoder\n * @typedef {import('../interface').TokenOrNestedTokens} TokenOrNestedTokens\n */\n\nconst cborEncoders = makeCborEncoders()\n\n/** @type {EncodeOptions} */\nconst defaultEncodeOptions = {\n float64: false,\n quickEncodeToken\n}\n\n/**\n * Calculate the byte length of the given data when encoded as CBOR with the\n * options provided.\n * This calculation will be accurate if the same options are used as when\n * performing a normal encode. Some encode options can change the encoding\n * output length.\n *\n * @param {any} data\n * @param {EncodeOptions} [options]\n * @returns {number}\n */\nexport function encodedLength (data, options) {\n options = Object.assign({}, defaultEncodeOptions, options)\n options.mapSorter = undefined // won't change the length\n const tokens = objectToTokens(data, options)\n return tokensToLength(tokens, cborEncoders, options)\n}\n\n/**\n * Calculate the byte length of the data as represented by the given tokens when\n * encoded as CBOR with the options provided.\n * This function is for advanced users and would not normally be called\n * directly. See `encodedLength()` for appropriate use.\n *\n * @param {TokenOrNestedTokens} tokens\n * @param {TokenTypeEncoder[]} [encoders]\n * @param {EncodeOptions} [options]\n */\nexport function tokensToLength (tokens, encoders = cborEncoders, options = defaultEncodeOptions) {\n if (Array.isArray(tokens)) {\n let len = 0\n for (const token of tokens) {\n len += tokensToLength(token, encoders, options)\n }\n return len\n } else {\n const encoder = encoders[tokens.type.major]\n /* c8 ignore next 3 */\n if (encoder.encodedSize === undefined || typeof encoder.encodedSize !== 'function') {\n throw new Error(`Encoder for ${tokens.type.name} does not have an encodedSize()`)\n }\n return encoder.encodedSize(tokens, options)\n }\n}\n", "import * as CBOR from '@ipld/dag-cbor'\nimport { Token, Type } from 'cborg'\nimport { tokensToLength } from 'cborg/length'\nimport varint from 'varint'\n\n/**\n * @typedef {import('./api.js').CID} CID\n * @typedef {import('./api.js').Block} Block\n * @typedef {import('./api.js').CarBufferWriter} Writer\n * @typedef {import('./api.js').CarBufferWriterOptions} Options\n * @typedef {import('./coding.js').CarEncoder} CarEncoder\n */\n\n/**\n * A simple CAR writer that writes to a pre-allocated buffer.\n *\n * @class\n * @name CarBufferWriter\n * @implements {Writer}\n */\nclass CarBufferWriter {\n /**\n * @param {Uint8Array} bytes\n * @param {number} headerSize\n */\n constructor (bytes, headerSize) {\n /** @readonly */\n this.bytes = bytes\n this.byteOffset = headerSize\n\n /**\n * @readonly\n * @type {CID[]}\n */\n this.roots = []\n this.headerSize = headerSize\n }\n\n /**\n * Add a root to this writer, to be used to create a header when the CAR is\n * finalized with {@link CarBufferWriter.close `close()`}\n *\n * @param {CID} root\n * @param {{resize?:boolean}} [options]\n * @returns {CarBufferWriter}\n */\n addRoot (root, options) {\n addRoot(this, root, options)\n return this\n }\n\n /**\n * Write a `Block` (a `{ cid:CID, bytes:Uint8Array }` pair) to the archive.\n * Throws if there is not enough capacity.\n *\n * @param {Block} block - A `{ cid:CID, bytes:Uint8Array }` pair.\n * @returns {CarBufferWriter}\n */\n write (block) {\n addBlock(this, block)\n return this\n }\n\n /**\n * Finalize the CAR and return it as a `Uint8Array`.\n *\n * @param {object} [options]\n * @param {boolean} [options.resize]\n * @returns {Uint8Array}\n */\n close (options) {\n return close(this, options)\n }\n}\n\n/**\n * @param {CarBufferWriter} writer\n * @param {CID} root\n * @param {{resize?:boolean}} [options]\n */\nexport const addRoot = (writer, root, options = {}) => {\n const { resize = false } = options\n const { bytes, headerSize, byteOffset, roots } = writer\n writer.roots.push(root)\n const size = headerLength(writer)\n // If there is not enough space for the new root\n if (size > headerSize) {\n // Check if we root would fit if we were to resize the head.\n if (size - headerSize + byteOffset < bytes.byteLength) {\n // If resize is enabled resize head\n if (resize) {\n resizeHeader(writer, size)\n // otherwise remove head and throw an error suggesting to resize\n } else {\n roots.pop()\n throw new RangeError(`Header of size ${headerSize} has no capacity for new root ${root}.\n However there is a space in the buffer and you could call addRoot(root, { resize: root }) to resize header to make a space for this root.`)\n }\n // If head would not fit even with resize pop new root and throw error\n } else {\n roots.pop()\n throw new RangeError(`Buffer has no capacity for a new root ${root}`)\n }\n }\n}\n\n/**\n * Calculates number of bytes required for storing given block in CAR. Useful in\n * estimating size of an `ArrayBuffer` for the `CarBufferWriter`.\n *\n * @name CarBufferWriter.blockLength(Block)\n * @param {Block} block\n * @returns {number}\n */\nexport const blockLength = ({ cid, bytes }) => {\n const size = cid.bytes.byteLength + bytes.byteLength\n return varint.encodingLength(size) + size\n}\n\n/**\n * @param {CarBufferWriter} writer\n * @param {Block} block\n */\nexport const addBlock = (writer, { cid, bytes }) => {\n const byteLength = cid.bytes.byteLength + bytes.byteLength\n const size = varint.encode(byteLength)\n if (writer.byteOffset + size.length + byteLength > writer.bytes.byteLength) {\n throw new RangeError('Buffer has no capacity for this block')\n } else {\n writeBytes(writer, size)\n writeBytes(writer, cid.bytes)\n writeBytes(writer, bytes)\n }\n}\n\n/**\n * @param {CarBufferWriter} writer\n * @param {object} [options]\n * @param {boolean} [options.resize]\n */\nexport const close = (writer, options = {}) => {\n const { resize = false } = options\n const { roots, bytes, byteOffset, headerSize } = writer\n\n const headerBytes = CBOR.encode({ version: 1, roots })\n const varintBytes = varint.encode(headerBytes.length)\n\n const size = varintBytes.length + headerBytes.byteLength\n const offset = headerSize - size\n\n // If header size estimate was accurate we just write header and return\n // view into buffer.\n if (offset === 0) {\n writeHeader(writer, varintBytes, headerBytes)\n return bytes.subarray(0, byteOffset)\n // If header was overestimated and `{resize: true}` is passed resize header\n } else if (resize) {\n resizeHeader(writer, size)\n writeHeader(writer, varintBytes, headerBytes)\n return bytes.subarray(0, writer.byteOffset)\n } else {\n throw new RangeError(`Header size was overestimated.\nYou can use close({ resize: true }) to resize header`)\n }\n}\n\n/**\n * @param {CarBufferWriter} writer\n * @param {number} byteLength\n */\nexport const resizeHeader = (writer, byteLength) => {\n const { bytes, headerSize } = writer\n // Move data section to a new offset\n bytes.set(bytes.subarray(headerSize, writer.byteOffset), byteLength)\n // Update header size & byteOffset\n writer.byteOffset += byteLength - headerSize\n writer.headerSize = byteLength\n}\n\n/**\n * @param {CarBufferWriter} writer\n * @param {number[]|Uint8Array} bytes\n */\n\nconst writeBytes = (writer, bytes) => {\n writer.bytes.set(bytes, writer.byteOffset)\n writer.byteOffset += bytes.length\n}\n/**\n * @param {{bytes:Uint8Array}} writer\n * @param {number[]} varint\n * @param {Uint8Array} header\n */\nconst writeHeader = ({ bytes }, varint, header) => {\n bytes.set(varint)\n bytes.set(header, varint.length)\n}\n\nconst headerPreludeTokens = [\n new Token(Type.map, 2),\n new Token(Type.string, 'version'),\n new Token(Type.uint, 1),\n new Token(Type.string, 'roots')\n]\n\nconst CID_TAG = new Token(Type.tag, 42)\n\n/**\n * Calculates header size given the array of byteLength for roots.\n *\n * @name CarBufferWriter.calculateHeaderLength(rootLengths)\n * @param {number[]} rootLengths\n * @returns {number}\n */\nexport const calculateHeaderLength = (rootLengths) => {\n const tokens = [...headerPreludeTokens]\n tokens.push(new Token(Type.array, rootLengths.length))\n for (const rootLength of rootLengths) {\n tokens.push(CID_TAG)\n tokens.push(new Token(Type.bytes, { length: rootLength + 1 }))\n }\n const length = tokensToLength(tokens) // no options needed here because we have simple tokens\n return varint.encodingLength(length) + length\n}\n\n/**\n * Calculates header size given the array of roots.\n *\n * @name CarBufferWriter.headerLength({ roots })\n * @param {object} options\n * @param {CID[]} options.roots\n * @returns {number}\n */\nexport const headerLength = ({ roots }) =>\n calculateHeaderLength(roots.map(cid => cid.bytes.byteLength))\n\n/**\n * Estimates header size given a count of the roots and the expected byte length\n * of the root CIDs. The default length works for a standard CIDv1 with a\n * single-byte multihash code, such as SHA2-256 (i.e. the most common CIDv1).\n *\n * @name CarBufferWriter.estimateHeaderLength(rootCount[, rootByteLength])\n * @param {number} rootCount\n * @param {number} [rootByteLength]\n * @returns {number}\n */\nexport const estimateHeaderLength = (rootCount, rootByteLength = 36) =>\n calculateHeaderLength(new Array(rootCount).fill(rootByteLength))\n\n/**\n * Creates synchronous CAR writer that can be used to encode blocks into a given\n * buffer. Optionally you could pass `byteOffset` and `byteLength` to specify a\n * range inside buffer to write into. If car file is going to have `roots` you\n * need to either pass them under `options.roots` (from which header size will\n * be calculated) or provide `options.headerSize` to allocate required space\n * in the buffer. You may also provide known `roots` and `headerSize` to\n * allocate space for the roots that may not be known ahead of time.\n *\n * Note: Incorrect `headerSize` may lead to copying bytes inside a buffer\n * which will have a negative impact on performance.\n *\n * @name CarBufferWriter.createWriter(buffer[, options])\n * @param {ArrayBuffer} buffer\n * @param {object} [options]\n * @param {CID[]} [options.roots]\n * @param {number} [options.byteOffset]\n * @param {number} [options.byteLength]\n * @param {number} [options.headerSize]\n * @returns {CarBufferWriter}\n */\nexport const createWriter = (buffer, options = {}) => {\n const {\n roots = [],\n byteOffset = 0,\n byteLength = buffer.byteLength,\n headerSize = headerLength({ roots })\n } = options\n const bytes = new Uint8Array(buffer, byteOffset, byteLength)\n\n const writer = new CarBufferWriter(bytes, headerSize)\n for (const root of roots) {\n writer.addRoot(root)\n }\n\n return writer\n}\n", "import { decode as decodeDagCbor } from '@ipld/dag-cbor'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { CIDV0_BYTES, decodeV2Header, decodeVarint, getMultihashLength, V2_HEADER_LENGTH } from './decoder-common.js'\nimport { CarV1HeaderOrV2Pragma } from './header-validator.js'\n\n/**\n * @typedef {import('./api.js').Block} Block\n * @typedef {import('./api.js').BlockHeader} BlockHeader\n * @typedef {import('./api.js').BlockIndex} BlockIndex\n * @typedef {import('./coding.js').BytesReader} BytesReader\n * @typedef {import('./coding.js').CarHeader} CarHeader\n * @typedef {import('./coding.js').CarV2Header} CarV2Header\n * @typedef {import('./coding.js').CarV2FixedHeader} CarV2FixedHeader\n * @typedef {import('./coding.js').CarDecoder} CarDecoder\n */\n\n/**\n * Reads header data from a `BytesReader`. The header may either be in the form\n * of a `CarHeader` or `CarV2Header` depending on the CAR being read.\n *\n * @name async decoder.readHeader(reader)\n * @param {BytesReader} reader\n * @param {number} [strictVersion]\n * @returns {Promise<CarHeader|CarV2Header>}\n */\nexport async function readHeader (reader, strictVersion) {\n const length = decodeVarint(await reader.upTo(8), reader)\n if (length === 0) {\n throw new Error('Invalid CAR header (zero length)')\n }\n const header = await reader.exactly(length, true)\n const block = decodeDagCbor(header)\n if (CarV1HeaderOrV2Pragma.toTyped(block) === undefined) {\n throw new Error('Invalid CAR header format')\n }\n if ((block.version !== 1 && block.version !== 2) || (strictVersion !== undefined && block.version !== strictVersion)) {\n throw new Error(`Invalid CAR version: ${block.version}${strictVersion !== undefined ? ` (expected ${strictVersion})` : ''}`)\n }\n if (block.version === 1) {\n // CarV1HeaderOrV2Pragma makes roots optional, let's make it mandatory\n if (!Array.isArray(block.roots)) {\n throw new Error('Invalid CAR header format')\n }\n return block\n }\n // version 2\n if (block.roots !== undefined) {\n throw new Error('Invalid CAR header format')\n }\n const v2Header = decodeV2Header(await reader.exactly(V2_HEADER_LENGTH, true))\n reader.seek(v2Header.dataOffset - reader.pos)\n const v1Header = await readHeader(reader, 1)\n return Object.assign(v1Header, v2Header)\n}\n\n/**\n * @param {BytesReader} reader\n * @returns {Promise<CID>}\n */\nasync function readCid (reader) {\n const first = await reader.exactly(2, false)\n if (first[0] === CIDV0_BYTES.SHA2_256 && first[1] === CIDV0_BYTES.LENGTH) {\n // cidv0 32-byte sha2-256\n const bytes = await reader.exactly(34, true)\n const multihash = Digest.decode(bytes)\n return CID.create(0, CIDV0_BYTES.DAG_PB, multihash)\n }\n\n const version = decodeVarint(await reader.upTo(8), reader)\n if (version !== 1) {\n throw new Error(`Unexpected CID version (${version})`)\n }\n const codec = decodeVarint(await reader.upTo(8), reader)\n const bytes = await reader.exactly(getMultihashLength(await reader.upTo(8)), true)\n const multihash = Digest.decode(bytes)\n return CID.create(version, codec, multihash)\n}\n\n/**\n * Reads the leading data of an individual block from CAR data from a\n * `BytesReader`. Returns a `BlockHeader` object which contains\n * `{ cid, length, blockLength }` which can be used to either index the block\n * or read the block binary data.\n *\n * @name async decoder.readBlockHead(reader)\n * @param {BytesReader} reader\n * @returns {Promise<BlockHeader>}\n */\nexport async function readBlockHead (reader) {\n // length includes a CID + Binary, where CID has a variable length\n // we have to deal with\n const start = reader.pos\n let length = decodeVarint(await reader.upTo(8), reader)\n if (length === 0) {\n throw new Error('Invalid CAR section (zero length)')\n }\n length += (reader.pos - start)\n const cid = await readCid(reader)\n const blockLength = length - Number(reader.pos - start) // subtract CID length\n\n return { cid, length, blockLength }\n}\n\n/**\n * @param {BytesReader} reader\n * @returns {Promise<Block>}\n */\nasync function readBlock (reader) {\n const { cid, blockLength } = await readBlockHead(reader)\n const bytes = await reader.exactly(blockLength, true)\n return { bytes, cid }\n}\n\n/**\n * @param {BytesReader} reader\n * @returns {Promise<BlockIndex>}\n */\nasync function readBlockIndex (reader) {\n const offset = reader.pos\n const { cid, length, blockLength } = await readBlockHead(reader)\n const index = { cid, length, blockLength, offset, blockOffset: reader.pos }\n reader.seek(index.blockLength)\n return index\n}\n\n/**\n * Creates a `CarDecoder` from a `BytesReader`. The `CarDecoder` is as async\n * interface that will consume the bytes from the `BytesReader` to yield a\n * `header()` and either `blocks()` or `blocksIndex()` data.\n *\n * @name decoder.createDecoder(reader)\n * @param {BytesReader} reader\n * @returns {CarDecoder}\n */\nexport function createDecoder (reader) {\n const headerPromise = (async () => {\n const header = await readHeader(reader)\n if (header.version === 2) {\n const v1length = reader.pos - header.dataOffset\n reader = limitReader(reader, header.dataSize - v1length)\n }\n return header\n })()\n\n return {\n header: () => headerPromise,\n\n async * blocks () {\n await headerPromise\n while ((await reader.upTo(8)).length > 0) {\n yield await readBlock(reader)\n }\n },\n\n async * blocksIndex () {\n await headerPromise\n while ((await reader.upTo(8)).length > 0) {\n yield await readBlockIndex(reader)\n }\n }\n }\n}\n\n/**\n * Creates a `BytesReader` from a `Uint8Array`.\n *\n * @name decoder.bytesReader(bytes)\n * @param {Uint8Array} bytes\n * @returns {BytesReader}\n */\nexport function bytesReader (bytes) {\n let pos = 0\n\n /** @type {BytesReader} */\n return {\n async upTo (length) {\n const out = bytes.subarray(pos, pos + Math.min(length, bytes.length - pos))\n return out\n },\n\n async exactly (length, seek = false) {\n if (length > bytes.length - pos) {\n throw new Error('Unexpected end of data')\n }\n const out = bytes.subarray(pos, pos + length)\n if (seek) {\n pos += length\n }\n return out\n },\n\n seek (length) {\n pos += length\n },\n\n get pos () {\n return pos\n }\n }\n}\n\n/**\n * reusable reader for streams and files, we just need a way to read an\n * additional chunk (of some undetermined size) and a way to close the\n * reader when finished\n *\n * @param {() => Promise<Uint8Array|null>} readChunk\n * @returns {BytesReader}\n */\nexport function chunkReader (readChunk /*, closer */) {\n let pos = 0\n let have = 0\n let offset = 0\n let currentChunk = new Uint8Array(0)\n\n const read = async (/** @type {number} */ length) => {\n have = currentChunk.length - offset\n const bufa = /** @type {Uint8Array<ArrayBufferLike>[]} */([currentChunk.subarray(offset)])\n while (have < length) {\n const chunk = await readChunk()\n if (chunk == null) {\n break\n }\n /* c8 ignore next 8 */\n // undo this ignore ^ when we have a fd implementation that can seek()\n if (have < 0) { // because of a seek()\n /* c8 ignore next 4 */\n // toohard to test the else\n if (chunk.length > have) {\n bufa.push(chunk.subarray(-have))\n } // else discard\n } else {\n bufa.push(chunk)\n }\n have += chunk.length\n }\n currentChunk = new Uint8Array(bufa.reduce((p, c) => p + c.length, 0))\n let off = 0\n for (const b of bufa) {\n currentChunk.set(b, off)\n off += b.length\n }\n offset = 0\n }\n\n /** @type {BytesReader} */\n return {\n async upTo (length) {\n if (currentChunk.length - offset < length) {\n await read(length)\n }\n return currentChunk.subarray(offset, offset + Math.min(currentChunk.length - offset, length))\n },\n\n async exactly (length, seek = false) {\n if (currentChunk.length - offset < length) {\n await read(length)\n }\n if (currentChunk.length - offset < length) {\n throw new Error('Unexpected end of data')\n }\n const out = currentChunk.subarray(offset, offset + length)\n if (seek) {\n pos += length\n offset += length\n }\n return out\n },\n\n seek (length) {\n pos += length\n offset += length\n },\n\n get pos () {\n return pos\n }\n }\n}\n\n/**\n * Creates a `BytesReader` from an `AsyncIterable<Uint8Array>`, which allows for\n * consumption of CAR data from a streaming source.\n *\n * @name decoder.asyncIterableReader(asyncIterable)\n * @param {AsyncIterable<Uint8Array>} asyncIterable\n * @returns {BytesReader}\n */\nexport function asyncIterableReader (asyncIterable) {\n const iterator = asyncIterable[Symbol.asyncIterator]()\n\n async function readChunk () {\n const next = await iterator.next()\n if (next.done) {\n return null\n }\n return next.value\n }\n\n return chunkReader(readChunk)\n}\n\n/**\n * Wraps a `BytesReader` in a limiting `BytesReader` which limits maximum read\n * to `byteLimit` bytes. It _does not_ update `pos` of the original\n * `BytesReader`.\n *\n * @name decoder.limitReader(reader, byteLimit)\n * @param {BytesReader} reader\n * @param {number} byteLimit\n * @returns {BytesReader}\n */\nexport function limitReader (reader, byteLimit) {\n let bytesRead = 0\n\n /** @type {BytesReader} */\n return {\n async upTo (length) {\n let bytes = await reader.upTo(length)\n if (bytes.length + bytesRead > byteLimit) {\n bytes = bytes.subarray(0, byteLimit - bytesRead)\n }\n return bytes\n },\n\n async exactly (length, seek = false) {\n const bytes = await reader.exactly(length, seek)\n if (bytes.length + bytesRead > byteLimit) {\n throw new Error('Unexpected end of data')\n }\n if (seek) {\n bytesRead += length\n }\n return bytes\n },\n\n seek (length) {\n bytesRead += length\n reader.seek(length)\n },\n\n get pos () {\n return reader.pos\n }\n }\n}\n", "import { encode as dagCborEncode } from '@ipld/dag-cbor'\nimport varint from 'varint'\n\n/**\n * @typedef {import('multiformats').CID} CID\n * @typedef {import('./api.js').Block} Block\n * @typedef {import('./coding.js').CarEncoder} CarEncoder\n * @typedef {import('./coding.js').IteratorChannel_Writer<Uint8Array>} IteratorChannel_Writer\n */\n\nconst CAR_V1_VERSION = 1\n\n/**\n * Create a header from an array of roots.\n *\n * @param {CID[]} roots\n * @returns {Uint8Array}\n */\nexport function createHeader (roots) {\n const headerBytes = dagCborEncode({ version: CAR_V1_VERSION, roots })\n const varintBytes = varint.encode(headerBytes.length)\n const header = new Uint8Array(varintBytes.length + headerBytes.length)\n header.set(varintBytes, 0)\n header.set(headerBytes, varintBytes.length)\n return header\n}\n\n/**\n * @param {IteratorChannel_Writer} writer\n * @returns {CarEncoder}\n */\nfunction createEncoder (writer) {\n // none of this is wrapped in a mutex, that needs to happen above this to\n // avoid overwrites\n\n return {\n /**\n * @param {CID[]} roots\n * @returns {Promise<void>}\n */\n async setRoots (roots) {\n const bytes = createHeader(roots)\n await writer.write(bytes)\n },\n\n /**\n * @param {Block} block\n * @returns {Promise<void>}\n */\n async writeBlock (block) {\n const { cid, bytes } = block\n await writer.write(new Uint8Array(varint.encode(cid.bytes.length + bytes.length)))\n await writer.write(cid.bytes)\n if (bytes.length) {\n // zero-length blocks are valid, but it'd be safer if we didn't write them\n await writer.write(bytes)\n }\n },\n\n /**\n * @returns {Promise<void>}\n */\n async close () {\n await writer.end()\n },\n\n /**\n * @returns {number}\n */\n version () {\n return CAR_V1_VERSION\n }\n }\n}\n\nexport { createEncoder }\n", "/**\n * @template {any} T\n * @typedef {import('./coding.js').IteratorChannel<T>} IteratorChannel\n */\n\nfunction noop () {}\n\n/**\n * @template {any} T\n * @returns {IteratorChannel<T>}\n */\nexport function create () {\n /** @type {T[]} */\n const chunkQueue = []\n /** @type {Promise<void> | null} */\n let drainer = null\n let drainerResolver = noop\n let ended = false\n /** @type {Promise<IteratorResult<T>> | null} */\n let outWait = null\n let outWaitResolver = noop\n\n const makeDrainer = () => {\n if (!drainer) {\n drainer = new Promise((resolve) => {\n drainerResolver = () => {\n drainer = null\n drainerResolver = noop\n resolve()\n }\n })\n }\n return drainer\n }\n\n /**\n * @returns {IteratorChannel<T>}\n */\n const writer = {\n /**\n * @param {T} chunk\n * @returns {Promise<void>}\n */\n write (chunk) {\n chunkQueue.push(chunk)\n const drainer = makeDrainer()\n outWaitResolver()\n return drainer\n },\n\n async end () {\n ended = true\n const drainer = makeDrainer()\n outWaitResolver()\n await drainer\n }\n }\n\n /** @type {AsyncIterator<T>} */\n const iterator = {\n /** @returns {Promise<IteratorResult<T>>} */\n async next () {\n const chunk = chunkQueue.shift()\n if (chunk) {\n if (chunkQueue.length === 0) {\n drainerResolver()\n }\n return { done: false, value: chunk }\n }\n\n if (ended) {\n drainerResolver()\n return { done: true, value: undefined }\n }\n\n if (!outWait) {\n outWait = new Promise((resolve) => {\n outWaitResolver = () => {\n outWait = null\n outWaitResolver = noop\n return resolve(iterator.next())\n }\n })\n }\n\n return outWait\n }\n }\n\n return { writer, iterator }\n}\n", "import { CID } from 'multiformats/cid'\nimport { bytesReader, readHeader } from './decoder.js'\nimport { createEncoder, createHeader } from './encoder.js'\nimport { create as iteratorChannel } from './iterator-channel.js'\n\n/**\n * @typedef {import('./api.js').Block} Block\n * @typedef {import('./api.js').BlockWriter} BlockWriter\n * @typedef {import('./api.js').WriterChannel} WriterChannel\n * @typedef {import('./coding.js').CarEncoder} CarEncoder\n * @typedef {import('./coding.js').IteratorChannel<Uint8Array>} IteratorChannel\n */\n\n/**\n * Provides a writer interface for the creation of CAR files.\n *\n * Creation of a `CarWriter` involves the instatiation of an input / output pair\n * in the form of a `WriterChannel`, which is a\n * `{ writer:CarWriter, out:AsyncIterable<Uint8Array> }` pair. These two\n * components form what can be thought of as a stream-like interface. The\n * `writer` component (an instantiated `CarWriter`), has methods to\n * {@link CarWriter.put `put()`} new blocks and {@link CarWriter.put `close()`}\n * the writing operation (finalising the CAR archive). The `out` component is\n * an `AsyncIterable` that yields the bytes of the archive. This can be\n * redirected to a file or other sink. In Node.js, you can use the\n * [`Readable.from()`](https://nodejs.org/api/stream.html#stream_stream_readable_from_iterable_options)\n * API to convert this to a standard Node.js stream, or it can be directly fed\n * to a\n * [`stream.pipeline()`](https://nodejs.org/api/stream.html#stream_stream_pipeline_source_transforms_destination_callback).\n *\n * The channel will provide a form of backpressure. The `Promise` from a\n * `write()` won't resolve until the resulting data is drained from the `out`\n * iterable.\n *\n * It is also possible to ignore the `Promise` from `write()` calls and allow\n * the generated data to queue in memory. This should be avoided for large CAR\n * archives of course due to the memory costs and potential for memory overflow.\n *\n * Load this class with either\n * `import { CarWriter } from '@ipld/car/writer'`\n * (`const { CarWriter } = require('@ipld/car/writer')`). Or\n * `import { CarWriter } from '@ipld/car'`\n * (`const { CarWriter } = require('@ipld/car')`). The former will likely\n * result in smaller bundle sizes where this is important.\n *\n * @name CarWriter\n * @class\n * @implements {BlockWriter}\n */\nexport class CarWriter {\n /**\n * @param {CID[]} roots\n * @param {CarEncoder} encoder\n */\n constructor (roots, encoder) {\n this._encoder = encoder\n /** @type {Promise<void>} */\n this._mutex = encoder.setRoots(roots)\n this._ended = false\n }\n\n /**\n * Write a `Block` (a `{ cid:CID, bytes:Uint8Array }` pair) to the archive.\n *\n * @function\n * @memberof CarWriter\n * @instance\n * @async\n * @param {Block} block - A `{ cid:CID, bytes:Uint8Array }` pair.\n * @returns {Promise<void>} The returned promise will only resolve once the\n * bytes this block generates are written to the `out` iterable.\n */\n async put (block) {\n if (!(block.bytes instanceof Uint8Array) || !block.cid) {\n throw new TypeError('Can only write {cid, bytes} objects')\n }\n if (this._ended) {\n throw new Error('Already closed')\n }\n const cid = CID.asCID(block.cid)\n if (!cid) {\n throw new TypeError('Can only write {cid, bytes} objects')\n }\n this._mutex = this._mutex.then(() => this._encoder.writeBlock({ cid, bytes: block.bytes }))\n return this._mutex\n }\n\n /**\n * Finalise the CAR archive and signal that the `out` iterable should end once\n * any remaining bytes are written.\n *\n * @function\n * @memberof CarWriter\n * @instance\n * @async\n * @returns {Promise<void>}\n */\n async close () {\n if (this._ended) {\n throw new Error('Already closed')\n }\n await this._mutex\n this._ended = true\n return this._encoder.close()\n }\n\n /**\n * Returns the version number of the CAR file being written\n *\n * @returns {number}\n */\n version () {\n return this._encoder.version()\n }\n\n /**\n * Create a new CAR writer \"channel\" which consists of a\n * `{ writer:CarWriter, out:AsyncIterable<Uint8Array> }` pair.\n *\n * @async\n * @static\n * @memberof CarWriter\n * @param {CID[] | CID | void} roots\n * @returns {WriterChannel} The channel takes the form of\n * `{ writer:CarWriter, out:AsyncIterable<Uint8Array> }`.\n */\n static create (roots) {\n roots = toRoots(roots)\n const { encoder, iterator } = encodeWriter()\n const writer = new CarWriter(roots, encoder)\n const out = new CarWriterOut(iterator)\n return { writer, out }\n }\n\n /**\n * Create a new CAR appender \"channel\" which consists of a\n * `{ writer:CarWriter, out:AsyncIterable<Uint8Array> }` pair.\n * This appender does not consider roots and does not produce a CAR header.\n * It is designed to append blocks to an _existing_ CAR archive. It is\n * expected that `out` will be concatenated onto the end of an existing\n * archive that already has a properly formatted header.\n *\n * @async\n * @static\n * @memberof CarWriter\n * @returns {WriterChannel} The channel takes the form of\n * `{ writer:CarWriter, out:AsyncIterable<Uint8Array> }`.\n */\n static createAppender () {\n const { encoder, iterator } = encodeWriter()\n encoder.setRoots = () => Promise.resolve()\n const writer = new CarWriter([], encoder)\n const out = new CarWriterOut(iterator)\n return { writer, out }\n }\n\n /**\n * Update the list of roots in the header of an existing CAR as represented\n * in a Uint8Array.\n *\n * This operation is an _overwrite_, the total length of the CAR will not be\n * modified. A rejection will occur if the new header will not be the same\n * length as the existing header, in which case the CAR will not be modified.\n * It is the responsibility of the user to ensure that the roots being\n * replaced encode as the same length as the new roots.\n *\n * The byte array passed in an argument will be modified and also returned\n * upon successful modification.\n *\n * @async\n * @static\n * @memberof CarWriter\n * @param {Uint8Array} bytes\n * @param {CID[]} roots - A new list of roots to replace the existing list in\n * the CAR header. The new header must take up the same number of bytes as the\n * existing header, so the roots should collectively be the same byte length\n * as the existing roots.\n * @returns {Promise<Uint8Array>}\n */\n static async updateRootsInBytes (bytes, roots) {\n const reader = bytesReader(bytes)\n await readHeader(reader)\n const newHeader = createHeader(roots)\n if (Number(reader.pos) !== newHeader.length) {\n throw new Error(`updateRoots() can only overwrite a header of the same length (old header is ${reader.pos} bytes, new header is ${newHeader.length} bytes)`)\n }\n bytes.set(newHeader, 0)\n return bytes\n }\n}\n\n/**\n * @class\n * @implements {AsyncIterable<Uint8Array>}\n */\nexport class CarWriterOut {\n /**\n * @param {AsyncIterator<Uint8Array>} iterator\n */\n constructor (iterator) {\n this._iterator = iterator\n }\n\n [Symbol.asyncIterator] () {\n if (this._iterating) {\n throw new Error('Multiple iterator not supported')\n }\n this._iterating = true\n return this._iterator\n }\n}\n\nfunction encodeWriter () {\n /** @type {IteratorChannel} */\n const iw = iteratorChannel()\n const { writer, iterator } = iw\n const encoder = createEncoder(writer)\n return { encoder, iterator }\n}\n\n/**\n * @private\n * @param {CID[] | CID | void} roots\n * @returns {CID[]}\n */\nfunction toRoots (roots) {\n if (roots === undefined) {\n return []\n }\n\n if (!Array.isArray(roots)) {\n const cid = CID.asCID(roots)\n if (!cid) {\n throw new TypeError('roots must be a single CID or an array of CIDs')\n }\n return [cid]\n }\n\n const _roots = []\n for (const root of roots) {\n const _root = CID.asCID(root)\n if (!_root) {\n throw new TypeError('roots must be a single CID or an array of CIDs')\n }\n _roots.push(_root)\n }\n return _roots\n}\n\nexport const __browser = true\n", "/**\n * @packageDocumentation\n *\n * Mostly useful for tests or when you want to be explicit about consuming an iterable without doing anything with any yielded values.\n *\n * @example\n *\n * ```javascript\n * import drain from 'it-drain'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * drain(values)\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import drain from 'it-drain'\n *\n * const values = async function * {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * await drain(values())\n * ```\n */\n\nfunction isAsyncIterable <T> (thing: any): thing is AsyncIterable<T> {\n return thing[Symbol.asyncIterator] != null\n}\n\n/**\n * Drains an (async) iterable discarding its' content and does not return\n * anything\n */\nfunction drain (source: Iterable<unknown>): void\nfunction drain (source: Iterable<unknown> | AsyncIterable<unknown>): Promise<void>\nfunction drain (source: Iterable<unknown> | AsyncIterable<unknown>): Promise<void> | void {\n if (isAsyncIterable(source)) {\n return (async () => {\n for await (const _ of source) { } // eslint-disable-line no-empty,@typescript-eslint/no-unused-vars\n })()\n } else {\n for (const _ of source) { } // eslint-disable-line no-empty,@typescript-eslint/no-unused-vars\n }\n}\n\nexport default drain\n", "/**\n * @packageDocumentation\n *\n * Lets you look at the contents of an async iterator and decide what to do\n *\n * @example\n *\n * ```javascript\n * import peekable from 'it-peekable'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const it = peekable(value)\n *\n * const first = it.peek()\n *\n * console.info(first) // 0\n *\n * it.push(first)\n *\n * console.info([...it])\n * // [ 0, 1, 2, 3, 4 ]\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import peekable from 'it-peekable'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const it = peekable(values())\n *\n * const first = await it.peek()\n *\n * console.info(first) // 0\n *\n * it.push(first)\n *\n * console.info(await all(it))\n * // [ 0, 1, 2, 3, 4 ]\n * ```\n */\n\nexport interface Peek <T> {\n peek(): IteratorResult<T, undefined>\n}\n\nexport interface AsyncPeek <T> {\n peek(): Promise<IteratorResult<T, undefined>>\n}\n\nexport interface Push <T> {\n push(value: T): void\n}\n\nexport type Peekable <T> = Iterable<T> & Peek<T> & Push<T> & Iterator<T>\n\nexport type AsyncPeekable <T> = AsyncIterable<T> & AsyncPeek<T> & Push<T> & AsyncIterator<T>\n\nfunction peekable <T> (iterable: Iterable<T>): Peekable<T>\nfunction peekable <T> (iterable: AsyncIterable<T>): AsyncPeekable<T>\nfunction peekable <T> (iterable: Iterable<T> | AsyncIterable<T>): Peekable<T> | AsyncPeekable<T> {\n // @ts-expect-error can't use Symbol.asyncIterator to index iterable since it might be Iterable\n const [iterator, symbol] = iterable[Symbol.asyncIterator] != null\n // @ts-expect-error can't use Symbol.asyncIterator to index iterable since it might be Iterable\n ? [iterable[Symbol.asyncIterator](), Symbol.asyncIterator]\n // @ts-expect-error can't use Symbol.iterator to index iterable since it might be AsyncIterable\n : [iterable[Symbol.iterator](), Symbol.iterator]\n\n const queue: any[] = []\n\n // @ts-expect-error can't use symbol to index peekable\n return {\n peek: () => {\n return iterator.next()\n },\n push: (value: any) => {\n queue.push(value)\n },\n next: () => {\n if (queue.length > 0) {\n return {\n done: false,\n value: queue.shift()\n }\n }\n\n return iterator.next()\n },\n [symbol] () {\n return this\n }\n }\n}\n\nexport default peekable\n", "/**\n * @packageDocumentation\n *\n * Convert one value from an (async)iterator into another.\n *\n * @example\n *\n * ```javascript\n * import map from 'it-map'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const result = map(values, (val, index) => val++)\n *\n * console.info(result) // [1, 2, 3, 4, 5]\n * ```\n *\n * Async sources and transforms must be awaited:\n *\n * ```javascript\n * import map from 'it-map'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const result = await map(values(), async (val, index) => val++)\n *\n * console.info(result) // [1, 2, 3, 4, 5]\n * ```\n */\n\nimport peek from 'it-peekable'\n\nfunction isAsyncIterable <T> (thing: any): thing is AsyncIterable<T> {\n return thing[Symbol.asyncIterator] != null\n}\n\n/**\n * Takes an (async) iterable and returns one with each item mapped by the passed\n * function\n */\nfunction map <I, O> (source: Iterable<I>, func: (val: I, index: number) => Promise<O>): AsyncGenerator<O, void, undefined>\nfunction map <I, O> (source: Iterable<I>, func: (val: I, index: number) => O): Generator<O, void, undefined>\nfunction map <I, O> (source: AsyncIterable<I> | Iterable<I>, func: (val: I, index: number) => O | Promise<O>): AsyncGenerator<O, void, undefined>\nfunction map <I, O> (source: AsyncIterable<I> | Iterable<I>, func: (val: I, index: number) => O | Promise<O>): AsyncGenerator<O, void, undefined> | Generator<O, void, undefined> {\n let index = 0\n\n if (isAsyncIterable(source)) {\n return (async function * () {\n for await (const val of source) {\n yield func(val, index++)\n }\n })()\n }\n\n // if mapping function returns a promise we have to return an async generator\n const peekable = peek(source)\n const { value, done } = peekable.next()\n\n if (done === true) {\n return (function * () {}())\n }\n\n const res = func(value, index++)\n\n // @ts-expect-error .then is not present on O\n if (typeof res.then === 'function') {\n return (async function * () {\n yield await res\n\n for (const val of peekable) {\n yield func(val, index++)\n }\n })()\n }\n\n const fn = func as (val: I, index: number) => O\n\n return (function * () {\n yield res as O\n\n for (const val of peekable) {\n yield fn(val, index++)\n }\n })()\n}\n\nexport default map\n", "import * as Digest from './digest.js'\nimport type { MultihashHasher } from './interface.js'\n\ntype Await<T> = Promise<T> | T\n\nexport function from <Name extends string, Code extends number> ({ name, code, encode }: { name: Name, code: Code, encode(input: Uint8Array): Await<Uint8Array> }): Hasher<Name, Code> {\n return new Hasher(name, code, encode)\n}\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher<Name extends string, Code extends number> implements MultihashHasher<Code> {\n readonly name: Name\n readonly code: Code\n readonly encode: (input: Uint8Array) => Await<Uint8Array>\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await<Uint8Array>) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n digest (input: Uint8Array): Await<Digest.Digest<Code, number>> {\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 } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n", "import { bytes as binary, CID } from './index.js'\nimport type * as API from './interface.js'\n\nfunction readonly ({ enumerable = true, configurable = false } = {}): { enumerable: boolean, configurable: boolean, writable: false } {\n return { enumerable, configurable, writable: false }\n}\n\nfunction * linksWithin (path: [string | number, string], value: any): Iterable<[string, CID]> {\n if (value != null && typeof value === 'object') {\n if (Array.isArray(value)) {\n for (const [index, element] of value.entries()) {\n const elementPath = [...path, index]\n const cid = CID.asCID(element)\n if (cid != null) {\n yield [elementPath.join('/'), cid]\n } else if (typeof element === 'object') {\n yield * links(element, elementPath)\n }\n }\n } else {\n const cid = CID.asCID(value)\n if (cid != null) {\n yield [path.join('/'), cid]\n } else {\n yield * links(value, path)\n }\n }\n }\n}\n\nfunction * links <T> (source: T, base: Array<string | number>): Iterable<[string, CID]> {\n if (source == null || source instanceof Uint8Array) {\n return\n }\n const cid = CID.asCID(source)\n if (cid != null) {\n yield [base.join('/'), cid]\n }\n for (const [key, value] of Object.entries(source)) {\n const path = [...base, key] as [string | number, string]\n yield * linksWithin(path, value)\n }\n}\n\nfunction * treeWithin (path: [string | number, string], value: any): Iterable<string> {\n if (Array.isArray(value)) {\n for (const [index, element] of value.entries()) {\n const elementPath = [...path, index]\n yield elementPath.join('/')\n if (typeof element === 'object' && (CID.asCID(element) == null)) {\n yield * tree(element, elementPath)\n }\n }\n } else {\n yield * tree(value, path)\n }\n}\n\nfunction * tree <T> (source: T, base: Array<string | number>): Iterable<string> {\n if (source == null || typeof source !== 'object') {\n return\n }\n for (const [key, value] of Object.entries(source)) {\n const path = [...base, key] as [string | number, string]\n yield path.join('/')\n if (value != null && !(value instanceof Uint8Array) && typeof value === 'object' && (CID.asCID(value) == null)) {\n yield * treeWithin(path, value)\n }\n }\n}\n\nfunction get <T> (source: T, path: string[]): API.BlockCursorView<unknown> {\n let node = source as Record<string, any>\n for (const [index, key] of path.entries()) {\n node = node[key]\n if (node == null) {\n throw new Error(`Object has no property at ${path.slice(0, index + 1).map(part => `[${JSON.stringify(part)}]`).join('')}`)\n }\n const cid = CID.asCID(node)\n if (cid != null) {\n return { value: cid, remaining: path.slice(index + 1).join('/') }\n }\n }\n return { value: node }\n}\n\n/**\n * @template T - Logical type of the data encoded in the block\n * @template C - multicodec code corresponding to codec used to encode the block\n * @template A - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @template V - CID version\n */\nexport class Block<T, C extends number, A extends number, V extends API.Version> implements API.BlockView<T, C, A, V> {\n readonly cid: CID<T, C, A, V>\n readonly bytes: API.ByteView<T>\n readonly value: T\n readonly asBlock: this\n\n constructor ({ cid, bytes, value }: { cid: CID<T, C, A, V>, bytes: API.ByteView<T>, value: T }) {\n if (cid == null || bytes == null || typeof value === 'undefined') { throw new Error('Missing required argument') }\n\n this.cid = cid\n this.bytes = bytes\n this.value = value\n this.asBlock = this\n\n // Mark all the properties immutable\n Object.defineProperties(this, {\n cid: readonly(),\n bytes: readonly(),\n value: readonly(),\n asBlock: readonly()\n })\n }\n\n links (): Iterable<[string, CID<unknown, number, number, API.Version>]> {\n return links(this.value, [])\n }\n\n tree (): Iterable<string> {\n return tree(this.value, [])\n }\n\n get (path = '/'): API.BlockCursorView<unknown> {\n return get(this.value, path.split('/').filter(Boolean))\n }\n}\n\ninterface EncodeInput <T, Code extends number, Alg extends number> {\n value: T\n codec: API.BlockEncoder<Code, T>\n hasher: API.MultihashHasher<Alg>\n}\n\n/**\n * @template T - Logical type of the data encoded in the block\n * @template Code - multicodec code corresponding to codec used to encode the block\n * @template Alg - multicodec code corresponding to the hashing algorithm used in CID creation.\n */\nexport async function encode <T, Code extends number, Alg extends number> ({ value, codec, hasher }: EncodeInput<T, Code, Alg>): Promise<API.BlockView<T, Code, Alg>> {\n if (typeof value === 'undefined') { throw new Error('Missing required argument \"value\"') }\n if (codec == null || hasher == null) { throw new Error('Missing required argument: codec or hasher') }\n\n const bytes = codec.encode(value)\n const hash = await hasher.digest(bytes)\n\n const cid = CID.create(\n 1,\n codec.code,\n hash\n ) as CID<T, Code, Alg, 1>\n\n return new Block({ value, bytes, cid })\n}\n\ninterface DecodeInput <T, Code extends number, Alg extends number> {\n bytes: API.ByteView<T>\n codec: API.BlockDecoder<Code, T>\n hasher: API.MultihashHasher<Alg>\n}\n\n/**\n * @template T - Logical type of the data encoded in the block\n * @template Code - multicodec code corresponding to codec used to encode the block\n * @template Alg - multicodec code corresponding to the hashing algorithm used in CID creation.\n */\nexport async function decode <T, Code extends number, Alg extends number> ({ bytes, codec, hasher }: DecodeInput<T, Code, Alg>): Promise<API.BlockView<T, Code, Alg>> {\n if (bytes == null) { throw new Error('Missing required argument \"bytes\"') }\n if (codec == null || hasher == null) { throw new Error('Missing required argument: codec or hasher') }\n\n const value = codec.decode(bytes)\n const hash = await hasher.digest(bytes)\n\n const cid = CID.create(1, codec.code, hash) as CID<T, Code, Alg, 1>\n\n return new Block({ value, bytes, cid })\n}\n\ntype CreateUnsafeInput <T, Code extends number, Alg extends number, V extends API.Version> = {\n cid: API.Link<T, Code, Alg, V>\n value: T\n codec?: API.BlockDecoder<Code, T>\n bytes: API.ByteView<T>\n} | {\n cid: API.Link<T, Code, Alg, V>\n value?: undefined\n codec: API.BlockDecoder<Code, T>\n bytes: API.ByteView<T>\n}\n\n/**\n * @template T - Logical type of the data encoded in the block\n * @template Code - multicodec code corresponding to codec used to encode the block\n * @template Alg - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @template V - CID version\n */\nexport function createUnsafe <T, Code extends number, Alg extends number, V extends API.Version> ({ bytes, cid, value: maybeValue, codec }: CreateUnsafeInput<T, Code, Alg, V>): API.BlockView<T, Code, Alg, V> {\n const value = maybeValue !== undefined\n ? maybeValue\n : (codec?.decode(bytes))\n\n if (value === undefined) { throw new Error('Missing required argument, must either provide \"value\" or \"codec\"') }\n\n return new Block({\n cid: cid as CID<T, Code, Alg, V>,\n bytes,\n value\n })\n}\n\ninterface CreateInput <T, Code extends number, Alg extends number, V extends API.Version> {\n bytes: API.ByteView<T>\n cid: API.Link<T, Code, Alg, V>\n hasher: API.MultihashHasher<Alg>\n codec: API.BlockDecoder<Code, T>\n}\n\n/**\n * @template T - Logical type of the data encoded in the block\n * @template Code - multicodec code corresponding to codec used to encode the block\n * @template Alg - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @template V - CID version\n */\nexport async function create <T, Code extends number, Alg extends number, V extends API.Version> ({ bytes, cid, hasher, codec }: CreateInput<T, Code, Alg, V>): Promise<API.BlockView<T, Code, Alg, V>> {\n if (bytes == null) { throw new Error('Missing required argument \"bytes\"') }\n if (hasher == null) { throw new Error('Missing required argument \"hasher\"') }\n const value = codec.decode(bytes)\n const hash = await hasher.digest(bytes)\n if (!binary.equals(cid.multihash.bytes, hash.bytes)) {\n throw new Error('CID hash does not match bytes')\n }\n\n return createUnsafe({\n bytes,\n cid,\n value,\n codec\n })\n}\n", "export default function pDefer() {\n\tconst deferred = {};\n\n\tdeferred.promise = new Promise((resolve, reject) => {\n\t\tdeferred.resolve = resolve;\n\t\tdeferred.reject = reject;\n\t});\n\n\treturn deferred;\n}\n", "import EventEmitter from './index.js'\n\nexport { EventEmitter }\nexport default EventEmitter\n", "export class TimeoutError extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = 'TimeoutError';\n\t}\n}\n\n/**\nAn error to be thrown when the request is aborted by AbortController.\nDOMException is thrown instead of this Error when DOMException is available.\n*/\nexport class AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\n/**\nTODO: Remove AbortError and just throw DOMException when targeting Node 18.\n*/\nconst getDOMException = errorMessage => globalThis.DOMException === undefined\n\t? new AbortError(errorMessage)\n\t: new DOMException(errorMessage);\n\n/**\nTODO: Remove below function and just 'reject(signal.reason)' when targeting Node 18.\n*/\nconst getAbortedReason = signal => {\n\tconst reason = signal.reason === undefined\n\t\t? getDOMException('This operation was aborted.')\n\t\t: signal.reason;\n\n\treturn reason instanceof Error ? reason : getDOMException(reason);\n};\n\nexport default function pTimeout(promise, options) {\n\tconst {\n\t\tmilliseconds,\n\t\tfallback,\n\t\tmessage,\n\t\tcustomTimers = {setTimeout, clearTimeout},\n\t} = options;\n\n\tlet timer;\n\tlet abortHandler;\n\n\tconst wrappedPromise = new Promise((resolve, reject) => {\n\t\tif (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {\n\t\t\tthrow new TypeError(`Expected \\`milliseconds\\` to be a positive number, got \\`${milliseconds}\\``);\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\tconst {signal} = options;\n\t\t\tif (signal.aborted) {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t}\n\n\t\t\tabortHandler = () => {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t};\n\n\t\t\tsignal.addEventListener('abort', abortHandler, {once: true});\n\t\t}\n\n\t\tif (milliseconds === Number.POSITIVE_INFINITY) {\n\t\t\tpromise.then(resolve, reject);\n\t\t\treturn;\n\t\t}\n\n\t\t// We create the error outside of `setTimeout` to preserve the stack trace.\n\t\tconst timeoutError = new TimeoutError();\n\n\t\ttimer = customTimers.setTimeout.call(undefined, () => {\n\t\t\tif (fallback) {\n\t\t\t\ttry {\n\t\t\t\t\tresolve(fallback());\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (typeof promise.cancel === 'function') {\n\t\t\t\tpromise.cancel();\n\t\t\t}\n\n\t\t\tif (message === false) {\n\t\t\t\tresolve();\n\t\t\t} else if (message instanceof Error) {\n\t\t\t\treject(message);\n\t\t\t} else {\n\t\t\t\ttimeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;\n\t\t\t\treject(timeoutError);\n\t\t\t}\n\t\t}, milliseconds);\n\n\t\t(async () => {\n\t\t\ttry {\n\t\t\t\tresolve(await promise);\n\t\t\t} catch (error) {\n\t\t\t\treject(error);\n\t\t\t}\n\t\t})();\n\t});\n\n\tconst cancelablePromise = wrappedPromise.finally(() => {\n\t\tcancelablePromise.clear();\n\t\tif (abortHandler && options.signal) {\n\t\t\toptions.signal.removeEventListener('abort', abortHandler);\n\t\t}\n\t});\n\n\tcancelablePromise.clear = () => {\n\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\ttimer = undefined;\n\t};\n\n\treturn cancelablePromise;\n}\n", "// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound\n// Used to compute insertion index to keep queue sorted after insertion\nexport default function lowerBound(array, value, comparator) {\n let first = 0;\n let count = array.length;\n while (count > 0) {\n const step = Math.trunc(count / 2);\n let it = first + step;\n if (comparator(array[it], value) <= 0) {\n first = ++it;\n count -= step + 1;\n }\n else {\n count = step;\n }\n }\n return first;\n}\n", "import lowerBound from './lower-bound.js';\nexport default class PriorityQueue {\n #queue = [];\n enqueue(run, options) {\n options = {\n priority: 0,\n ...options,\n };\n const element = {\n priority: options.priority,\n id: options.id,\n run,\n };\n if (this.size === 0 || this.#queue[this.size - 1].priority >= options.priority) {\n this.#queue.push(element);\n return;\n }\n const index = lowerBound(this.#queue, element, (a, b) => b.priority - a.priority);\n this.#queue.splice(index, 0, element);\n }\n setPriority(id, priority) {\n const index = this.#queue.findIndex((element) => element.id === id);\n if (index === -1) {\n throw new ReferenceError(`No promise function with the id \"${id}\" exists in the queue.`);\n }\n const [item] = this.#queue.splice(index, 1);\n this.enqueue(item.run, { priority, id });\n }\n dequeue() {\n const item = this.#queue.shift();\n return item?.run;\n }\n filter(options) {\n return this.#queue.filter((element) => element.priority === options.priority).map((element) => element.run);\n }\n get size() {\n return this.#queue.length;\n }\n}\n", "import { EventEmitter } from 'eventemitter3';\nimport pTimeout, { TimeoutError } from 'p-timeout';\nimport PriorityQueue from './priority-queue.js';\n/**\nPromise queue with concurrency control.\n*/\nexport default class PQueue extends EventEmitter {\n #carryoverConcurrencyCount;\n #isIntervalIgnored;\n #intervalCount = 0;\n #intervalCap;\n #interval;\n #intervalEnd = 0;\n #intervalId;\n #timeoutId;\n #queue;\n #queueClass;\n #pending = 0;\n // The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194\n #concurrency;\n #isPaused;\n #throwOnTimeout;\n // Use to assign a unique identifier to a promise function, if not explicitly specified\n #idAssigner = 1n;\n /**\n Per-operation timeout in milliseconds. Operations fulfill once `timeout` elapses if they haven't already.\n\n Applies to each future operation.\n */\n timeout;\n // TODO: The `throwOnTimeout` option should affect the return types of `add()` and `addAll()`\n constructor(options) {\n super();\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n options = {\n carryoverConcurrencyCount: false,\n intervalCap: Number.POSITIVE_INFINITY,\n interval: 0,\n concurrency: Number.POSITIVE_INFINITY,\n autoStart: true,\n queueClass: PriorityQueue,\n ...options,\n };\n if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) {\n throw new TypeError(`Expected \\`intervalCap\\` to be a number from 1 and up, got \\`${options.intervalCap?.toString() ?? ''}\\` (${typeof options.intervalCap})`);\n }\n if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) {\n throw new TypeError(`Expected \\`interval\\` to be a finite number >= 0, got \\`${options.interval?.toString() ?? ''}\\` (${typeof options.interval})`);\n }\n this.#carryoverConcurrencyCount = options.carryoverConcurrencyCount;\n this.#isIntervalIgnored = options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0;\n this.#intervalCap = options.intervalCap;\n this.#interval = options.interval;\n this.#queue = new options.queueClass();\n this.#queueClass = options.queueClass;\n this.concurrency = options.concurrency;\n this.timeout = options.timeout;\n this.#throwOnTimeout = options.throwOnTimeout === true;\n this.#isPaused = options.autoStart === false;\n }\n get #doesIntervalAllowAnother() {\n return this.#isIntervalIgnored || this.#intervalCount < this.#intervalCap;\n }\n get #doesConcurrentAllowAnother() {\n return this.#pending < this.#concurrency;\n }\n #next() {\n this.#pending--;\n this.#tryToStartAnother();\n this.emit('next');\n }\n #onResumeInterval() {\n this.#onInterval();\n this.#initializeIntervalIfNeeded();\n this.#timeoutId = undefined;\n }\n get #isIntervalPaused() {\n const now = Date.now();\n if (this.#intervalId === undefined) {\n const delay = this.#intervalEnd - now;\n if (delay < 0) {\n // Act as the interval was done\n // We don't need to resume it here because it will be resumed on line 160\n this.#intervalCount = (this.#carryoverConcurrencyCount) ? this.#pending : 0;\n }\n else {\n // Act as the interval is pending\n if (this.#timeoutId === undefined) {\n this.#timeoutId = setTimeout(() => {\n this.#onResumeInterval();\n }, delay);\n }\n return true;\n }\n }\n return false;\n }\n #tryToStartAnother() {\n if (this.#queue.size === 0) {\n // We can clear the interval (\"pause\")\n // Because we can redo it later (\"resume\")\n if (this.#intervalId) {\n clearInterval(this.#intervalId);\n }\n this.#intervalId = undefined;\n this.emit('empty');\n if (this.#pending === 0) {\n this.emit('idle');\n }\n return false;\n }\n if (!this.#isPaused) {\n const canInitializeInterval = !this.#isIntervalPaused;\n if (this.#doesIntervalAllowAnother && this.#doesConcurrentAllowAnother) {\n const job = this.#queue.dequeue();\n if (!job) {\n return false;\n }\n this.emit('active');\n job();\n if (canInitializeInterval) {\n this.#initializeIntervalIfNeeded();\n }\n return true;\n }\n }\n return false;\n }\n #initializeIntervalIfNeeded() {\n if (this.#isIntervalIgnored || this.#intervalId !== undefined) {\n return;\n }\n this.#intervalId = setInterval(() => {\n this.#onInterval();\n }, this.#interval);\n this.#intervalEnd = Date.now() + this.#interval;\n }\n #onInterval() {\n if (this.#intervalCount === 0 && this.#pending === 0 && this.#intervalId) {\n clearInterval(this.#intervalId);\n this.#intervalId = undefined;\n }\n this.#intervalCount = this.#carryoverConcurrencyCount ? this.#pending : 0;\n this.#processQueue();\n }\n /**\n Executes all queued functions until it reaches the limit.\n */\n #processQueue() {\n // eslint-disable-next-line no-empty\n while (this.#tryToStartAnother()) { }\n }\n get concurrency() {\n return this.#concurrency;\n }\n set concurrency(newConcurrency) {\n if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) {\n throw new TypeError(`Expected \\`concurrency\\` to be a number from 1 and up, got \\`${newConcurrency}\\` (${typeof newConcurrency})`);\n }\n this.#concurrency = newConcurrency;\n this.#processQueue();\n }\n async #throwOnAbort(signal) {\n return new Promise((_resolve, reject) => {\n signal.addEventListener('abort', () => {\n reject(signal.reason);\n }, { once: true });\n });\n }\n /**\n Updates the priority of a promise function by its id, affecting its execution order. Requires a defined concurrency limit to take effect.\n\n For example, this can be used to prioritize a promise function to run earlier.\n\n ```js\n import PQueue from 'p-queue';\n\n const queue = new PQueue({concurrency: 1});\n\n queue.add(async () => '\uD83E\uDD84', {priority: 1});\n queue.add(async () => '\uD83E\uDD80', {priority: 0, id: '\uD83E\uDD80'});\n queue.add(async () => '\uD83E\uDD84', {priority: 1});\n queue.add(async () => '\uD83E\uDD84', {priority: 1});\n\n queue.setPriority('\uD83E\uDD80', 2);\n ```\n\n In this case, the promise function with `id: '\uD83E\uDD80'` runs second.\n\n You can also deprioritize a promise function to delay its execution:\n\n ```js\n import PQueue from 'p-queue';\n\n const queue = new PQueue({concurrency: 1});\n\n queue.add(async () => '\uD83E\uDD84', {priority: 1});\n queue.add(async () => '\uD83E\uDD80', {priority: 1, id: '\uD83E\uDD80'});\n queue.add(async () => '\uD83E\uDD84');\n queue.add(async () => '\uD83E\uDD84', {priority: 0});\n\n queue.setPriority('\uD83E\uDD80', -1);\n ```\n Here, the promise function with `id: '\uD83E\uDD80'` executes last.\n */\n setPriority(id, priority) {\n this.#queue.setPriority(id, priority);\n }\n async add(function_, options = {}) {\n // In case `id` is not defined.\n options.id ??= (this.#idAssigner++).toString();\n options = {\n timeout: this.timeout,\n throwOnTimeout: this.#throwOnTimeout,\n ...options,\n };\n return new Promise((resolve, reject) => {\n this.#queue.enqueue(async () => {\n this.#pending++;\n this.#intervalCount++;\n try {\n options.signal?.throwIfAborted();\n let operation = function_({ signal: options.signal });\n if (options.timeout) {\n operation = pTimeout(Promise.resolve(operation), { milliseconds: options.timeout });\n }\n if (options.signal) {\n operation = Promise.race([operation, this.#throwOnAbort(options.signal)]);\n }\n const result = await operation;\n resolve(result);\n this.emit('completed', result);\n }\n catch (error) {\n if (error instanceof TimeoutError && !options.throwOnTimeout) {\n resolve();\n return;\n }\n reject(error);\n this.emit('error', error);\n }\n finally {\n this.#next();\n }\n }, options);\n this.emit('add');\n this.#tryToStartAnother();\n });\n }\n async addAll(functions, options) {\n return Promise.all(functions.map(async (function_) => this.add(function_, options)));\n }\n /**\n Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.)\n */\n start() {\n if (!this.#isPaused) {\n return this;\n }\n this.#isPaused = false;\n this.#processQueue();\n return this;\n }\n /**\n Put queue execution on hold.\n */\n pause() {\n this.#isPaused = true;\n }\n /**\n Clear the queue.\n */\n clear() {\n this.#queue = new this.#queueClass();\n }\n /**\n Can be called multiple times. Useful if you for example add additional items at a later time.\n\n @returns A promise that settles when the queue becomes empty.\n */\n async onEmpty() {\n // Instantly resolve if the queue is empty\n if (this.#queue.size === 0) {\n return;\n }\n await this.#onEvent('empty');\n }\n /**\n @returns A promise that settles when the queue size is less than the given limit: `queue.size < limit`.\n\n If you want to avoid having the queue grow beyond a certain size you can `await queue.onSizeLessThan()` before adding a new item.\n\n Note that this only limits the number of items waiting to start. There could still be up to `concurrency` jobs already running that this call does not include in its calculation.\n */\n async onSizeLessThan(limit) {\n // Instantly resolve if the queue is empty.\n if (this.#queue.size < limit) {\n return;\n }\n await this.#onEvent('next', () => this.#queue.size < limit);\n }\n /**\n The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet.\n\n @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle() {\n // Instantly resolve if none pending and if nothing else is queued\n if (this.#pending === 0 && this.#queue.size === 0) {\n return;\n }\n await this.#onEvent('idle');\n }\n async #onEvent(event, filter) {\n return new Promise(resolve => {\n const listener = () => {\n if (filter && !filter()) {\n return;\n }\n this.off(event, listener);\n resolve();\n };\n this.on(event, listener);\n });\n }\n /**\n Size of the queue, the number of queued items waiting to run.\n */\n get size() {\n return this.#queue.size;\n }\n /**\n Size of the queue, filtered by the given options.\n\n For example, this can be used to find the number of items remaining in the queue with a specific priority level.\n */\n sizeBy(options) {\n // eslint-disable-next-line unicorn/no-array-callback-reference\n return this.#queue.filter(options).length;\n }\n /**\n Number of running items (no longer in the queue).\n */\n get pending() {\n return this.#pending;\n }\n /**\n Whether the queue is currently paused.\n */\n get isPaused() {\n return this.#isPaused;\n }\n}\n", "import type { ExportStrategy } from '../index.js'\nimport type { BlockView } from 'multiformats/block/interface'\nimport type { CID } from 'multiformats/cid'\n\n/**\n * Traverses the DAG breadth-first starting at the target CID and yields all\n * encountered blocks.\n *\n * Blocks linked to from the target block are traversed using codecs defined in\n * the helia config.\n */\nexport class SubgraphExporter implements ExportStrategy {\n async * export (_cid: CID, block: BlockView<any, any, any, 0 | 1>): AsyncGenerator<CID, void, undefined> {\n for (const [, linkedCid] of block.links()) {\n yield linkedCid\n }\n }\n}\n", "import type { TraversalStrategy } from '../index.js'\nimport type { BlockView } from 'multiformats/block/interface'\nimport type { CID } from 'multiformats/cid'\n\n/**\n * A traversal strategy that performs a breadth-first search (so as to not load blocks unnecessarily) looking for a\n * target CID. Traversal stops when we reach the target CID or run out of nodes.\n */\nexport class GraphSearch implements TraversalStrategy {\n private readonly target: CID\n\n constructor (target: CID) {\n this.target = target\n }\n\n isTarget (cid: CID): boolean {\n return this.target.equals(cid)\n }\n\n async * traverse <T extends BlockView<any, any, any, 0 | 1>>(cid: CID, block: T): AsyncGenerator<CID, void, undefined> {\n for (const [, linkedCid] of block.links()) {\n yield linkedCid\n }\n }\n}\n", "import { CarWriter } from '@ipld/car'\nimport drain from 'it-drain'\nimport map from 'it-map'\nimport { createUnsafe } from 'multiformats/block'\nimport defer from 'p-defer'\nimport PQueue from 'p-queue'\nimport { DAG_WALK_QUEUE_CONCURRENCY } from './constants.js'\nimport { SubgraphExporter } from './export-strategies/subgraph-exporter.js'\nimport { GraphSearch } from './traversal-strategies/graph-search.js'\nimport type { CarComponents, Car as CarInterface, ExportCarOptions, ExportStrategy, TraversalStrategy } from './index.js'\nimport type { PutManyBlocksProgressEvents } from '@helia/interface/blocks'\nimport type { CarReader } from '@ipld/car'\nimport type { AbortOptions, Logger } from '@libp2p/interface'\nimport type { CID } from 'multiformats/cid'\nimport type { ProgressOptions } from 'progress-events'\n\n/**\n * Context for the traversal process.\n */\ninterface TraversalContext {\n currentPath: CID[]\n pathsToTarget: CID[][] | null // collect all target paths\n}\n\ninterface WalkDagContext<Strategy> {\n cid: CID\n queue: PQueue\n strategy: Strategy\n options?: ExportCarOptions\n}\n\ninterface ExportWalkDagContext extends WalkDagContext<ExportStrategy> {\n writer: Pick<CarWriter, 'put'>\n recursive?: boolean\n}\n\ninterface TraversalWalkDagContext extends WalkDagContext<TraversalStrategy> {\n traversalContext: TraversalContext\n parentPath: CID[]\n}\n\nexport class Car implements CarInterface {\n private readonly components: CarComponents\n private readonly log: Logger\n\n constructor (components: CarComponents, init: any) {\n this.components = components\n this.log = components.logger.forComponent('helia:car')\n }\n\n async import (reader: Pick<CarReader, 'blocks'>, options?: AbortOptions & ProgressOptions<PutManyBlocksProgressEvents>): Promise<void> {\n await drain(this.components.blockstore.putMany(\n map(reader.blocks(), ({ cid, bytes }) => ({ cid, block: bytes })),\n options\n ))\n }\n\n async export (root: CID | CID[], writer: Pick<CarWriter, 'put' | 'close'>, options?: ExportCarOptions): Promise<void> {\n const deferred = defer<Error | undefined>()\n const roots = Array.isArray(root) ? root : [root]\n\n // Create traversal-specific context\n const traversalContext: TraversalContext = {\n currentPath: [],\n pathsToTarget: null\n }\n\n const traversalStrategy = options?.traversal\n const exportStrategy = options?.exporter ?? new SubgraphExporter()\n\n // use a queue to walk the DAG instead of recursion so we can traverse very\n // large DAGs\n const queue = new PQueue({\n concurrency: DAG_WALK_QUEUE_CONCURRENCY\n })\n\n let startedExport = false\n queue.on('idle', () => {\n if (startedExport) {\n // idle event was called, and started exporting, so we are done.\n deferred.resolve()\n } else if (!startedExport && traversalContext.pathsToTarget?.length === roots.length) {\n // queue is idle, we haven't started exporting yet, and we have path(s)\n // to the target(s), so we can start the export process.\n this.log.trace('starting export of blocks to the car file')\n startedExport = true\n\n for (const path of traversalContext.pathsToTarget) {\n const targetIndex = path.length - 1\n const targetCid = path[targetIndex]\n\n // Process all verification blocks in the path except the target\n path.slice(0, -1).forEach(cid => {\n void queue.add(async () => {\n await this.#exportDagNode({ cid, queue, writer, strategy: exportStrategy, options, recursive: false })\n })\n .catch((err) => {\n this.log.error('error during queue operation - %e', err)\n })\n })\n\n // Process the target block (which will recursively export its DAG)\n void queue.add(async () => {\n await this.#exportDagNode({ cid: targetCid, queue, writer, strategy: exportStrategy, options })\n })\n .catch((err) => {\n this.log.error('error during queue operation - %e', err)\n })\n }\n } else {\n // queue is idle, we haven't started exporting yet, and we don't have\n // path(s) to the target(s), so we can't start the export process.\n // this should not happen without a separate error during traversal, but\n // we'll handle it here anyway.\n this.log.trace('no paths to target, skipping export')\n deferred.reject(new Error('Could not traverse to target CID(s)'))\n }\n })\n queue.on('error', (err) => {\n queue.clear()\n deferred.reject(err)\n })\n\n for (const root of roots) {\n void queue.add(async () => {\n this.log.trace('traversing dag from %c', root)\n await this.#traverseDagNode({ cid: root, queue, strategy: traversalStrategy ?? new GraphSearch(root), traversalContext, parentPath: [], options })\n })\n .catch((err) => {\n this.log.error('error during queue operation - %e', err)\n })\n }\n\n // wait for the writer to end\n try {\n await deferred.promise\n } finally {\n await writer.close()\n }\n }\n\n async * stream (root: CID | CID[], options?: ExportCarOptions): AsyncGenerator<Uint8Array, void, undefined> {\n const { writer, out } = CarWriter.create(root)\n\n // has to be done async so we write to `writer` and read from `out` at the\n // same time\n this.export(root, writer, options)\n .catch((err) => {\n this.log.error('error during streaming export - %e', err)\n })\n\n for await (const buf of out) {\n yield buf\n }\n }\n\n /**\n * Traverse a DAG and stop when we reach the target node\n */\n async #traverseDagNode ({ cid, queue, strategy, traversalContext, parentPath, options }: TraversalWalkDagContext): Promise<void> {\n // if we are traversing, we need to gather path(s) to the target(s)\n const currentPath = [...parentPath, cid]\n\n if (strategy.isTarget(cid)) {\n traversalContext.pathsToTarget = traversalContext.pathsToTarget ?? []\n traversalContext.pathsToTarget.push([...currentPath])\n this.log.trace('found path to target %c', cid)\n return\n }\n\n const codec = await this.components.getCodec(cid.code)\n const bytes = await this.components.blockstore.get(cid, options)\n\n // we are recursively traversing the dag\n const decodedBlock = createUnsafe({ bytes, cid, codec })\n\n for await (const nextCid of strategy.traverse(cid, decodedBlock)) {\n void queue.add(async () => {\n await this.#traverseDagNode({ cid: nextCid, queue, strategy, traversalContext, parentPath: currentPath ?? [], options })\n })\n .catch((err) => {\n this.log.error('error during traversal queue operation - %e', err)\n })\n }\n }\n\n /**\n * Use an ExportStrategy to export part of all of a DAG\n */\n async #exportDagNode ({ cid, queue, writer, strategy, options, recursive = true }: ExportWalkDagContext): Promise<void> {\n if (options?.blockFilter?.has(cid.multihash.bytes) === true) {\n return\n }\n\n const codec = await this.components.getCodec(cid.code)\n const bytes = await this.components.blockstore.get(cid, options)\n\n // Mark as processed\n options?.blockFilter?.add(cid.multihash.bytes)\n\n // Write to CAR\n await writer.put({ cid, bytes })\n\n if (recursive) {\n // we are recursively traversing the dag\n const decodedBlock = createUnsafe({ bytes, cid, codec })\n\n for await (const nextCid of strategy.export(cid, decodedBlock)) {\n void queue.add(async () => {\n await this.#exportDagNode({ cid: nextCid, queue, writer, strategy, options })\n })\n .catch((err) => {\n this.log.error('error during export queue operation - %e', err)\n })\n }\n }\n }\n}\n", "import type { ExportStrategy } from '../index.js'\nimport type { BlockView } from 'multiformats/block/interface'\nimport type { CID } from 'multiformats/cid'\n\n/**\n * Yields the first block from the first CID and stops\n */\nexport class BlockExporter implements ExportStrategy {\n async * export (cid: CID, block: BlockView<any, any, any, 0 | 1>): AsyncGenerator<CID, void, undefined> {\n // don't yield the block, index.ts will add it to the car file and then\n // we're done\n }\n}\n", "export class NotUnixFSError extends Error {\n static code = 'ERR_NOT_UNIXFS'\n static message = 'Not a UnixFS node'\n static name = 'NotUnixFSError'\n code = 'ERR_NOT_UNIXFS'\n message = 'Not a UnixFS node'\n name = 'NotUnixFSError'\n}\n", "import { DAG_PB_CODEC_CODE, RAW_PB_CODEC_CODE } from '../constants.js'\nimport { NotUnixFSError } from '../errors.js'\nimport type { ExportStrategy } from '../index.js'\nimport type { BlockView } from 'multiformats/block/interface'\nimport type { CID } from 'multiformats/cid'\n\n/**\n * This exporter is used when you want to generate a car file that contains a\n * single UnixFS file or directory\n */\nexport class UnixFSExporter implements ExportStrategy {\n async * export (cid: CID, block: BlockView<any, any, any, 0 | 1>): AsyncGenerator<CID, void, undefined> {\n if (cid.code !== DAG_PB_CODEC_CODE && cid.code !== RAW_PB_CODEC_CODE) {\n throw new NotUnixFSError('Target CID was not UnixFS - use the SubGraphExporter to export arbitrary graphs')\n }\n\n // yield all the blocks that make up the file or directory\n for (const [, linkedCid] of block.links()) {\n yield linkedCid\n }\n }\n}\n", "import type { TraversalStrategy } from '../index.js'\nimport type { BlockView } from 'multiformats/block/interface'\nimport type { CID } from 'multiformats/cid'\n\n/**\n * Simple strategy that traverses a known path to a target CID.\n *\n * All this strategy does is yield the next CID in the known path.\n */\nexport class CIDPath implements TraversalStrategy {\n private readonly pathToTarget: CID[]\n private readonly target: CID\n\n constructor (pathToTarget: CID[]) {\n this.pathToTarget = pathToTarget\n this.target = pathToTarget[pathToTarget.length - 1]\n }\n\n isTarget (cid: CID): boolean {\n return this.target.equals(cid)\n }\n\n async * traverse <T extends BlockView<any, any, any, 0 | 1>>(cid: CID, _block?: T): AsyncGenerator<CID, void, undefined> {\n const givenCidIndex = this.pathToTarget.indexOf(cid)\n const nextCid = this.pathToTarget[givenCidIndex + 1]\n\n yield nextCid\n }\n}\n", "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/* eslint-disable complexity, no-nested-ternary */\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<T>} ByteView\n */\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ArrayBufferView<T>} 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<T> | ArrayBufferView<T>} buf\n * @returns {ByteView<T>}\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<T>} ByteView\n */\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ArrayBufferView<T>} 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<PBNode>}\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<PBNode> | ArrayBufferView<PBNode>} 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 {\n // ignore parse fail\n }\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", "export class InvalidTypeError extends Error {\n static name = 'InvalidTypeError'\n static code = 'ERR_INVALID_TYPE'\n name = InvalidTypeError.name\n code = InvalidTypeError.code\n\n constructor (message = 'Invalid type') {\n super(message)\n }\n}\n\nexport class InvalidUnixFSMessageError extends Error {\n static name = 'InvalidUnixFSMessageError'\n static code = 'ERR_INVALID_MESSAGE'\n name = InvalidUnixFSMessageError.name\n code = InvalidUnixFSMessageError.code\n\n constructor (message = 'Invalid message') {\n super(message)\n }\n}\n", "/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n", "/* eslint-disable no-fallthrough */\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst N1 = Math.pow(2, 7)\nconst N2 = Math.pow(2, 14)\nconst N3 = Math.pow(2, 21)\nconst N4 = Math.pow(2, 28)\nconst N5 = Math.pow(2, 35)\nconst N6 = Math.pow(2, 42)\nconst N7 = Math.pow(2, 49)\n\n/** Most significant bit of a byte */\nconst MSB = 0x80\n/** Rest of the bits in a byte */\nconst REST = 0x7f\n\nexport function encodingLength (value: number): number {\n if (value < N1) {\n return 1\n }\n\n if (value < N2) {\n return 2\n }\n\n if (value < N3) {\n return 3\n }\n\n if (value < N4) {\n return 4\n }\n\n if (value < N5) {\n return 5\n }\n\n if (value < N6) {\n return 6\n }\n\n if (value < N7) {\n return 7\n }\n\n if (Number.MAX_SAFE_INTEGER != null && value > Number.MAX_SAFE_INTEGER) {\n throw new RangeError('Could not encode varint')\n }\n\n return 8\n}\n\nexport function encodeUint8Array (value: number, buf: Uint8Array, offset: number = 0): Uint8Array {\n switch (encodingLength(value)) {\n case 8: {\n buf[offset++] = (value & 0xFF) | MSB\n value /= 128\n }\n case 7: {\n buf[offset++] = (value & 0xFF) | MSB\n value /= 128\n }\n case 6: {\n buf[offset++] = (value & 0xFF) | MSB\n value /= 128\n }\n case 5: {\n buf[offset++] = (value & 0xFF) | MSB\n value /= 128\n }\n case 4: {\n buf[offset++] = (value & 0xFF) | MSB\n value >>>= 7\n }\n case 3: {\n buf[offset++] = (value & 0xFF) | MSB\n value >>>= 7\n }\n case 2: {\n buf[offset++] = (value & 0xFF) | MSB\n value >>>= 7\n }\n case 1: {\n buf[offset++] = (value & 0xFF)\n value >>>= 7\n break\n }\n default: throw new Error('unreachable')\n }\n return buf\n}\n\nexport function encodeUint8ArrayList (value: number, buf: Uint8ArrayList, offset: number = 0): Uint8ArrayList {\n switch (encodingLength(value)) {\n case 8: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value /= 128\n }\n case 7: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value /= 128\n }\n case 6: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value /= 128\n }\n case 5: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value /= 128\n }\n case 4: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value >>>= 7\n }\n case 3: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value >>>= 7\n }\n case 2: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value >>>= 7\n }\n case 1: {\n buf.set(offset++, (value & 0xFF))\n value >>>= 7\n break\n }\n default: throw new Error('unreachable')\n }\n return buf\n}\n\nexport function decodeUint8Array (buf: Uint8Array, offset: number): number {\n let b = buf[offset]\n let res = 0\n\n res += b & REST\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 1]\n res += (b & REST) << 7\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 2]\n res += (b & REST) << 14\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 3]\n res += (b & REST) << 21\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 4]\n res += (b & REST) * N4\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 5]\n res += (b & REST) * N5\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 6]\n res += (b & REST) * N6\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 7]\n res += (b & REST) * N7\n if (b < MSB) {\n return res\n }\n\n throw new RangeError('Could not decode varint')\n}\n\nexport function decodeUint8ArrayList (buf: Uint8ArrayList, offset: number): number {\n let b = buf.get(offset)\n let res = 0\n\n res += b & REST\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 1)\n res += (b & REST) << 7\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 2)\n res += (b & REST) << 14\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 3)\n res += (b & REST) << 21\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 4)\n res += (b & REST) * N4\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 5)\n res += (b & REST) * N5\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 6)\n res += (b & REST) * N6\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 7)\n res += (b & REST) * N7\n if (b < MSB) {\n return res\n }\n\n throw new RangeError('Could not decode varint')\n}\n\nexport function encode (value: number): Uint8Array\nexport function encode (value: number, buf: Uint8Array, offset?: number): Uint8Array\nexport function encode (value: number, buf: Uint8ArrayList, offset?: number): Uint8ArrayList\nexport function encode <T extends Uint8Array | Uint8ArrayList = Uint8Array> (value: number, buf?: T, offset: number = 0): T {\n if (buf == null) {\n buf = allocUnsafe(encodingLength(value)) as T\n }\n if (buf instanceof Uint8Array) {\n return encodeUint8Array(value, buf, offset) as T\n } else {\n return encodeUint8ArrayList(value, buf, offset) as T\n }\n}\n\nexport function decode (buf: Uint8ArrayList | Uint8Array, offset: number = 0): number {\n if (buf instanceof Uint8Array) {\n return decodeUint8Array(buf, offset)\n } else {\n return decodeUint8ArrayList(buf, offset)\n }\n}\n", "const f32 = new Float32Array([-0])\nconst f8b = new Uint8Array(f32.buffer)\n\n/**\n * Writes a 32 bit float to a buffer using little endian byte order\n */\nexport function writeFloatLE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[0]\n buf[pos + 1] = f8b[1]\n buf[pos + 2] = f8b[2]\n buf[pos + 3] = f8b[3]\n}\n\n/**\n * Writes a 32 bit float to a buffer using big endian byte order\n */\nexport function writeFloatBE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[3]\n buf[pos + 1] = f8b[2]\n buf[pos + 2] = f8b[1]\n buf[pos + 3] = f8b[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using little endian byte order\n */\nexport function readFloatLE (buf: Uint8Array, pos: number): number {\n f8b[0] = buf[pos]\n f8b[1] = buf[pos + 1]\n f8b[2] = buf[pos + 2]\n f8b[3] = buf[pos + 3]\n return f32[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using big endian byte order\n */\nexport function readFloatBE (buf: Uint8Array, pos: number): number {\n f8b[3] = buf[pos]\n f8b[2] = buf[pos + 1]\n f8b[1] = buf[pos + 2]\n f8b[0] = buf[pos + 3]\n return f32[0]\n}\n\nconst f64 = new Float64Array([-0])\nconst d8b = new Uint8Array(f64.buffer)\n\n/**\n * Writes a 64 bit double to a buffer using little endian byte order\n */\nexport function writeDoubleLE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[0]\n buf[pos + 1] = d8b[1]\n buf[pos + 2] = d8b[2]\n buf[pos + 3] = d8b[3]\n buf[pos + 4] = d8b[4]\n buf[pos + 5] = d8b[5]\n buf[pos + 6] = d8b[6]\n buf[pos + 7] = d8b[7]\n}\n\n/**\n * Writes a 64 bit double to a buffer using big endian byte order\n */\nexport function writeDoubleBE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[7]\n buf[pos + 1] = d8b[6]\n buf[pos + 2] = d8b[5]\n buf[pos + 3] = d8b[4]\n buf[pos + 4] = d8b[3]\n buf[pos + 5] = d8b[2]\n buf[pos + 6] = d8b[1]\n buf[pos + 7] = d8b[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using little endian byte order\n */\nexport function readDoubleLE (buf: Uint8Array, pos: number): number {\n d8b[0] = buf[pos]\n d8b[1] = buf[pos + 1]\n d8b[2] = buf[pos + 2]\n d8b[3] = buf[pos + 3]\n d8b[4] = buf[pos + 4]\n d8b[5] = buf[pos + 5]\n d8b[6] = buf[pos + 6]\n d8b[7] = buf[pos + 7]\n return f64[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using big endian byte order\n */\nexport function readDoubleBE (buf: Uint8Array, pos: number): number {\n d8b[7] = buf[pos]\n d8b[6] = buf[pos + 1]\n d8b[5] = buf[pos + 2]\n d8b[4] = buf[pos + 3]\n d8b[3] = buf[pos + 4]\n d8b[2] = buf[pos + 5]\n d8b[1] = buf[pos + 6]\n d8b[0] = buf[pos + 7]\n return f64[0]\n}\n", "// the largest BigInt we can safely downcast to a Number\nconst MAX_SAFE_NUMBER_INTEGER = BigInt(Number.MAX_SAFE_INTEGER)\nconst MIN_SAFE_NUMBER_INTEGER = BigInt(Number.MIN_SAFE_INTEGER)\n\n/**\n * Constructs new long bits.\n *\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @function Object() { [native code] }\n * @param {number} lo - Low 32 bits, unsigned\n * @param {number} hi - High 32 bits, unsigned\n */\nexport class LongBits {\n public lo: number\n public hi: number\n\n constructor (lo: number, hi: number) {\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 */\n this.lo = lo | 0\n\n /**\n * High bits\n */\n this.hi = hi | 0\n }\n\n /**\n * Converts this long bits to a possibly unsafe JavaScript number\n */\n toNumber (unsigned: boolean = false): number {\n if (!unsigned && (this.hi >>> 31) > 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(lo + hi * 4294967296)\n }\n return this.lo + this.hi * 4294967296\n }\n\n /**\n * Converts this long bits to a bigint\n */\n toBigInt (unsigned: boolean = false): bigint {\n if (unsigned) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n if ((this.hi >>> 31) !== 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(BigInt(lo) + (BigInt(hi) << 32n))\n }\n\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n /**\n * Converts this long bits to a string\n */\n toString (unsigned: boolean = false): string {\n return this.toBigInt(unsigned).toString()\n }\n\n /**\n * Zig-zag encodes this long bits\n */\n zzEncode (): this {\n const 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 */\n zzDecode (): this {\n const 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 */\n length (): number {\n const part0 = this.lo\n const part1 = (this.lo >>> 28 | this.hi << 4) >>> 0\n const 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\n /**\n * Constructs new long bits from the specified number\n */\n static fromBigInt (value: bigint): LongBits {\n if (value === 0n) {\n return zero\n }\n\n if (value < MAX_SAFE_NUMBER_INTEGER && value > MIN_SAFE_NUMBER_INTEGER) {\n return this.fromNumber(Number(value))\n }\n\n const negative = value < 0n\n\n if (negative) {\n value = -value\n }\n\n let hi = value >> 32n\n let lo = value - (hi << 32n)\n\n if (negative) {\n hi = ~hi | 0n\n lo = ~lo | 0n\n\n if (++lo > TWO_32) {\n lo = 0n\n if (++hi > TWO_32) { hi = 0n }\n }\n }\n\n return new LongBits(Number(lo), Number(hi))\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromNumber (value: number): LongBits {\n if (value === 0) { return zero }\n const sign = value < 0\n if (sign) { value = -value }\n let lo = value >>> 0\n let 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) { 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 */\n static from (value: bigint | number | string | { low: number, high: number }): LongBits {\n if (typeof value === 'number') {\n return LongBits.fromNumber(value)\n }\n if (typeof value === 'bigint') {\n return LongBits.fromBigInt(value)\n }\n if (typeof value === 'string') {\n return LongBits.fromBigInt(BigInt(value))\n }\n return value.low != null || value.high != null ? new LongBits(value.low >>> 0, value.high >>> 0) : zero\n }\n}\n\nconst zero = new LongBits(0, 0)\nzero.toBigInt = function () { return 0n }\nzero.zzEncode = zero.zzDecode = function () { return this }\nzero.length = function () { return 1 }\n\nconst TWO_32 = 4294967296n\n", "/**\n * Calculates the UTF8 byte length of a string\n */\nexport function length (string: string): number {\n let len = 0\n let c = 0\n for (let i = 0; i < string.length; ++i) {\n c = string.charCodeAt(i)\n\n if (c < 128) {\n len += 1\n } else if (c < 2048) {\n len += 2\n } else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\n ++i\n len += 4\n } else {\n len += 3\n }\n }\n\n return len\n}\n\n/**\n * Reads UTF8 bytes as a string\n */\nexport function read (buffer: Uint8Array, start: number, end: number): string {\n const len = end - start\n\n if (len < 1) {\n return ''\n }\n\n let parts: string[] | undefined\n const chunk: number[] = []\n let i = 0 // char offset\n let t: number // temporary\n\n while (start < end) {\n t = buffer[start++]\n\n if (t < 128) {\n chunk[i++] = t\n } else if (t > 191 && t < 224) {\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63\n } else if (t > 239 && t < 365) {\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000\n chunk[i++] = 0xD800 + (t >> 10)\n chunk[i++] = 0xDC00 + (t & 1023)\n } else {\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63\n }\n\n if (i > 8191) {\n (parts ?? (parts = [])).push(String.fromCharCode.apply(String, chunk))\n i = 0\n }\n }\n\n if (parts != null) {\n if (i > 0) {\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)))\n }\n\n return parts.join('')\n }\n\n return String.fromCharCode.apply(String, chunk.slice(0, i))\n}\n\n/**\n * Writes a string as UTF8 bytes\n */\nexport function write (string: string, buffer: Uint8Array, offset: number): number {\n const start = offset\n let c1 // character 1\n let c2 // character 2\n\n for (let i = 0; i < string.length; ++i) {\n c1 = string.charCodeAt(i)\n\n if (c1 < 128) {\n buffer[offset++] = c1\n } else if (c1 < 2048) {\n buffer[offset++] = c1 >> 6 | 192\n buffer[offset++] = c1 & 63 | 128\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF)\n ++i\n buffer[offset++] = c1 >> 18 | 240\n buffer[offset++] = c1 >> 12 & 63 | 128\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n } else {\n buffer[offset++] = c1 >> 12 | 224\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n }\n }\n\n return offset - start\n}\n", "import { decodeUint8Array, encodingLength } from 'uint8-varint'\nimport { readFloatLE, readDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport * as utf8 from './utf8.js'\nimport type { Reader } from '../index.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\n/* istanbul ignore next */\nfunction indexOutOfRange (reader: Reader, writeLength?: number): RangeError {\n return RangeError(`index out of range: ${reader.pos} + ${writeLength ?? 1} > ${reader.len}`)\n}\n\nfunction readFixed32End (buf: Uint8Array, end: number): number { // 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 * Constructs a new reader instance using the specified buffer.\n */\nexport class Uint8ArrayReader implements Reader {\n public buf: Uint8Array\n public pos: number\n public len: number\n\n public _slice = Uint8Array.prototype.subarray\n\n constructor (buffer: Uint8Array) {\n /**\n * Read buffer\n */\n this.buf = buffer\n\n /**\n * Read buffer position\n */\n this.pos = 0\n\n /**\n * Read buffer length\n */\n this.len = buffer.length\n }\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32 (): number {\n let value = 4294967295\n\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 if ((this.pos += 5) > this.len) {\n this.pos = this.len\n throw indexOutOfRange(this, 10)\n }\n\n return value\n }\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32 (): number {\n return this.uint32() | 0\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32 (): number {\n const value = this.uint32()\n return value >>> 1 ^ -(value & 1) | 0\n }\n\n /**\n * Reads a varint as a boolean\n */\n bool (): boolean {\n return this.uint32() !== 0\n }\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32 (): number {\n if (this.pos + 4 > this.len) { throw indexOutOfRange(this, 4) }\n\n const res = readFixed32End(this.buf, this.pos += 4)\n\n return res\n }\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32 (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const res = readFixed32End(this.buf, this.pos += 4) | 0\n\n return res\n }\n\n /**\n * Reads a float (32 bit) as a number\n */\n float (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const value = 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 */\n double (): number {\n /* istanbul ignore if */\n if (this.pos + 8 > this.len) { throw indexOutOfRange(this, 4) }\n\n const value = readDoubleLE(this.buf, this.pos)\n this.pos += 8\n return value\n }\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes (): Uint8Array {\n const length = this.uint32()\n const start = this.pos\n const end = this.pos + length\n\n /* istanbul ignore if */\n if (end > this.len) {\n throw indexOutOfRange(this, length)\n }\n\n this.pos += length\n\n return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1\n ? new Uint8Array(0)\n : this.buf.subarray(start, end)\n }\n\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string (): string {\n const 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 */\n skip (length?: number): this {\n if (typeof length === 'number') {\n /* istanbul ignore if */\n if (this.pos + length > this.len) { 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 }\n } while ((this.buf[this.pos++] & 128) !== 0)\n }\n return this\n }\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType (wireType: number): this {\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\n private readLongVarint (): LongBits {\n // tends to deopt with local vars for octet etc.\n const bits = new LongBits(0, 0)\n let 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) { 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) { return bits }\n i = 0\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len) { 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) { 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) { return bits }\n }\n } else {\n for (; i < 5; ++i) {\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n }\n\n throw Error('invalid varint encoding')\n }\n\n private readFixed64 (): LongBits {\n if (this.pos + 8 > this.len) {\n throw indexOutOfRange(this, 8)\n }\n\n const lo = readFixed32End(this.buf, this.pos += 4)\n const hi = readFixed32End(this.buf, this.pos += 4)\n\n return new LongBits(lo, hi)\n }\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64 (): bigint {\n return this.readLongVarint().toBigInt()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n int64Number (): number {\n return this.readLongVarint().toNumber()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a string\n */\n int64String (): string {\n return this.readLongVarint().toString()\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64 (): bigint {\n return this.readLongVarint().toBigInt(true)\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n uint64Number (): number {\n const value = decodeUint8Array(this.buf, this.pos)\n this.pos += encodingLength(value)\n return value\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a string\n */\n uint64String (): string {\n return this.readLongVarint().toString(true)\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64 (): bigint {\n return this.readLongVarint().zzDecode().toBigInt()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * possibly unsafe JavaScript number\n */\n sint64Number (): number {\n return this.readLongVarint().zzDecode().toNumber()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * string\n */\n sint64String (): string {\n return this.readLongVarint().zzDecode().toString()\n }\n\n /**\n * Reads fixed 64 bits\n */\n fixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads fixed 64 bits returned as a possibly unsafe JavaScript number\n */\n fixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads fixed 64 bits returned as a string\n */\n fixed64String (): string {\n return this.readFixed64().toString()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a possibly unsafe\n * JavaScript number\n */\n sfixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a string\n */\n sfixed64String (): string {\n return this.readFixed64().toString()\n }\n}\n\nexport function createReader (buf: Uint8Array | Uint8ArrayList): Reader {\n return new Uint8ArrayReader(buf instanceof Uint8Array ? buf : buf.subarray())\n}\n", "import { createReader } from './utils/reader.js'\nimport type { Codec, DecodeOptions } from './codec.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport function decodeMessage <T> (buf: Uint8Array | Uint8ArrayList, codec: Pick<Codec<T>, 'decode'>, opts?: DecodeOptions<T>): T {\n const reader = createReader(buf)\n\n return codec.decode(reader, undefined, opts)\n}\n", "import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n", "import { from } from './base.js'\n\nconst alphabet = Array.from('\uD83D\uDE80\uD83E\uDE90\u2604\uD83D\uDEF0\uD83C\uDF0C\uD83C\uDF11\uD83C\uDF12\uD83C\uDF13\uD83C\uDF14\uD83C\uDF15\uD83C\uDF16\uD83C\uDF17\uD83C\uDF18\uD83C\uDF0D\uD83C\uDF0F\uD83C\uDF0E\uD83D\uDC09\u2600\uD83D\uDCBB\uD83D\uDDA5\uD83D\uDCBE\uD83D\uDCBF\uD83D\uDE02\u2764\uD83D\uDE0D\uD83E\uDD23\uD83D\uDE0A\uD83D\uDE4F\uD83D\uDC95\uD83D\uDE2D\uD83D\uDE18\uD83D\uDC4D\uD83D\uDE05\uD83D\uDC4F\uD83D\uDE01\uD83D\uDD25\uD83E\uDD70\uD83D\uDC94\uD83D\uDC96\uD83D\uDC99\uD83D\uDE22\uD83E\uDD14\uD83D\uDE06\uD83D\uDE44\uD83D\uDCAA\uD83D\uDE09\u263A\uD83D\uDC4C\uD83E\uDD17\uD83D\uDC9C\uD83D\uDE14\uD83D\uDE0E\uD83D\uDE07\uD83C\uDF39\uD83E\uDD26\uD83C\uDF89\uD83D\uDC9E\u270C\u2728\uD83E\uDD37\uD83D\uDE31\uD83D\uDE0C\uD83C\uDF38\uD83D\uDE4C\uD83D\uDE0B\uD83D\uDC97\uD83D\uDC9A\uD83D\uDE0F\uD83D\uDC9B\uD83D\uDE42\uD83D\uDC93\uD83E\uDD29\uD83D\uDE04\uD83D\uDE00\uD83D\uDDA4\uD83D\uDE03\uD83D\uDCAF\uD83D\uDE48\uD83D\uDC47\uD83C\uDFB6\uD83D\uDE12\uD83E\uDD2D\u2763\uD83D\uDE1C\uD83D\uDC8B\uD83D\uDC40\uD83D\uDE2A\uD83D\uDE11\uD83D\uDCA5\uD83D\uDE4B\uD83D\uDE1E\uD83D\uDE29\uD83D\uDE21\uD83E\uDD2A\uD83D\uDC4A\uD83E\uDD73\uD83D\uDE25\uD83E\uDD24\uD83D\uDC49\uD83D\uDC83\uD83D\uDE33\u270B\uD83D\uDE1A\uD83D\uDE1D\uD83D\uDE34\uD83C\uDF1F\uD83D\uDE2C\uD83D\uDE43\uD83C\uDF40\uD83C\uDF37\uD83D\uDE3B\uD83D\uDE13\u2B50\u2705\uD83E\uDD7A\uD83C\uDF08\uD83D\uDE08\uD83E\uDD18\uD83D\uDCA6\u2714\uD83D\uDE23\uD83C\uDFC3\uD83D\uDC90\u2639\uD83C\uDF8A\uD83D\uDC98\uD83D\uDE20\u261D\uD83D\uDE15\uD83C\uDF3A\uD83C\uDF82\uD83C\uDF3B\uD83D\uDE10\uD83D\uDD95\uD83D\uDC9D\uD83D\uDE4A\uD83D\uDE39\uD83D\uDDE3\uD83D\uDCAB\uD83D\uDC80\uD83D\uDC51\uD83C\uDFB5\uD83E\uDD1E\uD83D\uDE1B\uD83D\uDD34\uD83D\uDE24\uD83C\uDF3C\uD83D\uDE2B\u26BD\uD83E\uDD19\u2615\uD83C\uDFC6\uD83E\uDD2B\uD83D\uDC48\uD83D\uDE2E\uD83D\uDE46\uD83C\uDF7B\uD83C\uDF43\uD83D\uDC36\uD83D\uDC81\uD83D\uDE32\uD83C\uDF3F\uD83E\uDDE1\uD83C\uDF81\u26A1\uD83C\uDF1E\uD83C\uDF88\u274C\u270A\uD83D\uDC4B\uD83D\uDE30\uD83E\uDD28\uD83D\uDE36\uD83E\uDD1D\uD83D\uDEB6\uD83D\uDCB0\uD83C\uDF53\uD83D\uDCA2\uD83E\uDD1F\uD83D\uDE41\uD83D\uDEA8\uD83D\uDCA8\uD83E\uDD2C\u2708\uD83C\uDF80\uD83C\uDF7A\uD83E\uDD13\uD83D\uDE19\uD83D\uDC9F\uD83C\uDF31\uD83D\uDE16\uD83D\uDC76\uD83E\uDD74\u25B6\u27A1\u2753\uD83D\uDC8E\uD83D\uDCB8\u2B07\uD83D\uDE28\uD83C\uDF1A\uD83E\uDD8B\uD83D\uDE37\uD83D\uDD7A\u26A0\uD83D\uDE45\uD83D\uDE1F\uD83D\uDE35\uD83D\uDC4E\uD83E\uDD32\uD83E\uDD20\uD83E\uDD27\uD83D\uDCCC\uD83D\uDD35\uD83D\uDC85\uD83E\uDDD0\uD83D\uDC3E\uD83C\uDF52\uD83D\uDE17\uD83E\uDD11\uD83C\uDF0A\uD83E\uDD2F\uD83D\uDC37\u260E\uD83D\uDCA7\uD83D\uDE2F\uD83D\uDC86\uD83D\uDC46\uD83C\uDFA4\uD83D\uDE47\uD83C\uDF51\u2744\uD83C\uDF34\uD83D\uDCA3\uD83D\uDC38\uD83D\uDC8C\uD83D\uDCCD\uD83E\uDD40\uD83E\uDD22\uD83D\uDC45\uD83D\uDCA1\uD83D\uDCA9\uD83D\uDC50\uD83D\uDCF8\uD83D\uDC7B\uD83E\uDD10\uD83E\uDD2E\uD83C\uDFBC\uD83E\uDD75\uD83D\uDEA9\uD83C\uDF4E\uD83C\uDF4A\uD83D\uDC7C\uD83D\uDC8D\uD83D\uDCE3\uD83E\uDD42')\nconst alphabetBytesToChars: string[] = (alphabet.reduce<string[]>((p, c, i) => { p[i] = c; return p }, ([])))\nconst alphabetCharsToBytes: number[] = (alphabet.reduce<number[]>((p, c, i) => {\n const codePoint = c.codePointAt(0)\n if (codePoint == null) {\n throw new Error(`Invalid character: ${c}`)\n }\n p[codePoint] = i\n return p\n}, ([])))\n\nfunction encode (data: Uint8Array): string {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\nfunction decode (str: string): Uint8Array {\n const byts = []\n for (const char of str) {\n const codePoint = char.codePointAt(0)\n if (codePoint == null) {\n throw new Error(`Invalid character: ${char}`)\n }\n const byt = alphabetCharsToBytes[codePoint]\n if (byt == null) {\n throw new Error(`Non-base256emoji character: ${char}`)\n }\n byts.push(byt)\n }\n return new Uint8Array(byts)\n}\n\nexport const base256emoji = from({\n prefix: '\uD83D\uDE80',\n name: 'base256emoji',\n encode,\n decode\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n", "import { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n", "import type { ArrayBufferView, ByteView } from './interface.js'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\nexport function encode <T> (node: T): ByteView<T> {\n return textEncoder.encode(JSON.stringify(node))\n}\n\nexport function decode <T> (data: ByteView<T> | ArrayBufferView<T>): T {\n return JSON.parse(textDecoder.decode(data))\n}\n", "import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code: 0x0 = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array): Digest.Digest<typeof code, number> {\n return Digest.create(code, encode(input))\n}\n\nexport const identity = { code, name, encode, digest }\n", "/* global crypto */\n\nimport { from } from './hasher.js'\n\nfunction sha (name: AlgorithmIdentifier): (data: Uint8Array) => Promise<Uint8Array> {\n return async data => new Uint8Array(await crypto.subtle.digest(name, data))\n}\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n", "import * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.js'\nimport * as base2 from './bases/base2.js'\nimport * as base256emoji from './bases/base256emoji.js'\nimport * as base32 from './bases/base32.js'\nimport * as base36 from './bases/base36.js'\nimport * as base58 from './bases/base58.js'\nimport * as base64 from './bases/base64.js'\nimport * as base8 from './bases/base8.js'\nimport * as identityBase from './bases/identity.js'\nimport * as json from './codecs/json.js'\nimport * as raw from './codecs/raw.js'\nimport * as identity from './hashes/identity.js'\nimport * as sha2 from './hashes/sha2.js'\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nexport const hashes = { ...sha2, ...identity }\nexport const codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes }\n", "import { bases } from 'multiformats/basics'\nimport type { MultibaseCodec } from 'multiformats'\nimport { allocUnsafe } from '#alloc'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec<any> {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n }\n}\n\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8')\n return 'u' + decoder.decode(buf)\n}, (str) => {\n const encoder = new TextEncoder()\n return encoder.encode(str.substring(1))\n})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i])\n }\n return string\n}, (str) => {\n str = str.substring(1)\n const buf = allocUnsafe(str.length)\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record<SupportedEncodings, MultibaseCodec<any>> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n", "import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function fromString (string: string, encoding: SupportedEncodings = 'utf8'): Uint8Array {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n", "import { allocUnsafe } from 'uint8arrays/alloc'\n\n/**\n * A general purpose buffer pool\n */\nexport default function pool (size?: number): (size: number) => Uint8Array {\n const SIZE = size ?? 8192\n const MAX = SIZE >>> 1\n let slab: Uint8Array\n let offset = SIZE\n return function poolAlloc (size: number) {\n if (size < 1 || size > MAX) {\n return allocUnsafe(size)\n }\n\n if (offset + size > SIZE) {\n slab = allocUnsafe(SIZE)\n offset = 0\n }\n\n const buf = slab.subarray(offset, offset += size)\n\n if ((offset & 7) !== 0) {\n // align to 32 bit\n offset = (offset | 7) + 1\n }\n\n return buf\n }\n}\n", "import { encodeUint8Array, encodingLength } from 'uint8-varint'\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { writeFloatLE, writeDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport pool from './pool.js'\nimport * as utf8 from './utf8.js'\nimport type { Writer } from '../index.js'\n\ninterface WriterOperation<T> {\n (val: T, buf: Uint8Array, pos: number): any\n}\n\n/**\n * Constructs a new writer operation instance.\n *\n * @classdesc Scheduled writer operation\n */\nclass Op<T> {\n /**\n * Function to call\n */\n public fn: WriterOperation<T>\n\n /**\n * Value byte length\n */\n public len: number\n\n /**\n * Next operation\n */\n public next?: Op<any>\n\n /**\n * Value to write\n */\n public val: T\n\n constructor (fn: WriterOperation<T>, len: number, val: T) {\n this.fn = fn\n this.len = len\n this.next = undefined\n this.val = val // type varies\n }\n}\n\n/* istanbul ignore next */\nfunction noop (): void {}\n\n/**\n * Constructs a new writer state instance\n */\nclass State {\n /**\n * Current head\n */\n public head: Op<any>\n\n /**\n * Current tail\n */\n public tail: Op<any>\n\n /**\n * Current buffer length\n */\n public len: number\n\n /**\n * Next state\n */\n public next?: State\n\n constructor (writer: Uint8ArrayWriter) {\n this.head = writer.head\n this.tail = writer.tail\n this.len = writer.len\n this.next = writer.states\n }\n}\n\nconst bufferPool = pool()\n\n/**\n * Allocates a buffer of the specified size\n */\nfunction alloc (size: number): Uint8Array {\n if (globalThis.Buffer != null) {\n return allocUnsafe(size)\n }\n\n return bufferPool(size)\n}\n\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 */\nclass Uint8ArrayWriter implements Writer {\n /**\n * Current length\n */\n public len: number\n\n /**\n * Operations head\n */\n public head: Op<any>\n\n /**\n * Operations tail\n */\n public tail: Op<any>\n\n /**\n * Linked forked states\n */\n public states?: any\n\n constructor () {\n this.len = 0\n this.head = new Op(noop, 0, 0)\n this.tail = this.head\n this.states = null\n }\n\n /**\n * Pushes a new operation to the queue\n */\n _push (fn: WriterOperation<any>, len: number, val: any): this {\n this.tail = this.tail.next = new Op(fn, len, val)\n this.len += len\n\n return this\n }\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32 (value: number): this {\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\n ? 1\n : value < 16384\n ? 2\n : value < 2097152\n ? 3\n : value < 268435456\n ? 4\n : 5,\n value)).len\n return this\n }\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32 (value: number): this {\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 */\n sint32 (value: number): this {\n return this.uint32((value << 1 ^ value >> 31) >>> 0)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number (value: number): this {\n return this._push(encodeUint8Array, encodingLength(value), value)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String (value: string): this {\n return this.uint64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64 (value: bigint): this {\n return this.uint64(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number (value: number): this {\n return this.uint64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String (value: string): this {\n return this.uint64String(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number (value: number): this {\n const bits = LongBits.fromNumber(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String (value: string): this {\n return this.sint64(BigInt(value))\n }\n\n /**\n * Writes a boolish value as a varint\n */\n bool (value: boolean): this {\n return this._push(writeByte, 1, value ? 1 : 0)\n }\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32 (value: number): this {\n return this._push(writeFixed32, 4, value >>> 0)\n }\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32 (value: number): this {\n return this.fixed32(value)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number (value: number): this {\n const bits = LongBits.fromNumber(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String (value: string): this {\n return this.fixed64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64 (value: bigint): this {\n return this.fixed64(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number (value: number): this {\n return this.fixed64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String (value: string): this {\n return this.fixed64String(value)\n }\n\n /**\n * Writes a float (32 bit)\n */\n float (value: number): this {\n return this._push(writeFloatLE, 4, value)\n }\n\n /**\n * Writes a double (64 bit float).\n *\n * @function\n * @param {number} value - Value to write\n * @returns {Writer} `this`\n */\n double (value: number): this {\n return this._push(writeDoubleLE, 8, value)\n }\n\n /**\n * Writes a sequence of bytes\n */\n bytes (value: Uint8Array): this {\n const len = value.length >>> 0\n\n if (len === 0) {\n return this._push(writeByte, 1, 0)\n }\n\n return this.uint32(len)._push(writeBytes, len, value)\n }\n\n /**\n * Writes a string\n */\n string (value: string): this {\n const len = utf8.length(value)\n return len !== 0\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 */\n fork (): this {\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 */\n reset (): this {\n if (this.states != null) {\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 */\n ldelim (): this {\n const head = this.head\n const tail = this.tail\n const len = this.len\n this.reset().uint32(len)\n if (len !== 0) {\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 */\n finish (): Uint8Array {\n let head = this.head.next // skip noop\n const buf = alloc(this.len)\n let pos = 0\n while (head != null) {\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}\n\nfunction writeByte (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n}\n\nfunction writeVarint32 (val: number, buf: Uint8Array, pos: number): void {\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 *\n * @classdesc Scheduled varint writer operation\n */\nclass VarintOp extends Op<number> {\n public next?: Op<any>\n\n constructor (len: number, val: number) {\n super(writeVarint32, len, val)\n this.next = undefined\n }\n}\n\nfunction writeVarint64 (val: LongBits, buf: Uint8Array, pos: number): void {\n while (val.hi !== 0) {\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\nfunction writeFixed32 (val: number, buf: Uint8Array, pos: number): void {\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\nfunction writeBytes (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos)\n}\n\nif (globalThis.Buffer != null) {\n Uint8ArrayWriter.prototype.bytes = function (value: Uint8Array) {\n const len = value.length >>> 0\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeBytesBuffer, len, value)\n }\n\n return this\n }\n\n Uint8ArrayWriter.prototype.string = function (value: string) {\n const len = globalThis.Buffer.byteLength(value)\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeStringBuffer, len, value)\n }\n\n return this\n }\n}\n\nfunction writeBytesBuffer (val: Uint8Array, buf: Uint8Array, pos: number): void {\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\nfunction writeStringBuffer (val: string, buf: Uint8Array, pos: number): void {\n if (val.length < 40) {\n // plain js is faster for short strings (probably due to redundant assertions)\n utf8.write(val, buf, pos)\n // @ts-expect-error buf isn't a Uint8Array?\n } else if (buf.utf8Write != null) {\n // @ts-expect-error buf isn't a Uint8Array?\n buf.utf8Write(val, pos)\n } else {\n buf.set(uint8ArrayFromString(val), pos)\n }\n}\n\n/**\n * Creates a new writer\n */\nexport function createWriter (): Writer {\n return new Uint8ArrayWriter()\n}\n", "import { createWriter } from './utils/writer.js'\nimport type { Codec } from './codec.js'\n\nexport function encodeMessage <T> (message: Partial<T>, codec: Pick<Codec<T>, 'encode'>): Uint8Array {\n const w = createWriter()\n\n codec.encode(message, w, {\n lengthDelimited: false\n })\n\n return w.finish()\n}\n", "import type { Writer, Reader } from './index.js'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeOptions {\n lengthDelimited?: boolean\n writeDefaults?: boolean\n}\n\nexport interface EncodeFunction<T> {\n (value: Partial<T>, writer: Writer, opts?: EncodeOptions): void\n}\n\n// protobuf types that contain multiple values\ntype CollectionTypes = any[] | Map<any, any>\n\n// protobuf types that are not collections or messages\ntype PrimitiveTypes = boolean | number | string | bigint | Uint8Array\n\n// recursive array/map field length limits\ntype CollectionLimits <T> = {\n [K in keyof T]: T[K] extends CollectionTypes ? number :\n T[K] extends PrimitiveTypes ? never : Limits<T[K]>\n}\n\n// recursive array member array/map field length limits\ntype ArrayElementLimits <T> = {\n [K in keyof T as `${string & K}$`]: T[K] extends Array<infer ElementType> ?\n (ElementType extends PrimitiveTypes ? never : Limits<ElementType>) :\n (T[K] extends PrimitiveTypes ? never : Limits<T[K]>)\n}\n\n// recursive map value array/map field length limits\ntype MapValueLimits <T> = {\n [K in keyof T as `${string & K}$value`]: T[K] extends Map<any, infer MapValueType> ?\n (MapValueType extends PrimitiveTypes ? never : Limits<MapValueType>) :\n (T[K] extends PrimitiveTypes ? never : Limits<T[K]>)\n}\n\n// union of collection and array elements\ntype Limits<T> = Partial<CollectionLimits<T> & ArrayElementLimits<T> & MapValueLimits<T>>\n\nexport interface DecodeOptions<T> {\n /**\n * Runtime-specified limits for lengths of repeated/map fields\n */\n limits?: Limits<T>\n}\n\nexport interface DecodeFunction<T> {\n (reader: Reader, length?: number, opts?: DecodeOptions<T>): T\n}\n\nexport interface Codec<T> {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction<T>\n decode: DecodeFunction<T>\n}\n\nexport function createCodec <T> (name: string, type: CODEC_TYPES, encode: EncodeFunction<T>, decode: DecodeFunction<T>): Codec<T> {\n return {\n name,\n type,\n encode,\n decode\n }\n}\n", "import { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, Codec } from '../codec.js'\n\nexport function enumeration <T> (v: any): Codec<T> {\n function findValue (val: string | number): number {\n // Use the reverse mapping to look up the enum key for the stored value\n // https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings\n if (v[val.toString()] == null) {\n throw new Error('Invalid enum value')\n }\n\n return v[val]\n }\n\n const encode: EncodeFunction<number | string> = function enumEncode (val, writer) {\n const enumValue = findValue(val)\n\n writer.int32(enumValue)\n }\n\n const decode: DecodeFunction<number | string> = function enumDecode (reader) {\n const val = reader.int32()\n\n return findValue(val)\n }\n\n // @ts-expect-error yeah yeah\n return createCodec('enum', CODEC_TYPES.VARINT, encode, decode)\n}\n", "import { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { EncodeFunction, DecodeFunction, Codec } from '../codec.js'\n\nexport interface Factory<A, T> {\n new (obj: A): T\n}\n\nexport function message <T> (encode: EncodeFunction<T>, decode: DecodeFunction<T>): Codec<T> {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode)\n}\n", "import { enumeration, encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface Data {\n Type?: Data.DataType\n Data?: Uint8Array\n filesize?: bigint\n blocksizes: bigint[]\n hashType?: bigint\n fanout?: bigint\n mode?: number\n mtime?: UnixTime\n}\n\nexport namespace Data {\n export enum DataType {\n Raw = 'Raw',\n Directory = 'Directory',\n File = 'File',\n Metadata = 'Metadata',\n Symlink = 'Symlink',\n HAMTShard = 'HAMTShard'\n }\n\n enum __DataTypeValues {\n Raw = 0,\n Directory = 1,\n File = 2,\n Metadata = 3,\n Symlink = 4,\n HAMTShard = 5\n }\n\n export namespace DataType {\n export const codec = (): Codec<DataType> => {\n return enumeration<DataType>(__DataTypeValues)\n }\n }\n\n let _codec: Codec<Data>\n\n export const codec = (): Codec<Data> => {\n if (_codec == null) {\n _codec = message<Data>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n Data.DataType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (obj.filesize != null) {\n w.uint32(24)\n w.uint64(obj.filesize)\n }\n\n if (obj.blocksizes != null) {\n for (const value of obj.blocksizes) {\n w.uint32(32)\n w.uint64(value)\n }\n }\n\n if (obj.hashType != null) {\n w.uint32(40)\n w.uint64(obj.hashType)\n }\n\n if (obj.fanout != null) {\n w.uint32(48)\n w.uint64(obj.fanout)\n }\n\n if (obj.mode != null) {\n w.uint32(56)\n w.uint32(obj.mode)\n }\n\n if (obj.mtime != null) {\n w.uint32(66)\n UnixTime.codec().encode(obj.mtime, w)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n blocksizes: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.Type = Data.DataType.codec().decode(reader)\n break\n case 2:\n obj.Data = reader.bytes()\n break\n case 3:\n obj.filesize = reader.uint64()\n break\n case 4:\n obj.blocksizes.push(reader.uint64())\n break\n case 5:\n obj.hashType = reader.uint64()\n break\n case 6:\n obj.fanout = reader.uint64()\n break\n case 7:\n obj.mode = reader.uint32()\n break\n case 8:\n obj.mtime = UnixTime.codec().decode(reader, reader.uint32())\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<Data>): Uint8Array => {\n return encodeMessage(obj, Data.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Data => {\n return decodeMessage(buf, Data.codec())\n }\n}\n\nexport interface UnixTime {\n Seconds?: bigint\n FractionalNanoseconds?: number\n}\n\nexport namespace UnixTime {\n let _codec: Codec<UnixTime>\n\n export const codec = (): Codec<UnixTime> => {\n if (_codec == null) {\n _codec = message<UnixTime>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Seconds != null) {\n w.uint32(8)\n w.int64(obj.Seconds)\n }\n\n if (obj.FractionalNanoseconds != null) {\n w.uint32(21)\n w.fixed32(obj.FractionalNanoseconds)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.Seconds = reader.int64()\n break\n case 2:\n obj.FractionalNanoseconds = reader.fixed32()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<UnixTime>): Uint8Array => {\n return encodeMessage(obj, UnixTime.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): UnixTime => {\n return decodeMessage(buf, UnixTime.codec())\n }\n}\n\nexport interface Metadata {\n MimeType?: string\n}\n\nexport namespace Metadata {\n let _codec: Codec<Metadata>\n\n export const codec = (): Codec<Metadata> => {\n if (_codec == null) {\n _codec = message<Metadata>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.MimeType != null) {\n w.uint32(10)\n w.string(obj.MimeType)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.MimeType = reader.string()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<Metadata>): Uint8Array => {\n return encodeMessage(obj, Metadata.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Metadata => {\n return decodeMessage(buf, Metadata.codec())\n }\n}\n", "/**\n * @packageDocumentation\n *\n * This module contains the protobuf definition of the UnixFS data structure found at the root of all UnixFS DAGs.\n *\n * The UnixFS spec can be found in the [ipfs/specs repository](http://github.com/ipfs/specs)\n *\n * @example Create a file composed of several blocks\n *\n * ```TypeScript\n * import { UnixFS } from 'ipfs-unixfs'\n *\n * const data = new UnixFS({ type: 'file' })\n * data.addBlockSize(256n) // add the size of each block\n * data.addBlockSize(256n)\n * // ...\n * ```\n *\n * @example Create a directory that contains several files\n *\n * Creating a directory that contains several files is achieve by creating a unixfs element that identifies a MerkleDAG node as a directory. The links of that MerkleDAG node are the files that are contained in this directory.\n *\n * ```TypeScript\n * import { UnixFS } from 'ipfs-unixfs'\n *\n * const data = new UnixFS({ type: 'directory' })\n * ```\n *\n * @example Create an unixfs Data element\n *\n * ```TypeScript\n * import { UnixFS } from 'ipfs-unixfs'\n *\n * const data = new UnixFS({\n * // ...options\n * })\n * ```\n *\n * `options` is an optional object argument that might include the following keys:\n *\n * - type (string, default `file`): The type of UnixFS entry. Can be:\n * - `raw`\n * - `directory`\n * - `file`\n * - `metadata`\n * - `symlink`\n * - `hamt-sharded-directory`\n * - data (Uint8Array): The optional data field for this node\n * - blockSizes (Array, default: `[]`): If this is a `file` node that is made up of multiple blocks, `blockSizes` is a list numbers that represent the size of the file chunks stored in each child node. It is used to calculate the total file size.\n * - mode (Number, default `0644` for files, `0755` for directories/hamt-sharded-directories) file mode\n * - mtime (`Date`, `{ secs, nsecs }`, `{ Seconds, FractionalNanoseconds }`, `[ secs, nsecs ]`): The modification time of this node\n *\n * @example Add and remove a block size to the block size list\n *\n * ```TypeScript\n * import { UnixFS } from 'ipfs-unixfs'\n *\n * const data = new UnixFS({ type: 'file' })\n * const sizeInBytes = 100n\n * data.addBlockSize(sizeInBytes)\n * ```\n *\n * ```TypeScript\n * import { UnixFS } from 'ipfs-unixfs'\n *\n * const data = new UnixFS({ type: 'file' })\n *\n * const index = 0\n * data.removeBlockSize(index)\n * ```\n *\n * @example Get total fileSize\n *\n * ```TypeScript\n * import { UnixFS } from 'ipfs-unixfs'\n *\n * const data = new UnixFS({ type: 'file' })\n * data.fileSize() // => size in bytes\n * ```\n *\n * @example Marshal and unmarshal\n *\n * ```TypeScript\n * import { UnixFS } from 'ipfs-unixfs'\n *\n * const data = new UnixFS({ type: 'file' })\n * const marshaled = data.marshal()\n * const unmarshaled = UnixFS.unmarshal(marshaled)\n * ```\n *\n * @example Is this UnixFS entry a directory?\n *\n * ```TypeScript\n * import { UnixFS } from 'ipfs-unixfs'\n *\n * const dir = new UnixFS({ type: 'directory' })\n * dir.isDirectory() // true\n *\n * const file = new UnixFS({ type: 'file' })\n * file.isDirectory() // false\n * ```\n *\n * @example Has an mtime been set?\n *\n * If no modification time has been set, no `mtime` property will be present on the `Data` instance:\n *\n * ```TypeScript\n * import { UnixFS } from 'ipfs-unixfs'\n *\n * const file = new UnixFS({ type: 'file' })\n * file.mtime // undefined\n *\n * Object.prototype.hasOwnProperty.call(file, 'mtime') // false\n *\n * const dir = new UnixFS({ type: 'directory', mtime: { secs: 5n } })\n * dir.mtime // { secs: Number, nsecs: Number }\n * ```\n */\n\nimport { InvalidTypeError, InvalidUnixFSMessageError } from './errors.js'\nimport { Data as PBData } from './unixfs.js'\n\nexport interface Mtime {\n secs: bigint\n nsecs?: number\n}\n\nexport type MtimeLike = Mtime | { Seconds: number, FractionalNanoseconds?: number } | [number, number] | Date\n\nexport type UnixFSType = 'raw' | 'directory' | 'file' | 'metadata' | 'symlink' | 'hamt-sharded-directory'\n\nconst types: Record<string, UnixFSType> = {\n Raw: 'raw',\n Directory: 'directory',\n File: 'file',\n Metadata: 'metadata',\n Symlink: 'symlink',\n HAMTShard: 'hamt-sharded-directory'\n}\n\nconst dirTypes = [\n 'directory',\n 'hamt-sharded-directory'\n]\n\nconst DEFAULT_FILE_MODE = parseInt('0644', 8)\nconst DEFAULT_DIRECTORY_MODE = parseInt('0755', 8)\n\n// https://github.com/ipfs/boxo/blob/364c5040ec91ec8e2a61446e9921e9225704c34d/ipld/unixfs/hamt/hamt.go#L778\nconst MAX_FANOUT = BigInt(1 << 10)\n\nexport interface UnixFSOptions {\n type?: UnixFSType\n data?: Uint8Array\n blockSizes?: bigint[]\n hashType?: bigint\n fanout?: bigint\n mtime?: Mtime\n mode?: number\n}\n\nclass UnixFS {\n /**\n * Decode from protobuf https://github.com/ipfs/specs/blob/master/UNIXFS.md\n */\n static unmarshal (marshaled: Uint8Array): UnixFS {\n const message = PBData.decode(marshaled)\n\n if (message.fanout != null && message.fanout > MAX_FANOUT) {\n throw new InvalidUnixFSMessageError(`Fanout size was too large - ${message.fanout} > ${MAX_FANOUT}`)\n }\n\n const data = new UnixFS({\n type: types[message.Type != null ? message.Type.toString() : 'File'],\n data: message.Data,\n blockSizes: message.blocksizes,\n mode: message.mode,\n mtime: message.mtime != null\n ? {\n secs: message.mtime.Seconds ?? 0n,\n nsecs: message.mtime.FractionalNanoseconds\n }\n : undefined,\n fanout: message.fanout\n })\n\n // make sure we honour the original mode\n data._originalMode = message.mode ?? 0\n\n return data\n }\n\n public type: string\n public data?: Uint8Array\n public blockSizes: bigint[]\n public hashType?: bigint\n public fanout?: bigint\n public mtime?: Mtime\n\n private _mode?: number\n private _originalMode: number\n\n constructor (options: UnixFSOptions = {\n type: 'file'\n }) {\n const {\n type,\n data,\n blockSizes,\n hashType,\n fanout,\n mtime,\n mode\n } = options\n\n if (type != null && !Object.values(types).includes(type)) {\n throw new InvalidTypeError('Type: ' + type + ' is not valid')\n }\n\n this.type = type ?? 'file'\n this.data = data\n this.hashType = hashType\n this.fanout = fanout\n this.blockSizes = blockSizes ?? []\n this._originalMode = 0\n this.mode = mode\n this.mtime = mtime\n }\n\n set mode (mode: number | undefined) {\n if (mode == null) {\n this._mode = this.isDirectory() ? DEFAULT_DIRECTORY_MODE : DEFAULT_FILE_MODE\n } else {\n this._mode = (mode & 0xFFF)\n }\n }\n\n get mode (): number | undefined {\n return this._mode\n }\n\n isDirectory (): boolean {\n return dirTypes.includes(this.type)\n }\n\n addBlockSize (size: bigint): void {\n this.blockSizes.push(size)\n }\n\n removeBlockSize (index: number): void {\n this.blockSizes.splice(index, 1)\n }\n\n /**\n * Returns `0n` for directories or `data.length + sum(blockSizes)` for everything else\n */\n fileSize (): bigint {\n if (this.isDirectory()) {\n // dirs don't have file size\n return 0n\n }\n\n let sum = 0n\n this.blockSizes.forEach((size) => {\n sum += size\n })\n\n if (this.data != null) {\n sum += BigInt(this.data.length)\n }\n\n return sum\n }\n\n /**\n * encode to protobuf Uint8Array\n */\n marshal (): Uint8Array {\n let type\n\n switch (this.type) {\n case 'raw': type = PBData.DataType.Raw; break\n case 'directory': type = PBData.DataType.Directory; break\n case 'file': type = PBData.DataType.File; break\n case 'metadata': type = PBData.DataType.Metadata; break\n case 'symlink': type = PBData.DataType.Symlink; break\n case 'hamt-sharded-directory': type = PBData.DataType.HAMTShard; break\n default:\n throw new InvalidTypeError(`Type: ${type} is not valid`)\n }\n\n let data = this.data\n\n if (this.data == null || this.data.length === 0) {\n data = undefined\n }\n\n let mode\n\n if (this.mode != null) {\n mode = (this._originalMode & 0xFFFFF000) | (this.mode ?? 0)\n\n if (mode === DEFAULT_FILE_MODE && !this.isDirectory()) {\n mode = undefined\n }\n\n if (mode === DEFAULT_DIRECTORY_MODE && this.isDirectory()) {\n mode = undefined\n }\n }\n\n let mtime\n\n if (this.mtime != null) {\n mtime = {\n Seconds: this.mtime.secs,\n FractionalNanoseconds: this.mtime.nsecs\n }\n }\n\n return PBData.encode({\n Type: type,\n Data: data,\n filesize: this.isDirectory() ? undefined : this.fileSize(),\n blocksizes: this.blockSizes,\n hashType: this.hashType,\n fanout: this.fanout,\n mode,\n mtime\n })\n }\n}\n\nexport { UnixFS }\nexport * from './errors.js'\n", "import { decode } from '@ipld/dag-pb'\nimport { UnixFS } from 'ipfs-unixfs'\nimport { DAG_PB_CODEC_CODE } from '../constants.js'\nimport { NotUnixFSError } from '../errors.js'\nimport type { TraversalStrategy } from '../index.js'\nimport type { BlockView } from 'multiformats/block/interface'\nimport type { CID } from 'multiformats/cid'\n\n/**\n * Traverses a DAG containing UnixFS directories\n */\nexport class UnixFSPath implements TraversalStrategy {\n private readonly path: string[]\n\n constructor (path: string) {\n // \"/foo/bar/baz.txt\" -> ['foo', 'bar', 'baz.txt']\n this.path = path.replace(/^\\//, '').split('/')\n }\n\n isTarget (): boolean {\n return this.path.length === 0\n }\n\n async * traverse <T extends BlockView<any, any, any, 0 | 1>>(cid: CID, block: T): AsyncGenerator<CID, void, undefined> {\n if (cid.code !== DAG_PB_CODEC_CODE) {\n throw new NotUnixFSError('Target CID is not UnixFS')\n }\n\n const segment = this.path.shift()\n\n if (segment == null) {\n return\n }\n\n const pb = decode(block.bytes)\n\n if (pb.Data == null) {\n throw new NotUnixFSError('Target CID has no UnixFS data in decoded bytes')\n }\n\n const unixfs = UnixFS.unmarshal(pb.Data)\n\n if (unixfs.type === 'directory') {\n const link = pb.Links.filter(link => link.Name === segment).pop()\n\n if (link == null) {\n throw new NotUnixFSError(`Target CID directory has no link with name ${segment}`)\n }\n\n yield link.Hash\n return\n }\n\n // TODO: HAMT support\n\n throw new NotUnixFSError('Target CID is not a UnixFS directory')\n }\n}\n"],
4
+ "sourcesContent": ["module.exports = encode\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31)\n\nfunction encode(num, out, offset) {\n if (Number.MAX_SAFE_INTEGER && num > Number.MAX_SAFE_INTEGER) {\n encode.bytes = 0\n throw new RangeError('Could not encode varint')\n }\n out = out || []\n offset = offset || 0\n var oldOffset = offset\n\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 \n encode.bytes = offset - oldOffset + 1\n \n return out\n}\n", "module.exports = read\n\nvar MSB = 0x80\n , REST = 0x7F\n\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length\n\n do {\n if (counter >= l || shift > 49) {\n read.bytes = 0\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++]\n res += shift < 28\n ? (b & REST) << shift\n : (b & REST) * Math.pow(2, shift)\n shift += 7\n } while (b >= MSB)\n\n read.bytes = counter - offset\n\n return res\n}\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)\n\nmodule.exports = function (value) {\n return (\n 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 )\n}\n", "module.exports = {\n encode: require('./encode.js')\n , decode: require('./decode.js')\n , encodingLength: require('./length.js')\n}\n", "'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n", "/**\n * @packageDocumentation\n *\n * `@helia/car` provides `import` and `export` methods to read/write Car files\n * to {@link https://github.com/ipfs/helia Helia}'s blockstore.\n *\n * See the {@link Car} interface for all available operations.\n *\n * By default it supports `dag-pb`, `dag-cbor`, `dag-json` and `raw` CIDs, more\n * esoteric DAG walkers can be passed as an init option.\n *\n * @example Exporting a DAG as a CAR file\n *\n * ```typescript\n * import { createHelia } from 'helia'\n * import { car } from '@helia/car'\n * import { CID } from 'multiformats/cid'\n * import nodeFs from 'node:fs'\n *\n * const helia = await createHelia()\n * const cid = CID.parse('QmFoo...')\n *\n * const c = car(helia)\n * const out = nodeFs.createWriteStream('example.car')\n *\n * for await (const buf of c.stream(cid)) {\n * out.write(buf)\n * }\n *\n * out.end()\n * ```\n *\n * @example Exporting a part of a UnixFS DAG as a CAR file\n *\n * ```typescript\n * import { createHelia } from 'helia'\n * import { car, UnixFSPath } from '@helia/car'\n * import { CID } from 'multiformats/cid'\n * import nodeFs from 'node:fs'\n *\n * const helia = await createHelia()\n * const cid = CID.parse('QmFoo...')\n *\n * const c = car(helia)\n * const out = nodeFs.createWriteStream('example.car')\n *\n * for await (const buf of c.stream(cid, {\n * traversal: new UnixFSPath('/foo/bar/baz.txt')\n * })) {\n * out.write(buf)\n * }\n *\n * out.end()\n * ```\n *\n * @example Importing all blocks from a CAR file\n *\n * ```typescript\n * import { createHelia } from 'helia'\n * import { unixfs } from '@helia/unixfs'\n * import { car } from '@helia/car'\n * import { CarReader } from '@ipld/car'\n * import { Readable } from 'node:stream'\n * import nodeFs from 'node:fs'\n *\n * const helia = await createHelia({\n * // ... helia config\n * })\n *\n * // import the car\n * const inStream = nodeFs.createReadStream('example.car')\n * const reader = await CarReader.fromIterable(inStream)\n *\n * const c = car(helia)\n * await c.import(reader)\n * ```\n */\n\nimport { Car as CarClass } from './car.js'\nimport type { CodecLoader } from '@helia/interface'\nimport type { PutManyBlocksProgressEvents, GetBlockProgressEvents, ProviderOptions } from '@helia/interface/blocks'\nimport type { CarWriter, CarReader } from '@ipld/car'\nimport type { AbortOptions, ComponentLogger } from '@libp2p/interface'\nimport type { Filter } from '@libp2p/utils/filters'\nimport type { Blockstore } from 'interface-blockstore'\nimport type { BlockView } from 'multiformats/block/interface'\nimport type { CID } from 'multiformats/cid'\nimport type { ProgressOptions } from 'progress-events'\n\nexport interface CarComponents {\n logger: ComponentLogger\n blockstore: Blockstore\n getCodec: CodecLoader\n}\n\n/**\n * Interface for different traversal strategies.\n *\n * While traversing the DAG, it will yield blocks that it has traversed.\n */\nexport interface TraversalStrategy {\n /**\n * Traverse the DAG and yield the next CID to traverse\n */\n traverse<T extends BlockView<any, any, any, 0 | 1>>(cid: CID, block: T): AsyncGenerator<CID, void, undefined>\n\n /**\n * Returns true if the current CID is the target and we should switch to the\n * export strategy\n */\n isTarget(cid: CID): boolean\n}\n\n/**\n * Interface for different export strategies.\n *\n * When traversal has ended the export begins starting at the target CID, and\n * the export strategy may do further traversal and writing to the car file.\n */\nexport interface ExportStrategy {\n /**\n * Export the DAG and yield the next CID to traverse\n */\n export<T extends BlockView<any, any, any, 0 | 1>>(cid: CID, block: T): AsyncGenerator<CID, void, undefined>\n}\n\nexport * from './export-strategies/index.js'\nexport * from './traversal-strategies/index.js'\n\nexport interface ExportCarOptions extends AbortOptions, ProgressOptions<GetBlockProgressEvents>, ProviderOptions {\n\n /**\n * If true, the blockstore will not do any network requests.\n *\n * @default false\n */\n offline?: boolean\n\n /**\n * If a filter is passed it will be used to deduplicate blocks exported in the\n * car file\n */\n blockFilter?: Filter\n\n /**\n * The traversal strategy to use for the export. This determines how the dag\n * is traversed: either depth first, breadth first, or a custom strategy.\n */\n traversal?: TraversalStrategy\n\n /**\n * Export strategy to use for the export. This should be used to change the\n * blocks included in the exported car file. (e.g. https://specs.ipfs.tech/http-gateways/trustless-gateway/#dag-scope-request-query-parameter)\n */\n exporter?: ExportStrategy\n}\n\n/**\n * The Car interface provides operations for importing and exporting Car files\n * from Helia's underlying blockstore.\n */\nexport interface Car {\n /**\n * Add all blocks in the passed CarReader to the blockstore.\n *\n * @example\n *\n * ```typescript\n * import fs from 'node:fs'\n * import { createHelia } from 'helia'\n * import { car } from '@helia/car\n * import { CarReader } from '@ipld/car'\n *\n * const helia = await createHelia()\n *\n * const inStream = fs.createReadStream('example.car')\n * const reader = await CarReader.fromIterable(inStream)\n *\n * const c = car(helia)\n * await c.import(reader)\n * ```\n */\n import(reader: Pick<CarReader, 'blocks'>, options?: AbortOptions & ProgressOptions<PutManyBlocksProgressEvents>): Promise<void>\n\n /**\n * Store all blocks that make up one or more DAGs in a car file.\n *\n * @example\n *\n * ```typescript\n * import fs from 'node:fs'\n * import { Readable } from 'node:stream'\n * import { car } from '@helia/car'\n * import { CarWriter } from '@ipld/car'\n * import { createHelia } from 'helia'\n * import { CID } from 'multiformats/cid'\n * import { pEvent } from 'p-event'\n *\n * const helia = await createHelia()\n * const cid = CID.parse('QmFoo...')\n *\n * const c = car(helia)\n * const { writer, out } = CarWriter.create(cid)\n * const output = fs.createWriteStream('example.car')\n * const stream = Readable.from(out).pipe(output)\n *\n * await Promise.all([\n * c.export(cid, writer),\n * pEvent(stream, 'close')\n * ])\n * ```\n *\n * @deprecated Use `stream` instead. In a future release `stream` will be renamed `export`.\n */\n export(root: CID | CID[], writer: Pick<CarWriter, 'put' | 'close'>, options?: ExportCarOptions): Promise<void>\n\n /**\n * Returns an AsyncGenerator that yields CAR file bytes.\n *\n * @example\n *\n * ```typescript\n * import { createHelia } from 'helia'\n * import { car } from '@helia/car'\n * import { CID } from 'multiformats/cid'\n *\n * const helia = await createHelia()\n * const cid = CID.parse('QmFoo...')\n *\n * const c = car(helia)\n *\n * for (const buf of c.stream(cid)) {\n * // store or send `buf` somewhere\n * }\n * ```\n */\n stream(root: CID | CID[], options?: ExportCarOptions): AsyncGenerator<Uint8Array, void, undefined>\n}\n\n/**\n * Create a {@link Car} instance for use with {@link https://github.com/ipfs/helia Helia}\n */\nexport function car (helia: CarComponents, init: any = {}): Car {\n return new CarClass(helia, init)\n}\n", "// This is an unfortunate replacement for @sindresorhus/is that we need to\n// re-implement for performance purposes. In particular the is.observable()\n// check is expensive, and unnecessary for our purposes. The values returned\n// are compatible with @sindresorhus/is, however.\n\nconst typeofs = [\n 'string',\n 'number',\n 'bigint',\n 'symbol'\n]\n\nconst objectTypeNames = [\n 'Function',\n 'Generator',\n 'AsyncGenerator',\n 'GeneratorFunction',\n 'AsyncGeneratorFunction',\n 'AsyncFunction',\n 'Observable',\n 'Array',\n 'Buffer',\n 'Object',\n 'RegExp',\n 'Date',\n 'Error',\n 'Map',\n 'Set',\n 'WeakMap',\n 'WeakSet',\n 'ArrayBuffer',\n 'SharedArrayBuffer',\n 'DataView',\n 'Promise',\n 'URL',\n 'HTMLElement',\n 'Int8Array',\n 'Uint8Array',\n 'Uint8ClampedArray',\n 'Int16Array',\n 'Uint16Array',\n 'Int32Array',\n 'Uint32Array',\n 'Float32Array',\n 'Float64Array',\n 'BigInt64Array',\n 'BigUint64Array'\n]\n\n/**\n * @param {any} value\n * @returns {string}\n */\nexport function is (value) {\n if (value === null) {\n return 'null'\n }\n if (value === undefined) {\n return 'undefined'\n }\n if (value === true || value === false) {\n return 'boolean'\n }\n const typeOf = typeof value\n if (typeofs.includes(typeOf)) {\n return typeOf\n }\n /* c8 ignore next 4 */\n // not going to bother testing this, it's not going to be valid anyway\n if (typeOf === 'function') {\n return 'Function'\n }\n if (Array.isArray(value)) {\n return 'Array'\n }\n if (isBuffer(value)) {\n return 'Buffer'\n }\n const objectType = getObjectType(value)\n if (objectType) {\n return objectType\n }\n /* c8 ignore next */\n return 'Object'\n}\n\n/**\n * @param {any} value\n * @returns {boolean}\n */\nfunction isBuffer (value) {\n return value && value.constructor && value.constructor.isBuffer && value.constructor.isBuffer.call(null, value)\n}\n\n/**\n * @param {any} value\n * @returns {string|undefined}\n */\nfunction getObjectType (value) {\n const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)\n if (objectTypeNames.includes(objectTypeName)) {\n return objectTypeName\n }\n /* c8 ignore next */\n return undefined\n}\n", "class Type {\n /**\n * @param {number} major\n * @param {string} name\n * @param {boolean} terminal\n */\n constructor (major, name, terminal) {\n this.major = major\n this.majorEncoded = major << 5\n this.name = name\n this.terminal = terminal\n }\n\n /* c8 ignore next 3 */\n toString () {\n return `Type[${this.major}].${this.name}`\n }\n\n /**\n * @param {Type} typ\n * @returns {number}\n */\n compare (typ) {\n /* c8 ignore next 1 */\n return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0\n }\n}\n\n// convert to static fields when better supported\nType.uint = new Type(0, 'uint', true)\nType.negint = new Type(1, 'negint', true)\nType.bytes = new Type(2, 'bytes', true)\nType.string = new Type(3, 'string', true)\nType.array = new Type(4, 'array', false)\nType.map = new Type(5, 'map', false)\nType.tag = new Type(6, 'tag', false) // terminal?\nType.float = new Type(7, 'float', true)\nType.false = new Type(7, 'false', true)\nType.true = new Type(7, 'true', true)\nType.null = new Type(7, 'null', true)\nType.undefined = new Type(7, 'undefined', true)\nType.break = new Type(7, 'break', true)\n// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)\n\nclass Token {\n /**\n * @param {Type} type\n * @param {any} [value]\n * @param {number} [encodedLength]\n */\n constructor (type, value, encodedLength) {\n this.type = type\n this.value = value\n this.encodedLength = encodedLength\n /** @type {Uint8Array|undefined} */\n this.encodedBytes = undefined\n /** @type {Uint8Array|undefined} */\n this.byteValue = undefined\n }\n\n /* c8 ignore next 3 */\n toString () {\n return `Token[${this.type}].${this.value}`\n }\n}\n\nexport { Type, Token }\n", "// Use Uint8Array directly in the browser, use Buffer in Node.js but don't\n// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill\n\n// @ts-ignore\nexport const useBuffer = globalThis.process &&\n // @ts-ignore\n !globalThis.process.browser &&\n // @ts-ignore\n globalThis.Buffer &&\n // @ts-ignore\n typeof globalThis.Buffer.isBuffer === 'function'\n\nconst textDecoder = new TextDecoder()\nconst textEncoder = new TextEncoder()\n\n/**\n * @param {Uint8Array} buf\n * @returns {boolean}\n */\nfunction isBuffer (buf) {\n // @ts-ignore\n return useBuffer && globalThis.Buffer.isBuffer(buf)\n}\n\n/**\n * @param {Uint8Array|number[]} buf\n * @returns {Uint8Array}\n */\nexport function asU8A (buf) {\n /* c8 ignore next */\n if (!(buf instanceof Uint8Array)) {\n return Uint8Array.from(buf)\n }\n return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf\n}\n\nexport const toString = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n (bytes, start, end) => {\n return end - start > 64\n ? // eslint-disable-line operator-linebreak\n // @ts-ignore\n globalThis.Buffer.from(bytes.subarray(start, end)).toString('utf8')\n : utf8Slice(bytes, start, end)\n }\n /* c8 ignore next 11 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n (bytes, start, end) => {\n return end - start > 64\n ? textDecoder.decode(bytes.subarray(start, end))\n : utf8Slice(bytes, start, end)\n }\n\nexport const fromString = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {string} string\n */\n (string) => {\n return string.length > 64\n ? // eslint-disable-line operator-linebreak\n // @ts-ignore\n globalThis.Buffer.from(string)\n : utf8ToBytes(string)\n }\n /* c8 ignore next 7 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {string} string\n */\n (string) => {\n return string.length > 64 ? textEncoder.encode(string) : utf8ToBytes(string)\n }\n\n/**\n * Buffer variant not fast enough for what we need\n * @param {number[]} arr\n * @returns {Uint8Array}\n */\nexport const fromArray = (arr) => {\n return Uint8Array.from(arr)\n}\n\nexport const slice = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n (bytes, start, end) => {\n if (isBuffer(bytes)) {\n return new Uint8Array(bytes.subarray(start, end))\n }\n return bytes.slice(start, end)\n }\n /* c8 ignore next 9 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n (bytes, start, end) => {\n return bytes.slice(start, end)\n }\n\nexport const concat = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array[]} chunks\n * @param {number} length\n * @returns {Uint8Array}\n */\n (chunks, length) => {\n // might get a stray plain Array here\n /* c8 ignore next 1 */\n chunks = chunks.map((c) => c instanceof Uint8Array\n ? c\n // this case is occasionally missed during test runs so becomes coverage-flaky\n /* c8 ignore next 4 */\n : // eslint-disable-line operator-linebreak\n // @ts-ignore\n globalThis.Buffer.from(c))\n // @ts-ignore\n return asU8A(globalThis.Buffer.concat(chunks, length))\n }\n /* c8 ignore next 19 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array[]} chunks\n * @param {number} length\n * @returns {Uint8Array}\n */\n (chunks, length) => {\n const out = new Uint8Array(length)\n let off = 0\n for (let b of chunks) {\n if (off + b.length > out.length) {\n // final chunk that's bigger than we need\n b = b.subarray(0, out.length - off)\n }\n out.set(b, off)\n off += b.length\n }\n return out\n }\n\nexport const alloc = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {number} size\n * @returns {Uint8Array}\n */\n (size) => {\n // we always write over the contents we expose so this should be safe\n // @ts-ignore\n return globalThis.Buffer.allocUnsafe(size)\n }\n /* c8 ignore next 8 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {number} size\n * @returns {Uint8Array}\n */\n (size) => {\n return new Uint8Array(size)\n }\n\nexport const toHex = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} d\n * @returns {string}\n */\n (d) => {\n if (typeof d === 'string') {\n return d\n }\n // @ts-ignore\n return globalThis.Buffer.from(toBytes(d)).toString('hex')\n }\n /* c8 ignore next 12 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} d\n * @returns {string}\n */\n (d) => {\n if (typeof d === 'string') {\n return d\n }\n // @ts-ignore not smart enough to figure this out\n return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')\n }\n\nexport const fromHex = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {string|Uint8Array} hex\n * @returns {Uint8Array}\n */\n (hex) => {\n if (hex instanceof Uint8Array) {\n return hex\n }\n // @ts-ignore\n return globalThis.Buffer.from(hex, 'hex')\n }\n /* c8 ignore next 17 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {string|Uint8Array} hex\n * @returns {Uint8Array}\n */\n (hex) => {\n if (hex instanceof Uint8Array) {\n return hex\n }\n if (!hex.length) {\n return new Uint8Array(0)\n }\n return new Uint8Array(hex.split('')\n .map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')\n .filter(Boolean)\n .map((/** @type {string} */ e) => parseInt(e, 16)))\n }\n\n/**\n * @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj\n * @returns {Uint8Array}\n */\nfunction toBytes (obj) {\n if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {\n return obj\n }\n if (obj instanceof ArrayBuffer) {\n return new Uint8Array(obj)\n }\n if (ArrayBuffer.isView(obj)) {\n return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)\n }\n /* c8 ignore next */\n throw new Error('Unknown type, must be binary type')\n}\n\n/**\n * @param {Uint8Array} b1\n * @param {Uint8Array} b2\n * @returns {number}\n */\nexport function compare (b1, b2) {\n /* c8 ignore next 5 */\n if (isBuffer(b1) && isBuffer(b2)) {\n // probably not possible to get here in the current API\n // @ts-ignore Buffer\n return b1.compare(b2)\n }\n for (let i = 0; i < b1.length; i++) {\n if (b1[i] === b2[i]) {\n continue\n }\n return b1[i] < b2[i] ? -1 : 1\n } /* c8 ignore next 3 */\n return 0\n}\n\n// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143\n// Licensed Apache-2.0.\n\n/**\n * @param {string} str\n * @returns {number[]}\n */\nfunction utf8ToBytes (str) {\n const out = []\n let p = 0\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i)\n if (c < 128) {\n out[p++] = c\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192\n out[p++] = (c & 63) | 128\n } else if (\n ((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&\n ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {\n // Surrogate Pair\n c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)\n out[p++] = (c >> 18) | 240\n out[p++] = ((c >> 12) & 63) | 128\n out[p++] = ((c >> 6) & 63) | 128\n out[p++] = (c & 63) | 128\n } else {\n out[p++] = (c >> 12) | 224\n out[p++] = ((c >> 6) & 63) | 128\n out[p++] = (c & 63) | 128\n }\n }\n return out\n}\n\n// The below code is mostly taken from https://github.com/feross/buffer\n// Licensed MIT. Copyright (c) Feross Aboukhadijeh\n\n/**\n * @param {Uint8Array} buf\n * @param {number} offset\n * @param {number} end\n * @returns {string}\n */\nfunction utf8Slice (buf, offset, end) {\n const res = []\n\n while (offset < end) {\n const firstByte = buf[offset]\n let codePoint = null\n let bytesPerSequence = (firstByte > 0xef) ? 4 : (firstByte > 0xdf) ? 3 : (firstByte > 0xbf) ? 2 : 1\n\n if (offset + bytesPerSequence <= end) {\n let secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[offset + 1]\n if ((secondByte & 0xc0) === 0x80) {\n tempCodePoint = (firstByte & 0x1f) << 0x6 | (secondByte & 0x3f)\n if (tempCodePoint > 0x7f) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[offset + 1]\n thirdByte = buf[offset + 2]\n if ((secondByte & 0xc0) === 0x80 && (thirdByte & 0xc0) === 0x80) {\n tempCodePoint = (firstByte & 0xf) << 0xc | (secondByte & 0x3f) << 0x6 | (thirdByte & 0x3f)\n /* c8 ignore next 3 */\n if (tempCodePoint > 0x7ff && (tempCodePoint < 0xd800 || tempCodePoint > 0xdfff)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[offset + 1]\n thirdByte = buf[offset + 2]\n fourthByte = buf[offset + 3]\n if ((secondByte & 0xc0) === 0x80 && (thirdByte & 0xc0) === 0x80 && (fourthByte & 0xc0) === 0x80) {\n tempCodePoint = (firstByte & 0xf) << 0x12 | (secondByte & 0x3f) << 0xc | (thirdByte & 0x3f) << 0x6 | (fourthByte & 0x3f)\n if (tempCodePoint > 0xffff && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n /* c8 ignore next 5 */\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xfffd\n bytesPerSequence = 1\n } else if (codePoint > 0xffff) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3ff | 0xd800)\n codePoint = 0xdc00 | codePoint & 0x3ff\n }\n\n res.push(codePoint)\n offset += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nconst MAX_ARGUMENTS_LENGTH = 0x1000\n\n/**\n * @param {number[]} codePoints\n * @returns {string}\n */\nexport function decodeCodePointsArray (codePoints) {\n const len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n /* c8 ignore next 10 */\n // Decode in chunks to avoid \"call stack size exceeded\".\n let res = ''\n let i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n", "/**\n * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for\n * writing rather than reading.\n * A Bl object accepts set() operations for individual bytes and copyTo() for\n * inserting byte arrays. These write operations don't automatically increment\n * the internal cursor so its \"length\" won't be changed. Instead, increment()\n * must be called to extend its length to cover the inserted data.\n * The toBytes() call will convert all internal memory to a single Uint8Array of\n * the correct length, truncating any data that is stored but hasn't been\n * included by an increment().\n * get() can retrieve a single byte.\n * All operations (except toBytes()) take an \"offset\" argument that will perform\n * the write at the offset _from the current cursor_. For most operations this\n * will be `0` to write at the current cursor position but it can be ahead of\n * the current cursor. Negative offsets probably work but are untested.\n */\n\n// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39\nimport { alloc, concat, slice } from './byte-utils.js'\n\n// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists\n// for perf reasons. Consider better approaches to this or removing it entirely, it is quite\n// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.\n\nconst defaultChunkSize = 256\n\nexport class Bl {\n /**\n * @param {number} [chunkSize]\n */\n constructor (chunkSize = defaultChunkSize) {\n this.chunkSize = chunkSize\n /** @type {number} */\n this.cursor = 0\n /** @type {number} */\n this.maxCursor = -1\n /** @type {(Uint8Array|number[])[]} */\n this.chunks = []\n // keep the first chunk around if we can to save allocations for future encodes\n /** @type {Uint8Array|number[]|null} */\n this._initReuseChunk = null\n }\n\n reset () {\n this.cursor = 0\n this.maxCursor = -1\n if (this.chunks.length) {\n this.chunks = []\n }\n if (this._initReuseChunk !== null) {\n this.chunks.push(this._initReuseChunk)\n this.maxCursor = this._initReuseChunk.length - 1\n }\n }\n\n /**\n * @param {Uint8Array|number[]} bytes\n */\n push (bytes) {\n let topChunk = this.chunks[this.chunks.length - 1]\n const newMax = this.cursor + bytes.length\n if (newMax <= this.maxCursor + 1) {\n // we have at least one chunk and we can fit these bytes into that chunk\n const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1\n // @ts-ignore\n topChunk.set(bytes, chunkPos)\n } else {\n // can't fit it in\n if (topChunk) {\n // trip the last chunk to `cursor` if we need to\n const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1\n if (chunkPos < topChunk.length) {\n // @ts-ignore\n this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)\n this.maxCursor = this.cursor - 1\n }\n }\n if (bytes.length < 64 && bytes.length < this.chunkSize) {\n // make a new chunk and copy the new one into it\n topChunk = alloc(this.chunkSize)\n this.chunks.push(topChunk)\n this.maxCursor += topChunk.length\n if (this._initReuseChunk === null) {\n this._initReuseChunk = topChunk\n }\n // @ts-ignore\n topChunk.set(bytes, 0)\n } else {\n // push the new bytes in as its own chunk\n this.chunks.push(bytes)\n this.maxCursor += bytes.length\n }\n }\n this.cursor += bytes.length\n }\n\n /**\n * @param {boolean} [reset]\n * @returns {Uint8Array}\n */\n toBytes (reset = false) {\n let byts\n if (this.chunks.length === 1) {\n const chunk = this.chunks[0]\n if (reset && this.cursor > chunk.length / 2) {\n /* c8 ignore next 2 */\n // @ts-ignore\n byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)\n this._initReuseChunk = null\n this.chunks = []\n } else {\n // @ts-ignore\n byts = slice(chunk, 0, this.cursor)\n }\n } else {\n // @ts-ignore\n byts = concat(this.chunks, this.cursor)\n }\n if (reset) {\n this.reset()\n }\n return byts\n }\n}\n", "const decodeErrPrefix = 'CBOR decode error:'\nconst encodeErrPrefix = 'CBOR encode error:'\n\nconst uintMinorPrefixBytes = []\nuintMinorPrefixBytes[23] = 1\nuintMinorPrefixBytes[24] = 2\nuintMinorPrefixBytes[25] = 3\nuintMinorPrefixBytes[26] = 5\nuintMinorPrefixBytes[27] = 9\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} need\n */\nfunction assertEnoughData (data, pos, need) {\n if (data.length - pos < need) {\n throw new Error(`${decodeErrPrefix} not enough data for type`)\n }\n}\n\nexport {\n decodeErrPrefix,\n encodeErrPrefix,\n uintMinorPrefixBytes,\n assertEnoughData\n}\n", "/* globals BigInt */\n\nimport { Token, Type } from './token.js'\nimport { decodeErrPrefix, assertEnoughData } from './common.js'\n\nexport const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint8 (data, offset, options) {\n assertEnoughData(data, offset, 1)\n const value = data[offset]\n if (options.strict === true && value < uintBoundaries[0]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint16 (data, offset, options) {\n assertEnoughData(data, offset, 2)\n const value = (data[offset] << 8) | data[offset + 1]\n if (options.strict === true && value < uintBoundaries[1]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint32 (data, offset, options) {\n assertEnoughData(data, offset, 4)\n const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]\n if (options.strict === true && value < uintBoundaries[2]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number|bigint}\n */\nexport function readUint64 (data, offset, options) {\n // assume BigInt, convert back to Number if within safe range\n assertEnoughData(data, offset, 8)\n const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]\n const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]\n const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)\n if (options.strict === true && value < uintBoundaries[3]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n if (value <= Number.MAX_SAFE_INTEGER) {\n return Number(value)\n }\n if (options.allowBigInt === true) {\n return value\n }\n throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)\n}\n\n/* not required thanks to quick[] list\nconst oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))\nexport function decodeUintCompact (data, pos, minor, options) {\n return oneByteTokens[minor]\n}\n*/\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint8 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint16 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint32 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint32(data, pos + 1, options), 5)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint64 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint64(data, pos + 1, options), 9)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeUint (buf, token) {\n return encodeUintValue(buf, 0, token.value)\n}\n\n/**\n * @param {Bl} buf\n * @param {number} major\n * @param {number|bigint} uint\n */\nexport function encodeUintValue (buf, major, uint) {\n if (uint < uintBoundaries[0]) {\n const nuint = Number(uint)\n // pack into one byte, minor=0, additional=value\n buf.push([major | nuint])\n } else if (uint < uintBoundaries[1]) {\n const nuint = Number(uint)\n // pack into two byte, minor=0, additional=24\n buf.push([major | 24, nuint])\n } else if (uint < uintBoundaries[2]) {\n const nuint = Number(uint)\n // pack into three byte, minor=0, additional=25\n buf.push([major | 25, nuint >>> 8, nuint & 0xff])\n } else if (uint < uintBoundaries[3]) {\n const nuint = Number(uint)\n // pack into five byte, minor=0, additional=26\n buf.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])\n } else {\n const buint = BigInt(uint)\n if (buint < uintBoundaries[4]) {\n // pack into nine byte, minor=0, additional=27\n const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]\n // simulate bitwise above 32 bits\n let lo = Number(buint & BigInt(0xffffffff))\n let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))\n set[8] = lo & 0xff\n lo = lo >> 8\n set[7] = lo & 0xff\n lo = lo >> 8\n set[6] = lo & 0xff\n lo = lo >> 8\n set[5] = lo & 0xff\n set[4] = hi & 0xff\n hi = hi >> 8\n set[3] = hi & 0xff\n hi = hi >> 8\n set[2] = hi & 0xff\n hi = hi >> 8\n set[1] = hi & 0xff\n buf.push(set)\n } else {\n throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`)\n }\n }\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeUint.encodedSize = function encodedSize (token) {\n return encodeUintValue.encodedSize(token.value)\n}\n\n/**\n * @param {number} uint\n * @returns {number}\n */\nencodeUintValue.encodedSize = function encodedSize (uint) {\n if (uint < uintBoundaries[0]) {\n return 1\n }\n if (uint < uintBoundaries[1]) {\n return 2\n }\n if (uint < uintBoundaries[2]) {\n return 3\n }\n if (uint < uintBoundaries[3]) {\n return 5\n }\n return 9\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeUint.compareTokens = function compareTokens (tok1, tok2) {\n return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : /* c8 ignore next */ 0\n}\n", "/* eslint-env es2020 */\n\nimport { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint8 (data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint16 (data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint32 (data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5)\n}\n\nconst neg1b = BigInt(-1)\nconst pos1b = BigInt(1)\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint64 (data, pos, _minor, options) {\n const int = uint.readUint64(data, pos + 1, options)\n if (typeof int !== 'bigint') {\n const value = -1 - int\n if (value >= Number.MIN_SAFE_INTEGER) {\n return new Token(Type.negint, value, 9)\n }\n }\n if (options.allowBigInt !== true) {\n throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)\n }\n return new Token(Type.negint, neg1b - BigInt(int), 9)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeNegint (buf, token) {\n const negint = token.value\n const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))\n uint.encodeUintValue(buf, token.type.majorEncoded, unsigned)\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeNegint.encodedSize = function encodedSize (token) {\n const negint = token.value\n const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))\n /* c8 ignore next 4 */\n // handled by quickEncode, we shouldn't get here but it's included for completeness\n if (unsigned < uint.uintBoundaries[0]) {\n return 1\n }\n if (unsigned < uint.uintBoundaries[1]) {\n return 2\n }\n if (unsigned < uint.uintBoundaries[2]) {\n return 3\n }\n if (unsigned < uint.uintBoundaries[3]) {\n return 5\n }\n return 9\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeNegint.compareTokens = function compareTokens (tok1, tok2) {\n // opposite of the uint comparison since we store the uint version in bytes\n return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : /* c8 ignore next */ 0\n}\n", "import { Token, Type } from './token.js'\nimport { assertEnoughData, decodeErrPrefix } from './common.js'\nimport * as uint from './0uint.js'\nimport { compare, fromString, slice } from './byte-utils.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (data, pos, prefix, length) {\n assertEnoughData(data, pos, prefix + length)\n const buf = slice(data, pos + prefix, pos + prefix + length)\n return new Token(Type.bytes, buf, prefix + length)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeBytesCompact (data, pos, minor, _options) {\n return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`)\n }\n return toToken(data, pos, 9, l)\n}\n\n/**\n * `encodedBytes` allows for caching when we do a byte version of a string\n * for key sorting purposes\n * @param {Token} token\n * @returns {Uint8Array}\n */\nfunction tokenBytes (token) {\n if (token.encodedBytes === undefined) {\n token.encodedBytes = token.type === Type.string ? fromString(token.value) : token.value\n }\n // @ts-ignore c'mon\n return token.encodedBytes\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeBytes (buf, token) {\n const bytes = tokenBytes(token)\n uint.encodeUintValue(buf, token.type.majorEncoded, bytes.length)\n buf.push(bytes)\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeBytes.encodedSize = function encodedSize (token) {\n const bytes = tokenBytes(token)\n return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeBytes.compareTokens = function compareTokens (tok1, tok2) {\n return compareBytes(tokenBytes(tok1), tokenBytes(tok2))\n}\n\n/**\n * @param {Uint8Array} b1\n * @param {Uint8Array} b2\n * @returns {number}\n */\nexport function compareBytes (b1, b2) {\n return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2)\n}\n", "import { Token, Type } from './token.js'\nimport { assertEnoughData, decodeErrPrefix } from './common.js'\nimport * as uint from './0uint.js'\nimport { encodeBytes } from './2bytes.js'\nimport { toString, slice } from './byte-utils.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} prefix\n * @param {number} length\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nfunction toToken (data, pos, prefix, length, options) {\n const totLength = prefix + length\n assertEnoughData(data, pos, totLength)\n const tok = new Token(Type.string, toString(data, pos + prefix, pos + totLength), totLength)\n if (options.retainStringBytes === true) {\n tok.byteValue = slice(data, pos + prefix, pos + totLength)\n }\n return tok\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeStringCompact (data, pos, minor, options) {\n return toToken(data, pos, 1, minor, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options)\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`)\n }\n return toToken(data, pos, 9, l, options)\n}\n\nexport const encodeString = encodeBytes\n", "import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (_data, _pos, prefix, length) {\n return new Token(Type.array, length, prefix)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeArrayCompact (data, pos, minor, _options) {\n return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`)\n }\n return toToken(data, pos, 9, l)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArrayIndefinite (data, pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n }\n return toToken(data, pos, 1, Infinity)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeArray (buf, token) {\n uint.encodeUintValue(buf, Type.array.majorEncoded, token.value)\n}\n\n// using an array as a map key, are you sure about this? we can only sort\n// by map length here, it's up to the encoder to decide to look deeper\nencodeArray.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeArray.encodedSize = function encodedSize (token) {\n return uint.encodeUintValue.encodedSize(token.value)\n}\n", "import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (_data, _pos, prefix, length) {\n return new Token(Type.map, length, prefix)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeMapCompact (data, pos, minor, _options) {\n return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`)\n }\n return toToken(data, pos, 9, l)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMapIndefinite (data, pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n }\n return toToken(data, pos, 1, Infinity)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeMap (buf, token) {\n uint.encodeUintValue(buf, Type.map.majorEncoded, token.value)\n}\n\n// using a map as a map key, are you sure about this? we can only sort\n// by map length here, it's up to the encoder to decide to look deeper\nencodeMap.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeMap.encodedSize = function encodedSize (token) {\n return uint.encodeUintValue.encodedSize(token.value)\n}\n", "import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeTagCompact (_data, _pos, minor, _options) {\n return new Token(Type.tag, minor, 1)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag8 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag16 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag32 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag64 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeTag (buf, token) {\n uint.encodeUintValue(buf, Type.tag.majorEncoded, token.value)\n}\n\nencodeTag.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeTag.encodedSize = function encodedSize (token) {\n return uint.encodeUintValue.encodedSize(token.value)\n}\n", "// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer\n// where possible\n\nimport { Token, Type } from './token.js'\nimport { decodeErrPrefix } from './common.js'\nimport { encodeUint } from './0uint.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n * @typedef {import('../interface').EncodeOptions} EncodeOptions\n */\n\nconst MINOR_FALSE = 20\nconst MINOR_TRUE = 21\nconst MINOR_NULL = 22\nconst MINOR_UNDEFINED = 23\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUndefined (_data, _pos, _minor, options) {\n if (options.allowUndefined === false) {\n throw new Error(`${decodeErrPrefix} undefined values are not supported`)\n } else if (options.coerceUndefinedToNull === true) {\n return new Token(Type.null, null, 1)\n }\n return new Token(Type.undefined, undefined, 1)\n}\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBreak (_data, _pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n }\n return new Token(Type.break, undefined, 1)\n}\n\n/**\n * @param {number} value\n * @param {number} bytes\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nfunction createToken (value, bytes, options) {\n if (options) {\n if (options.allowNaN === false && Number.isNaN(value)) {\n throw new Error(`${decodeErrPrefix} NaN values are not supported`)\n }\n if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {\n throw new Error(`${decodeErrPrefix} Infinity values are not supported`)\n }\n }\n return new Token(Type.float, value, bytes)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat16 (data, pos, _minor, options) {\n return createToken(readFloat16(data, pos + 1), 3, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat32 (data, pos, _minor, options) {\n return createToken(readFloat32(data, pos + 1), 5, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat64 (data, pos, _minor, options) {\n return createToken(readFloat64(data, pos + 1), 9, options)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n * @param {EncodeOptions} options\n */\nexport function encodeFloat (buf, token, options) {\n const float = token.value\n\n if (float === false) {\n buf.push([Type.float.majorEncoded | MINOR_FALSE])\n } else if (float === true) {\n buf.push([Type.float.majorEncoded | MINOR_TRUE])\n } else if (float === null) {\n buf.push([Type.float.majorEncoded | MINOR_NULL])\n } else if (float === undefined) {\n buf.push([Type.float.majorEncoded | MINOR_UNDEFINED])\n } else {\n let decoded\n let success = false\n if (!options || options.float64 !== true) {\n encodeFloat16(float)\n decoded = readFloat16(ui8a, 1)\n if (float === decoded || Number.isNaN(float)) {\n ui8a[0] = 0xf9\n buf.push(ui8a.slice(0, 3))\n success = true\n } else {\n encodeFloat32(float)\n decoded = readFloat32(ui8a, 1)\n if (float === decoded) {\n ui8a[0] = 0xfa\n buf.push(ui8a.slice(0, 5))\n success = true\n }\n }\n }\n if (!success) {\n encodeFloat64(float)\n decoded = readFloat64(ui8a, 1)\n ui8a[0] = 0xfb\n buf.push(ui8a.slice(0, 9))\n }\n }\n}\n\n/**\n * @param {Token} token\n * @param {EncodeOptions} options\n * @returns {number}\n */\nencodeFloat.encodedSize = function encodedSize (token, options) {\n const float = token.value\n\n if (float === false || float === true || float === null || float === undefined) {\n return 1\n }\n\n if (!options || options.float64 !== true) {\n encodeFloat16(float)\n let decoded = readFloat16(ui8a, 1)\n if (float === decoded || Number.isNaN(float)) {\n return 3\n }\n encodeFloat32(float)\n decoded = readFloat32(ui8a, 1)\n if (float === decoded) {\n return 5\n }\n }\n return 9\n}\n\nconst buffer = new ArrayBuffer(9)\nconst dataView = new DataView(buffer, 1)\nconst ui8a = new Uint8Array(buffer, 0)\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat16 (inp) {\n if (inp === Infinity) {\n dataView.setUint16(0, 0x7c00, false)\n } else if (inp === -Infinity) {\n dataView.setUint16(0, 0xfc00, false)\n } else if (Number.isNaN(inp)) {\n dataView.setUint16(0, 0x7e00, false)\n } else {\n dataView.setFloat32(0, inp)\n const valu32 = dataView.getUint32(0)\n const exponent = (valu32 & 0x7f800000) >> 23\n const mantissa = valu32 & 0x7fffff\n\n /* c8 ignore next 6 */\n if (exponent === 0xff) {\n // too big, Infinity, but this should be hard (impossible?) to trigger\n dataView.setUint16(0, 0x7c00, false)\n } else if (exponent === 0x00) {\n // 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int\n dataView.setUint16(0, ((inp & 0x80000000) >> 16) | (mantissa >> 13), false)\n } else { // standard numbers\n // chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127\n const logicalExponent = exponent - 127\n // Now we know that 2^exponent <= 0 logically\n /* c8 ignore next 6 */\n if (logicalExponent < -24) {\n /* No unambiguous representation exists, this float is not a half float\n and is too small to be represented using a half, round off to zero.\n Consistent with the reference implementation. */\n // should be difficult (impossible?) to get here in JS\n dataView.setUint16(0, 0)\n } else if (logicalExponent < -14) {\n /* Offset the remaining decimal places by shifting the significand, the\n value is lost. This is an implementation decision that works around the\n absence of standard half-float in the language. */\n dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)\n } else {\n dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)\n }\n }\n }\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat16 (ui8a, pos) {\n if (ui8a.length - pos < 2) {\n throw new Error(`${decodeErrPrefix} not enough data for float16`)\n }\n\n const half = (ui8a[pos] << 8) + ui8a[pos + 1]\n if (half === 0x7c00) {\n return Infinity\n }\n if (half === 0xfc00) {\n return -Infinity\n }\n if (half === 0x7e00) {\n return NaN\n }\n const exp = (half >> 10) & 0x1f\n const mant = half & 0x3ff\n let val\n if (exp === 0) {\n val = mant * (2 ** -24)\n } else if (exp !== 31) {\n val = (mant + 1024) * (2 ** (exp - 25))\n /* c8 ignore next 4 */\n } else {\n // may not be possible to get here\n val = mant === 0 ? Infinity : NaN\n }\n return (half & 0x8000) ? -val : val\n}\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat32 (inp) {\n dataView.setFloat32(0, inp, false)\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat32 (ui8a, pos) {\n if (ui8a.length - pos < 4) {\n throw new Error(`${decodeErrPrefix} not enough data for float32`)\n }\n const offset = (ui8a.byteOffset || 0) + pos\n return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)\n}\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat64 (inp) {\n dataView.setFloat64(0, inp, false)\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat64 (ui8a, pos) {\n if (ui8a.length - pos < 8) {\n throw new Error(`${decodeErrPrefix} not enough data for float64`)\n }\n const offset = (ui8a.byteOffset || 0) + pos\n return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)\n}\n\n/**\n * @param {Token} _tok1\n * @param {Token} _tok2\n * @returns {number}\n */\nencodeFloat.compareTokens = encodeUint.compareTokens\n/*\nencodeFloat.compareTokens = function compareTokens (_tok1, _tok2) {\n return _tok1\n throw new Error(`${encodeErrPrefix} cannot use floats as map keys`)\n}\n*/\n", "import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport * as negint from './1negint.js'\nimport * as bytes from './2bytes.js'\nimport * as string from './3string.js'\nimport * as array from './4array.js'\nimport * as map from './5map.js'\nimport * as tag from './6tag.js'\nimport * as float from './7float.js'\nimport { decodeErrPrefix } from './common.js'\nimport { fromArray } from './byte-utils.js'\n\n/**\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n */\nfunction invalidMinor (data, pos, minor) {\n throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)\n}\n\n/**\n * @param {string} msg\n * @returns {()=>any}\n */\nfunction errorer (msg) {\n return () => { throw new Error(`${decodeErrPrefix} ${msg}`) }\n}\n\n/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */\nexport const jump = []\n\n// unsigned integer, 0x00..0x17 (0..23)\nfor (let i = 0; i <= 0x17; i++) {\n jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]\n}\njump[0x18] = uint.decodeUint8 // unsigned integer, one-byte uint8_t follows\njump[0x19] = uint.decodeUint16 // unsigned integer, two-byte uint16_t follows\njump[0x1a] = uint.decodeUint32 // unsigned integer, four-byte uint32_t follows\njump[0x1b] = uint.decodeUint64 // unsigned integer, eight-byte uint64_t follows\njump[0x1c] = invalidMinor\njump[0x1d] = invalidMinor\njump[0x1e] = invalidMinor\njump[0x1f] = invalidMinor\n// negative integer, -1-0x00..-1-0x17 (-1..-24)\nfor (let i = 0x20; i <= 0x37; i++) {\n jump[i] = invalidMinor // negintDecode, handled by quick[]\n}\njump[0x38] = negint.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows\njump[0x39] = negint.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows\njump[0x3a] = negint.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows\njump[0x3b] = negint.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows\njump[0x3c] = invalidMinor\njump[0x3d] = invalidMinor\njump[0x3e] = invalidMinor\njump[0x3f] = invalidMinor\n// byte string, 0x00..0x17 bytes follow\nfor (let i = 0x40; i <= 0x57; i++) {\n jump[i] = bytes.decodeBytesCompact\n}\njump[0x58] = bytes.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow\njump[0x59] = bytes.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow\njump[0x5a] = bytes.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow\njump[0x5b] = bytes.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow\njump[0x5c] = invalidMinor\njump[0x5d] = invalidMinor\njump[0x5e] = invalidMinor\njump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by \"break\"\n// UTF-8 string 0x00..0x17 bytes follow\nfor (let i = 0x60; i <= 0x77; i++) {\n jump[i] = string.decodeStringCompact\n}\njump[0x78] = string.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow\njump[0x79] = string.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow\njump[0x7a] = string.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow\njump[0x7b] = string.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow\njump[0x7c] = invalidMinor\njump[0x7d] = invalidMinor\njump[0x7e] = invalidMinor\njump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by \"break\"\n// array, 0x00..0x17 data items follow\nfor (let i = 0x80; i <= 0x97; i++) {\n jump[i] = array.decodeArrayCompact\n}\njump[0x98] = array.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow\njump[0x99] = array.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow\njump[0x9a] = array.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow\njump[0x9b] = array.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow\njump[0x9c] = invalidMinor\njump[0x9d] = invalidMinor\njump[0x9e] = invalidMinor\njump[0x9f] = array.decodeArrayIndefinite // array, data items follow, terminated by \"break\"\n// map, 0x00..0x17 pairs of data items follow\nfor (let i = 0xa0; i <= 0xb7; i++) {\n jump[i] = map.decodeMapCompact\n}\njump[0xb8] = map.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow\njump[0xb9] = map.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow\njump[0xba] = map.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow\njump[0xbb] = map.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow\njump[0xbc] = invalidMinor\njump[0xbd] = invalidMinor\njump[0xbe] = invalidMinor\njump[0xbf] = map.decodeMapIndefinite // map, pairs of data items follow, terminated by \"break\"\n// tags\nfor (let i = 0xc0; i <= 0xd7; i++) {\n jump[i] = tag.decodeTagCompact\n}\njump[0xd8] = tag.decodeTag8\njump[0xd9] = tag.decodeTag16\njump[0xda] = tag.decodeTag32\njump[0xdb] = tag.decodeTag64\njump[0xdc] = invalidMinor\njump[0xdd] = invalidMinor\njump[0xde] = invalidMinor\njump[0xdf] = invalidMinor\n// 0xe0..0xf3 simple values, unsupported\nfor (let i = 0xe0; i <= 0xf3; i++) {\n jump[i] = errorer('simple values are not supported')\n}\njump[0xf4] = invalidMinor // false, handled by quick[]\njump[0xf5] = invalidMinor // true, handled by quick[]\njump[0xf6] = invalidMinor // null, handled by quick[]\njump[0xf7] = float.decodeUndefined // undefined\njump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported\njump[0xf9] = float.decodeFloat16 // half-precision float (two-byte IEEE 754)\njump[0xfa] = float.decodeFloat32 // single-precision float (four-byte IEEE 754)\njump[0xfb] = float.decodeFloat64 // double-precision float (eight-byte IEEE 754)\njump[0xfc] = invalidMinor\njump[0xfd] = invalidMinor\njump[0xfe] = invalidMinor\njump[0xff] = float.decodeBreak // \"break\" stop code\n\n/** @type {Token[]} */\nexport const quick = []\n// ints <24\nfor (let i = 0; i < 24; i++) {\n quick[i] = new Token(Type.uint, i, 1)\n}\n// negints >= -24\nfor (let i = -1; i >= -24; i--) {\n quick[31 - i] = new Token(Type.negint, i, 1)\n}\n// empty bytes\nquick[0x40] = new Token(Type.bytes, new Uint8Array(0), 1)\n// empty string\nquick[0x60] = new Token(Type.string, '', 1)\n// empty list\nquick[0x80] = new Token(Type.array, 0, 1)\n// empty map\nquick[0xa0] = new Token(Type.map, 0, 1)\n// false\nquick[0xf4] = new Token(Type.false, false, 1)\n// true\nquick[0xf5] = new Token(Type.true, true, 1)\n// null\nquick[0xf6] = new Token(Type.null, null, 1)\n\n/**\n * @param {Token} token\n * @returns {Uint8Array|undefined}\n */\nexport function quickEncodeToken (token) {\n switch (token.type) {\n case Type.false:\n return fromArray([0xf4])\n case Type.true:\n return fromArray([0xf5])\n case Type.null:\n return fromArray([0xf6])\n case Type.bytes:\n if (!token.value.length) {\n return fromArray([0x40])\n }\n return\n case Type.string:\n if (token.value === '') {\n return fromArray([0x60])\n }\n return\n case Type.array:\n if (token.value === 0) {\n return fromArray([0x80])\n }\n /* c8 ignore next 2 */\n // shouldn't be possible if this were called when there was only one token\n return\n case Type.map:\n if (token.value === 0) {\n return fromArray([0xa0])\n }\n /* c8 ignore next 2 */\n // shouldn't be possible if this were called when there was only one token\n return\n case Type.uint:\n if (token.value < 24) {\n return fromArray([Number(token.value)])\n }\n return\n case Type.negint:\n if (token.value >= -24) {\n return fromArray([31 - Number(token.value)])\n }\n }\n}\n", "import { is } from './is.js'\nimport { Token, Type } from './token.js'\nimport { Bl } from './bl.js'\nimport { encodeErrPrefix } from './common.js'\nimport { quickEncodeToken } from './jump.js'\nimport { asU8A } from './byte-utils.js'\n\nimport { encodeUint } from './0uint.js'\nimport { encodeNegint } from './1negint.js'\nimport { encodeBytes } from './2bytes.js'\nimport { encodeString } from './3string.js'\nimport { encodeArray } from './4array.js'\nimport { encodeMap } from './5map.js'\nimport { encodeTag } from './6tag.js'\nimport { encodeFloat } from './7float.js'\n\n/**\n * @typedef {import('../interface').EncodeOptions} EncodeOptions\n * @typedef {import('../interface').OptionalTypeEncoder} OptionalTypeEncoder\n * @typedef {import('../interface').Reference} Reference\n * @typedef {import('../interface').StrictTypeEncoder} StrictTypeEncoder\n * @typedef {import('../interface').TokenTypeEncoder} TokenTypeEncoder\n * @typedef {import('../interface').TokenOrNestedTokens} TokenOrNestedTokens\n */\n\n/** @type {EncodeOptions} */\nconst defaultEncodeOptions = {\n float64: false,\n mapSorter,\n quickEncodeToken\n}\n\n/** @returns {TokenTypeEncoder[]} */\nexport function makeCborEncoders () {\n const encoders = []\n encoders[Type.uint.major] = encodeUint\n encoders[Type.negint.major] = encodeNegint\n encoders[Type.bytes.major] = encodeBytes\n encoders[Type.string.major] = encodeString\n encoders[Type.array.major] = encodeArray\n encoders[Type.map.major] = encodeMap\n encoders[Type.tag.major] = encodeTag\n encoders[Type.float.major] = encodeFloat\n return encoders\n}\n\nconst cborEncoders = makeCborEncoders()\n\nconst buf = new Bl()\n\n/** @implements {Reference} */\nclass Ref {\n /**\n * @param {object|any[]} obj\n * @param {Reference|undefined} parent\n */\n constructor (obj, parent) {\n this.obj = obj\n this.parent = parent\n }\n\n /**\n * @param {object|any[]} obj\n * @returns {boolean}\n */\n includes (obj) {\n /** @type {Reference|undefined} */\n let p = this\n do {\n if (p.obj === obj) {\n return true\n }\n } while (p = p.parent) // eslint-disable-line\n return false\n }\n\n /**\n * @param {Reference|undefined} stack\n * @param {object|any[]} obj\n * @returns {Reference}\n */\n static createCheck (stack, obj) {\n if (stack && stack.includes(obj)) {\n throw new Error(`${encodeErrPrefix} object contains circular references`)\n }\n return new Ref(obj, stack)\n }\n}\n\nconst simpleTokens = {\n null: new Token(Type.null, null),\n undefined: new Token(Type.undefined, undefined),\n true: new Token(Type.true, true),\n false: new Token(Type.false, false),\n emptyArray: new Token(Type.array, 0),\n emptyMap: new Token(Type.map, 0)\n}\n\n/** @type {{[typeName: string]: StrictTypeEncoder}} */\nconst typeEncoders = {\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n number (obj, _typ, _options, _refStack) {\n if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {\n return new Token(Type.float, obj)\n } else if (obj >= 0) {\n return new Token(Type.uint, obj)\n } else {\n return new Token(Type.negint, obj)\n }\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n bigint (obj, _typ, _options, _refStack) {\n if (obj >= BigInt(0)) {\n return new Token(Type.uint, obj)\n } else {\n return new Token(Type.negint, obj)\n }\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n Uint8Array (obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, obj)\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n string (obj, _typ, _options, _refStack) {\n return new Token(Type.string, obj)\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n boolean (obj, _typ, _options, _refStack) {\n return obj ? simpleTokens.true : simpleTokens.false\n },\n\n /**\n * @param {any} _obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n null (_obj, _typ, _options, _refStack) {\n return simpleTokens.null\n },\n\n /**\n * @param {any} _obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n undefined (_obj, _typ, _options, _refStack) {\n return simpleTokens.undefined\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n ArrayBuffer (obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, new Uint8Array(obj))\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n DataView (obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} options\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\n Array (obj, _typ, options, refStack) {\n if (!obj.length) {\n if (options.addBreakTokens === true) {\n return [simpleTokens.emptyArray, new Token(Type.break)]\n }\n return simpleTokens.emptyArray\n }\n refStack = Ref.createCheck(refStack, obj)\n const entries = []\n let i = 0\n for (const e of obj) {\n entries[i++] = objectToTokens(e, options, refStack)\n }\n if (options.addBreakTokens) {\n return [new Token(Type.array, obj.length), entries, new Token(Type.break)]\n }\n return [new Token(Type.array, obj.length), entries]\n },\n\n /**\n * @param {any} obj\n * @param {string} typ\n * @param {EncodeOptions} options\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\n Object (obj, typ, options, refStack) {\n // could be an Object or a Map\n const isMap = typ !== 'Object'\n // it's slightly quicker to use Object.keys() than Object.entries()\n const keys = isMap ? obj.keys() : Object.keys(obj)\n const length = isMap ? obj.size : keys.length\n if (!length) {\n if (options.addBreakTokens === true) {\n return [simpleTokens.emptyMap, new Token(Type.break)]\n }\n return simpleTokens.emptyMap\n }\n refStack = Ref.createCheck(refStack, obj)\n /** @type {TokenOrNestedTokens[]} */\n const entries = []\n let i = 0\n for (const key of keys) {\n entries[i++] = [\n objectToTokens(key, options, refStack),\n objectToTokens(isMap ? obj.get(key) : obj[key], options, refStack)\n ]\n }\n sortMapEntries(entries, options)\n if (options.addBreakTokens) {\n return [new Token(Type.map, length), entries, new Token(Type.break)]\n }\n return [new Token(Type.map, length), entries]\n }\n}\n\ntypeEncoders.Map = typeEncoders.Object\ntypeEncoders.Buffer = typeEncoders.Uint8Array\nfor (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {\n typeEncoders[`${typ}Array`] = typeEncoders.DataView\n}\n\n/**\n * @param {any} obj\n * @param {EncodeOptions} [options]\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\nfunction objectToTokens (obj, options = {}, refStack) {\n const typ = is(obj)\n const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]\n if (typeof customTypeEncoder === 'function') {\n const tokens = customTypeEncoder(obj, typ, options, refStack)\n if (tokens != null) {\n return tokens\n }\n }\n const typeEncoder = typeEncoders[typ]\n if (!typeEncoder) {\n throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)\n }\n return typeEncoder(obj, typ, options, refStack)\n}\n\n/*\nCBOR key sorting is a mess.\n\nThe canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9\nincludes the wording:\n\n> The keys in every map must be sorted lowest value to highest.\n> Sorting is performed on the bytes of the representation of the key\n> data items without paying attention to the 3/5 bit splitting for\n> major types.\n> ...\n> * If two keys have different lengths, the shorter one sorts\n earlier;\n> * If two keys have the same length, the one with the lower value\n in (byte-wise) lexical order sorts earlier.\n\n1. It is not clear what \"bytes of the representation of the key\" means: is it\n the CBOR representation, or the binary representation of the object itself?\n Consider the int and uint difference here.\n2. It is not clear what \"without paying attention to\" means: do we include it\n and compare on that? Or do we omit the special prefix byte, (mostly) treating\n the key in its plain binary representation form.\n\nThe FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR\nwording and clarifies it according to their understanding.\nhttps://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding\n\n> The keys in every map must be sorted lowest value to highest. Sorting is\n> performed on the bytes of the representation of the key data items without\n> paying attention to the 3/5 bit splitting for major types. The sorting rules\n> are:\n> * If the major types are different, the one with the lower value in numerical\n> order sorts earlier.\n> * If two keys have different lengths, the shorter one sorts earlier;\n> * If two keys have the same length, the one with the lower value in\n> (byte-wise) lexical order sorts earlier.\n\nSome other implementations, such as borc, do a full encode then do a\nlength-first, byte-wise-second comparison:\nhttps://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358\nhttps://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151\n\nThis has the benefit of being able to easily handle arbitrary keys, including\ncomplex types (maps and arrays).\n\nWe'll opt for the FIDO approach, since it affords some efficies since we don't\nneed a full encode of each key to determine order and can defer to the types\nto determine how to most efficiently order their values (i.e. int and uint\nordering can be done on the numbers, no need for byte-wise, for example).\n\nRecommendation: stick to single key types or you'll get into trouble, and prefer\nstring keys because it's much simpler that way.\n*/\n\n/*\n(UPDATE, Dec 2020)\nhttps://tools.ietf.org/html/rfc8949 is the updated CBOR spec and clarifies some\nof the questions above with a new recommendation for sorting order being much\ncloser to what would be expected in other environments (i.e. no length-first\nweirdness).\nThis new sorting order is not yet implemented here but could be added as an\noption. \"Determinism\" (canonicity) is system dependent and it's difficult to\nchange existing systems that are built with existing expectations. So if a new\nordering is introduced here, the old needs to be kept as well with the user\nhaving the option.\n*/\n\n/**\n * @param {TokenOrNestedTokens[]} entries\n * @param {EncodeOptions} options\n */\nfunction sortMapEntries (entries, options) {\n if (options.mapSorter) {\n entries.sort(options.mapSorter)\n }\n}\n\n/**\n * @param {(Token|Token[])[]} e1\n * @param {(Token|Token[])[]} e2\n * @returns {number}\n */\nfunction mapSorter (e1, e2) {\n // the key position ([0]) could have a single token or an array\n // almost always it'll be a single token but complex key might get involved\n /* c8 ignore next 2 */\n const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]\n const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]\n\n // different key types\n if (keyToken1.type !== keyToken2.type) {\n return keyToken1.type.compare(keyToken2.type)\n }\n\n const major = keyToken1.type.major\n // TODO: handle case where cmp === 0 but there are more keyToken e. complex type)\n const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2)\n /* c8 ignore next 5 */\n if (tcmp === 0) {\n // duplicate key or complex type where the first token matched,\n // i.e. a map or array and we're only comparing the opening token\n console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')\n }\n return tcmp\n}\n\n/**\n * @param {Bl} buf\n * @param {TokenOrNestedTokens} tokens\n * @param {TokenTypeEncoder[]} encoders\n * @param {EncodeOptions} options\n */\nfunction tokensToEncoded (buf, tokens, encoders, options) {\n if (Array.isArray(tokens)) {\n for (const token of tokens) {\n tokensToEncoded(buf, token, encoders, options)\n }\n } else {\n encoders[tokens.type.major](buf, tokens, options)\n }\n}\n\n/**\n * @param {any} data\n * @param {TokenTypeEncoder[]} encoders\n * @param {EncodeOptions} options\n * @returns {Uint8Array}\n */\nfunction encodeCustom (data, encoders, options) {\n const tokens = objectToTokens(data, options)\n if (!Array.isArray(tokens) && options.quickEncodeToken) {\n const quickBytes = options.quickEncodeToken(tokens)\n if (quickBytes) {\n return quickBytes\n }\n const encoder = encoders[tokens.type.major]\n if (encoder.encodedSize) {\n const size = encoder.encodedSize(tokens, options)\n const buf = new Bl(size)\n encoder(buf, tokens, options)\n /* c8 ignore next 4 */\n // this would be a problem with encodedSize() functions\n if (buf.chunks.length !== 1) {\n throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)\n }\n return asU8A(buf.chunks[0])\n }\n }\n buf.reset()\n tokensToEncoded(buf, tokens, encoders, options)\n return buf.toBytes(true)\n}\n\n/**\n * @param {any} data\n * @param {EncodeOptions} [options]\n * @returns {Uint8Array}\n */\nfunction encode (data, options) {\n options = Object.assign({}, defaultEncodeOptions, options)\n return encodeCustom(data, cborEncoders, options)\n}\n\nexport { objectToTokens, encode, encodeCustom, Ref }\n", "import { decodeErrPrefix } from './common.js'\nimport { Type } from './token.js'\nimport { jump, quick } from './jump.js'\n\n/**\n * @typedef {import('./token.js').Token} Token\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n * @typedef {import('../interface').DecodeTokenizer} DecodeTokenizer\n */\n\nconst defaultDecodeOptions = {\n strict: false,\n allowIndefinite: true,\n allowUndefined: true,\n allowBigInt: true\n}\n\n/**\n * @implements {DecodeTokenizer}\n */\nclass Tokeniser {\n /**\n * @param {Uint8Array} data\n * @param {DecodeOptions} options\n */\n constructor (data, options = {}) {\n this._pos = 0\n this.data = data\n this.options = options\n }\n\n pos () {\n return this._pos\n }\n\n done () {\n return this._pos >= this.data.length\n }\n\n next () {\n const byt = this.data[this._pos]\n let token = quick[byt]\n if (token === undefined) {\n const decoder = jump[byt]\n /* c8 ignore next 4 */\n // if we're here then there's something wrong with our jump or quick lists!\n if (!decoder) {\n throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)\n }\n const minor = byt & 31\n token = decoder(this.data, this._pos, minor, this.options)\n }\n // @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)\n this._pos += token.encodedLength\n return token\n }\n}\n\nconst DONE = Symbol.for('DONE')\nconst BREAK = Symbol.for('BREAK')\n\n/**\n * @param {Token} token\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|BREAK|DONE}\n */\nfunction tokenToArray (token, tokeniser, options) {\n const arr = []\n for (let i = 0; i < token.value; i++) {\n const value = tokensToObject(tokeniser, options)\n if (value === BREAK) {\n if (token.value === Infinity) {\n // normal end to indefinite length array\n break\n }\n throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`)\n }\n if (value === DONE) {\n throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)\n }\n arr[i] = value\n }\n return arr\n}\n\n/**\n * @param {Token} token\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|BREAK|DONE}\n */\nfunction tokenToMap (token, tokeniser, options) {\n const useMaps = options.useMaps === true\n const obj = useMaps ? undefined : {}\n const m = useMaps ? new Map() : undefined\n for (let i = 0; i < token.value; i++) {\n const key = tokensToObject(tokeniser, options)\n if (key === BREAK) {\n if (token.value === Infinity) {\n // normal end to indefinite length map\n break\n }\n throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)\n }\n if (key === DONE) {\n throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)\n }\n if (useMaps !== true && typeof key !== 'string') {\n throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)\n }\n if (options.rejectDuplicateMapKeys === true) {\n // @ts-ignore\n if ((useMaps && m.has(key)) || (!useMaps && (key in obj))) {\n throw new Error(`${decodeErrPrefix} found repeat map key \"${key}\"`)\n }\n }\n const value = tokensToObject(tokeniser, options)\n if (value === DONE) {\n throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)\n }\n if (useMaps) {\n // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types\n m.set(key, value)\n } else {\n // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types\n obj[key] = value\n }\n }\n // @ts-ignore c'mon man\n return useMaps ? m : obj\n}\n\n/**\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|BREAK|DONE}\n */\nfunction tokensToObject (tokeniser, options) {\n // should we support array as an argument?\n // check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?\n if (tokeniser.done()) {\n return DONE\n }\n\n const token = tokeniser.next()\n\n if (token.type === Type.break) {\n return BREAK\n }\n\n if (token.type.terminal) {\n return token.value\n }\n\n if (token.type === Type.array) {\n return tokenToArray(token, tokeniser, options)\n }\n\n if (token.type === Type.map) {\n return tokenToMap(token, tokeniser, options)\n }\n\n if (token.type === Type.tag) {\n if (options.tags && typeof options.tags[token.value] === 'function') {\n const tagged = tokensToObject(tokeniser, options)\n return options.tags[token.value](tagged)\n }\n throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`)\n }\n /* c8 ignore next */\n throw new Error('unsupported')\n}\n\n/**\n * @param {Uint8Array} data\n * @param {DecodeOptions} [options]\n * @returns {[any, Uint8Array]}\n */\nfunction decodeFirst (data, options) {\n if (!(data instanceof Uint8Array)) {\n throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`)\n }\n options = Object.assign({}, defaultDecodeOptions, options)\n const tokeniser = options.tokenizer || new Tokeniser(data, options)\n const decoded = tokensToObject(tokeniser, options)\n if (decoded === DONE) {\n throw new Error(`${decodeErrPrefix} did not find any content to decode`)\n }\n if (decoded === BREAK) {\n throw new Error(`${decodeErrPrefix} got unexpected break`)\n }\n return [decoded, data.subarray(tokeniser.pos())]\n}\n\n/**\n * @param {Uint8Array} data\n * @param {DecodeOptions} [options]\n * @returns {any}\n */\nfunction decode (data, options) {\n const [decoded, remainder] = decodeFirst(data, options)\n if (remainder.length > 0) {\n throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`)\n }\n return decoded\n}\n\nexport { Tokeniser, tokensToObject, decode, decodeFirst }\n", "import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n", "export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) { return true }\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') { return o }\n if (o instanceof ArrayBuffer) { 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}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n", "/* 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) { throw new TypeError('Alphabet too long') }\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) { throw new TypeError(x + ' is ambiguous') }\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<number>} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\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) { throw new Error('Non-zero carry') }\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) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\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) { return }\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) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\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) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n", "import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\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<Base extends string, Prefix extends string> implements MultibaseEncoder<Prefix>, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase<Prefix> {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\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<Base extends string, Prefix extends string> implements MultibaseDecoder<Prefix>, UnibaseDecoder<Prefix>, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n const prefixCodePoint = prefix.codePointAt(0)\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefixCodePoint\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\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 } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or<OtherPrefix extends string> (decoder: UnibaseDecoder<OtherPrefix> | ComposedDecoder<OtherPrefix>): ComposedDecoder<Prefix | OtherPrefix> {\n return or(this, decoder)\n }\n}\n\ntype Decoders<Prefix extends string> = Record<Prefix, UnibaseDecoder<Prefix>>\n\nclass ComposedDecoder<Prefix extends string> implements MultibaseDecoder<Prefix>, CombobaseDecoder<Prefix> {\n readonly decoders: Decoders<Prefix>\n\n constructor (decoders: Decoders<Prefix>) {\n this.decoders = decoders\n }\n\n or <OtherPrefix extends string> (decoder: UnibaseDecoder<OtherPrefix> | ComposedDecoder<OtherPrefix>): ComposedDecoder<Prefix | OtherPrefix> {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\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}\n\nexport function or <L extends string, R extends string> (left: UnibaseDecoder<L> | CombobaseDecoder<L>, right: UnibaseDecoder<R> | CombobaseDecoder<R>): ComposedDecoder<L | R> {\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder<L>).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder<R>).prefix]: right })\n } as Decoders<L | R>)\n}\n\nexport class Codec<Base extends string, Prefix extends string> implements MultibaseCodec<Prefix>, MultibaseEncoder<Prefix>, MultibaseDecoder<Prefix>, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder<Base, Prefix>\n readonly decoder: Decoder<Base, Prefix>\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\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\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from <Base extends string, Prefix extends string> ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec<Base, Prefix> {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX <Base extends string, Prefix extends string> ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec<Base, Prefix> {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabetIdx: Record<string, number>, bitsPerChar: number, name: string): Uint8Array {\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\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 = alphabetIdx[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\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\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\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\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\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\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\n return out\n}\n\nfunction createAlphabetIdx (alphabet: string): Record<string, number> {\n // Build the character lookup table:\n const alphabetIdx: Record<string, number> = {}\n for (let i = 0; i < alphabet.length; ++i) {\n alphabetIdx[alphabet[i]] = i\n }\n return alphabetIdx\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 <Base extends string, Prefix extends string> ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec<Base, Prefix> {\n const alphabetIdx = createAlphabetIdx(alphabet)\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabetIdx, bitsPerChar, name)\n }\n })\n}\n", "import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n", "import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n", "/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\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\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 \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\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\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\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);\n\nvar length = function (/** @type {number} */ value) {\n return (\n 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 )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n", "import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n", "import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create <Code extends number> (code: Code, digest: Uint8Array): Digest<Code, number> {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\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\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\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\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\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<Code extends number, Size extends number> implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n\n/**\n * Used to check that the passed multihash has the passed code\n */\nexport function hasCode <T extends number> (digest: MultihashDigest, code: T): digest is MultihashDigest<T> {\n return digest.code === code\n}\n", "import { base32 } from './bases/base32.js'\nimport { base36 } from './bases/base36.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'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format <T extends API.Link<unknown, number, number, API.Version>, Prefix extends string> (link: T, base?: API.MultibaseEncoder<Prefix>): API.ToString<T, Prefix> {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder<Prefix>\n )\n }\n}\n\nexport function toJSON <Link extends API.UnknownLink> (link: Link): API.LinkJSON<Link> {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON <Link extends API.UnknownLink> (json: API.LinkJSON<Link>): CID<unknown, number, number, API.Version> {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap<API.UnknownLink, Map<string, string>>()\n\nfunction baseCache (cid: API.UnknownLink): Map<string, string> {\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}\n\nexport class CID<Data = unknown, Format extends number = number, Alg extends number = number, Version extends API.Version = API.Version> implements API.Link<Data, Format, Alg, Version> {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest<Alg>\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\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: Version, code: Format, multihash: API.MultihashDigest<Alg>, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\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 (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID<Data, API.DAG_PB, API.SHA_256, 0> {\n switch (this.version) {\n case 0: {\n return this as CID<Data, API.DAG_PB, API.SHA_256, 0>\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\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\n return (\n CID.createV0(\n multihash as API.MultihashDigest<API.SHA_256>\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID<Data, Format, Alg, 1> {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID<Data, Format, Alg, 1>\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID<Data, Format, Alg, Version> {\n return CID.equals(this, other)\n }\n\n static equals <Data, Format extends number, Alg extends number, Version extends API.Version>(self: API.Link<Data, Format, Alg, Version>, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder<string>): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON<this> {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\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 <Data, Format extends number, Alg extends number, Version extends API.Version, U>(input: API.Link<Data, Format, Alg, Version> | U): CID<Data, Format, Alg, Version> | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\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(\n version,\n code,\n multihash as API.MultihashDigest<Alg>,\n 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) as API.MultihashDigest<Alg>\n return CID.create(version, code, digest)\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 /**\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 <Data, Format extends number, Alg extends number, Version extends API.Version>(version: Version, code: Format, digest: API.MultihashDigest<Alg>): CID<Data, Format, Alg, Version> {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `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 /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 <T = unknown>(digest: API.MultihashDigest<typeof SHA_256_CODE>): CID<T, typeof DAG_PB_CODE, typeof SHA_256_CODE, 0> {\n return CID.create(0, DAG_PB_CODE, digest)\n }\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 <Data, Code extends number, Alg extends number>(code: Code, digest: API.MultihashDigest<Alg>): CID<Data, Code, Alg, 1> {\n return CID.create(1, code, digest)\n }\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 <Data, Code extends number, Alg extends number, Version extends API.Version>(bytes: API.ByteView<API.Link<Data, Code, Alg, Version>>): CID<Data, Code, Alg, Version> {\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 /**\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 <T, C extends number, A extends number, V extends API.Version>(bytes: API.ByteView<API.Link<T, C, A, V>>): [CID<T, C, A, V>, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest<API.SHA_256>)\n : CID.createV1(specs.codec, digest)\n return [cid as CID<T, C, A, V>, bytes.subarray(specs.size)]\n }\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 <T, C extends number, A extends number, V extends API.Version>(initialBytes: API.ByteView<API.Link<T, C, A, V>>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\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 <Prefix extends string, Data, Code extends number, Alg extends number, Version extends API.Version>(source: API.ToString<API.Link<Data, Code, Alg, Version>, Prefix>, base?: API.MultibaseDecoder<Prefix>): CID<Data, Code, Alg, Version> {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes <Prefix extends string, Data, Code extends number, Alg extends number, Version extends API.Version> (source: API.ToString<API.Link<Data, Code, Alg, Version>, Prefix>, base?: API.MultibaseDecoder<Prefix>): [Prefix, API.ByteView<API.Link<Data, Code, Alg, Version>>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n case base36.prefix: {\n const decoder = base ?? base36\n return [base36.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map<string, string>, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\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 } else {\n return cid\n }\n}\n\nfunction toStringV1 <Prefix extends string> (bytes: Uint8Array, cache: Map<string, string>, base: API.MultibaseEncoder<Prefix>): string {\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 } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\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}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n", "import * as cborg from 'cborg'\nimport { CID } from 'multiformats/cid'\n\n// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692\nconst CID_CBOR_TAG = 42\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ByteView<T>} ByteView\n */\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ArrayBufferView<T>} ArrayBufferView\n */\n\n/**\n * @template T\n * @param {ByteView<T> | ArrayBufferView<T>} buf\n * @returns {ByteView<T>}\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\n/**\n * cidEncoder will receive all Objects during encode, it needs to filter out\n * anything that's not a CID and return `null` for that so it's encoded as\n * normal.\n *\n * @param {any} obj\n * @returns {cborg.Token[]|null}\n */\nfunction cidEncoder (obj) {\n if (obj.asCID !== obj && obj['/'] !== obj.bytes) {\n return null // any other kind of object\n }\n const cid = CID.asCID(obj)\n /* c8 ignore next 4 */\n // very unlikely case, and it'll probably throw a recursion error in cborg\n if (!cid) {\n return null\n }\n const bytes = new Uint8Array(cid.bytes.byteLength + 1)\n bytes.set(cid.bytes, 1) // prefix is 0x00, for historical reasons\n return [\n new cborg.Token(cborg.Type.tag, CID_CBOR_TAG),\n new cborg.Token(cborg.Type.bytes, bytes)\n ]\n}\n\n// eslint-disable-next-line jsdoc/require-returns-check\n/**\n * Intercept all `undefined` values from an object walk and reject the entire\n * object if we find one.\n *\n * @returns {null}\n */\nfunction undefinedEncoder () {\n throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')\n}\n\n/**\n * Intercept all `number` values from an object walk and reject the entire\n * object if we find something that doesn't fit the IPLD data model (NaN &\n * Infinity).\n *\n * @param {number} num\n * @returns {null}\n */\nfunction numberEncoder (num) {\n if (Number.isNaN(num)) {\n throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')\n }\n if (num === Infinity || num === -Infinity) {\n throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')\n }\n return null\n}\n\nconst _encodeOptions = {\n float64: true,\n typeEncoders: {\n Object: cidEncoder,\n undefined: undefinedEncoder,\n number: numberEncoder\n }\n}\n\nexport const encodeOptions = {\n ..._encodeOptions,\n typeEncoders: {\n ..._encodeOptions.typeEncoders\n }\n}\n\n/**\n * @param {Uint8Array} bytes\n * @returns {CID}\n */\nfunction cidDecoder (bytes) {\n if (bytes[0] !== 0) {\n throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00')\n }\n return CID.decode(bytes.subarray(1)) // ignore leading 0x00\n}\n\nconst _decodeOptions = {\n allowIndefinite: false,\n coerceUndefinedToNull: true,\n allowNaN: false,\n allowInfinity: false,\n allowBigInt: true, // this will lead to BigInt for ints outside of\n // safe-integer range, which may surprise users\n strict: true,\n useMaps: false,\n rejectDuplicateMapKeys: true,\n /** @type {import('cborg').TagDecoder[]} */\n tags: []\n}\n_decodeOptions.tags[CID_CBOR_TAG] = cidDecoder\n\nexport const decodeOptions = {\n ..._decodeOptions,\n tags: _decodeOptions.tags.slice()\n}\n\nexport const name = 'dag-cbor'\nexport const code = 0x71\n\n/**\n * @template T\n * @param {T} node\n * @returns {ByteView<T>}\n */\nexport const encode = (node) => cborg.encode(node, _encodeOptions)\n\n/**\n * @template T\n * @param {ByteView<T> | ArrayBufferView<T>} data\n * @returns {T}\n */\nexport const decode = (data) => cborg.decode(toByteView(data), _decodeOptions)\n", "import varint from 'varint'\n\nexport const CIDV0_BYTES = {\n SHA2_256: 0x12,\n LENGTH: 0x20,\n DAG_PB: 0x70\n}\n\nexport const V2_HEADER_LENGTH = /* characteristics */ 16 /* v1 offset */ + 8 /* v1 size */ + 8 /* index offset */ + 8\n\n/**\n * Decodes varint and seeks the buffer\n *\n * ```js\n * // needs bytes to be read first\n * const bytes = reader.upTo(8) // maybe async\n * ```\n *\n * @param {Uint8Array} bytes\n * @param {import('./coding.js').Seekable} seeker\n * @returns {number}\n */\nexport function decodeVarint (bytes, seeker) {\n if (!bytes.length) {\n throw new Error('Unexpected end of data')\n }\n const i = varint.decode(bytes)\n seeker.seek(/** @type {number} */(varint.decode.bytes))\n return i\n}\n\n/**\n * Decode v2 header\n *\n * ```js\n * // needs bytes to be read first\n * const bytes = reader.exactly(V2_HEADER_LENGTH, true) // maybe async\n * ```\n *\n * @param {Uint8Array} bytes\n * @returns {import('./coding.js').CarV2FixedHeader}\n */\nexport function decodeV2Header (bytes) {\n const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n let offset = 0\n const header = {\n version: 2,\n /** @type {[bigint, bigint]} */\n characteristics: [\n dv.getBigUint64(offset, true),\n dv.getBigUint64(offset += 8, true)\n ],\n dataOffset: Number(dv.getBigUint64(offset += 8, true)),\n dataSize: Number(dv.getBigUint64(offset += 8, true)),\n indexOffset: Number(dv.getBigUint64(offset += 8, true))\n }\n return header\n}\n\n/**\n * Checks the length of the multihash to be read afterwards\n *\n * ```js\n * // needs bytes to be read first\n * const bytes = reader.upTo(8) // maybe async\n * ```\n *\n * @param {Uint8Array} bytes\n */\nexport function getMultihashLength (bytes) {\n // | code | length | .... |\n // where both code and length are varints, so we have to decode\n // them first before we can know total length\n\n varint.decode(bytes) // code\n const codeLength = /** @type {number} */(varint.decode.bytes)\n const length = varint.decode(bytes.subarray(varint.decode.bytes))\n const lengthLength = /** @type {number} */(varint.decode.bytes)\n const mhLength = codeLength + lengthLength + length\n\n return mhLength\n}\n", "/* eslint-disable jsdoc/check-indentation, max-depth */\n\n/**\n * Auto-generated with @ipld/schema@v4.2.0 at Thu Sep 14 2023 from IPLD Schema:\n *\n * # CarV1HeaderOrV2Pragma is a more relaxed form, and can parse {version:x} where\n * # roots are optional. This is typically useful for the {verison:2} CARv2\n * # pragma.\n *\n * type CarV1HeaderOrV2Pragma struct {\n * roots optional [&Any]\n * # roots is _not_ optional for CarV1 but we defer that check within code to\n * # gracefully handle the V2 case where it's just {version:X}\n * version Int\n * }\n *\n * # CarV1Header is the strict form of the header, and requires roots to be\n * # present. This is compatible with the CARv1 specification.\n *\n * # type CarV1Header struct {\n * # roots [&Any]\n * # version Int\n * # }\n *\n */\n\nconst Kinds = {\n Null: /**\n * @param obj\n * @returns {undefined|null}\n */ (/** @type {any} */ obj) => obj === null ? obj : undefined,\n Int: /**\n * @param obj\n * @returns {undefined|number}\n */ (/** @type {any} */ obj) => Number.isInteger(obj) ? obj : undefined,\n Float: /**\n * @param obj\n * @returns {undefined|number}\n */ (/** @type {any} */ obj) => typeof obj === 'number' && Number.isFinite(obj) ? obj : undefined,\n String: /**\n * @param obj\n * @returns {undefined|string}\n */ (/** @type {any} */ obj) => typeof obj === 'string' ? obj : undefined,\n Bool: /**\n * @param obj\n * @returns {undefined|boolean}\n */ (/** @type {any} */ obj) => typeof obj === 'boolean' ? obj : undefined,\n Bytes: /**\n * @param obj\n * @returns {undefined|Uint8Array}\n */ (/** @type {any} */ obj) => obj instanceof Uint8Array ? obj : undefined,\n Link: /**\n * @param obj\n * @returns {undefined|object}\n */ (/** @type {any} */ obj) => obj !== null && typeof obj === 'object' && obj.asCID === obj ? obj : undefined,\n List: /**\n * @param obj\n * @returns {undefined|Array<any>}\n */ (/** @type {any} */ obj) => Array.isArray(obj) ? obj : undefined,\n Map: /**\n * @param obj\n * @returns {undefined|object}\n */ (/** @type {any} */ obj) => obj !== null && typeof obj === 'object' && obj.asCID !== obj && !Array.isArray(obj) && !(obj instanceof Uint8Array) ? obj : undefined\n}\n/** @type {{ [k in string]: (obj:any)=>undefined|any}} */\nconst Types = {\n 'CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)': Kinds.Link,\n 'CarV1HeaderOrV2Pragma > roots (anon)': /**\n * @param obj\n * @returns {undefined|any}\n */ (/** @type {any} */ obj) => {\n if (Kinds.List(obj) === undefined) {\n return undefined\n }\n for (let i = 0; i < obj.length; i++) {\n let v = obj[i]\n v = Types['CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)'](v)\n if (v === undefined) {\n return undefined\n }\n if (v !== obj[i]) {\n const ret = obj.slice(0, i)\n for (let j = i; j < obj.length; j++) {\n let v = obj[j]\n v = Types['CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)'](v)\n if (v === undefined) {\n return undefined\n }\n ret.push(v)\n }\n return ret\n }\n }\n return obj\n },\n Int: Kinds.Int,\n CarV1HeaderOrV2Pragma: /**\n * @param obj\n * @returns {undefined|any}\n */ (/** @type {any} */ obj) => {\n if (Kinds.Map(obj) === undefined) {\n return undefined\n }\n const entries = Object.entries(obj)\n /** @type {{[k in string]: any}} */\n let ret = obj\n let requiredCount = 1\n for (let i = 0; i < entries.length; i++) {\n const [key, value] = entries[i]\n switch (key) {\n case 'roots':\n {\n const v = Types['CarV1HeaderOrV2Pragma > roots (anon)'](obj[key])\n if (v === undefined) {\n return undefined\n }\n if (v !== value || ret !== obj) {\n if (ret === obj) {\n /** @type {{[k in string]: any}} */\n ret = {}\n for (let j = 0; j < i; j++) {\n ret[entries[j][0]] = entries[j][1]\n }\n }\n ret.roots = v\n }\n }\n break\n case 'version':\n {\n requiredCount--\n const v = Types.Int(obj[key])\n if (v === undefined) {\n return undefined\n }\n if (v !== value || ret !== obj) {\n if (ret === obj) {\n /** @type {{[k in string]: any}} */\n ret = {}\n for (let j = 0; j < i; j++) {\n ret[entries[j][0]] = entries[j][1]\n }\n }\n ret.version = v\n }\n }\n break\n default:\n return undefined\n }\n }\n\n if (requiredCount > 0) {\n return undefined\n }\n return ret\n }\n}\n/** @type {{ [k in string]: (obj:any)=>undefined|any}} */\nconst Reprs = {\n 'CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)': Kinds.Link,\n 'CarV1HeaderOrV2Pragma > roots (anon)': /**\n * @param obj\n * @returns {undefined|any}\n */ (/** @type {any} */ obj) => {\n if (Kinds.List(obj) === undefined) {\n return undefined\n }\n for (let i = 0; i < obj.length; i++) {\n let v = obj[i]\n v = Reprs['CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)'](v)\n if (v === undefined) {\n return undefined\n }\n if (v !== obj[i]) {\n const ret = obj.slice(0, i)\n for (let j = i; j < obj.length; j++) {\n let v = obj[j]\n v = Reprs['CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)'](v)\n if (v === undefined) {\n return undefined\n }\n ret.push(v)\n }\n return ret\n }\n }\n return obj\n },\n Int: Kinds.Int,\n CarV1HeaderOrV2Pragma: /**\n * @param obj\n * @returns {undefined|any}\n */ (/** @type {any} */ obj) => {\n if (Kinds.Map(obj) === undefined) {\n return undefined\n }\n const entries = Object.entries(obj)\n /** @type {{[k in string]: any}} */\n let ret = obj\n let requiredCount = 1\n for (let i = 0; i < entries.length; i++) {\n const [key, value] = entries[i]\n switch (key) {\n case 'roots':\n {\n const v = Reprs['CarV1HeaderOrV2Pragma > roots (anon)'](value)\n if (v === undefined) {\n return undefined\n }\n if (v !== value || ret !== obj) {\n if (ret === obj) {\n /** @type {{[k in string]: any}} */\n ret = {}\n for (let j = 0; j < i; j++) {\n ret[entries[j][0]] = entries[j][1]\n }\n }\n ret.roots = v\n }\n }\n break\n case 'version':\n {\n requiredCount--\n const v = Reprs.Int(value)\n if (v === undefined) {\n return undefined\n }\n if (v !== value || ret !== obj) {\n if (ret === obj) {\n /** @type {{[k in string]: any}} */\n ret = {}\n for (let j = 0; j < i; j++) {\n ret[entries[j][0]] = entries[j][1]\n }\n }\n ret.version = v\n }\n }\n break\n default:\n return undefined\n }\n }\n if (requiredCount > 0) {\n return undefined\n }\n return ret\n }\n}\n\nexport const CarV1HeaderOrV2Pragma = {\n toTyped: Types.CarV1HeaderOrV2Pragma,\n toRepresentation: Reprs.CarV1HeaderOrV2Pragma\n}\n", "import { makeCborEncoders, objectToTokens } from './encode.js'\nimport { quickEncodeToken } from './jump.js'\n\n/**\n * @typedef {import('../interface').EncodeOptions} EncodeOptions\n * @typedef {import('../interface').TokenTypeEncoder} TokenTypeEncoder\n * @typedef {import('../interface').TokenOrNestedTokens} TokenOrNestedTokens\n */\n\nconst cborEncoders = makeCborEncoders()\n\n/** @type {EncodeOptions} */\nconst defaultEncodeOptions = {\n float64: false,\n quickEncodeToken\n}\n\n/**\n * Calculate the byte length of the given data when encoded as CBOR with the\n * options provided.\n * This calculation will be accurate if the same options are used as when\n * performing a normal encode. Some encode options can change the encoding\n * output length.\n *\n * @param {any} data\n * @param {EncodeOptions} [options]\n * @returns {number}\n */\nexport function encodedLength (data, options) {\n options = Object.assign({}, defaultEncodeOptions, options)\n options.mapSorter = undefined // won't change the length\n const tokens = objectToTokens(data, options)\n return tokensToLength(tokens, cborEncoders, options)\n}\n\n/**\n * Calculate the byte length of the data as represented by the given tokens when\n * encoded as CBOR with the options provided.\n * This function is for advanced users and would not normally be called\n * directly. See `encodedLength()` for appropriate use.\n *\n * @param {TokenOrNestedTokens} tokens\n * @param {TokenTypeEncoder[]} [encoders]\n * @param {EncodeOptions} [options]\n */\nexport function tokensToLength (tokens, encoders = cborEncoders, options = defaultEncodeOptions) {\n if (Array.isArray(tokens)) {\n let len = 0\n for (const token of tokens) {\n len += tokensToLength(token, encoders, options)\n }\n return len\n } else {\n const encoder = encoders[tokens.type.major]\n /* c8 ignore next 3 */\n if (encoder.encodedSize === undefined || typeof encoder.encodedSize !== 'function') {\n throw new Error(`Encoder for ${tokens.type.name} does not have an encodedSize()`)\n }\n return encoder.encodedSize(tokens, options)\n }\n}\n", "import * as CBOR from '@ipld/dag-cbor'\nimport { Token, Type } from 'cborg'\nimport { tokensToLength } from 'cborg/length'\nimport varint from 'varint'\n\n/**\n * @typedef {import('./api.js').CID} CID\n * @typedef {import('./api.js').Block} Block\n * @typedef {import('./api.js').CarBufferWriter} Writer\n * @typedef {import('./api.js').CarBufferWriterOptions} Options\n * @typedef {import('./coding.js').CarEncoder} CarEncoder\n */\n\n/**\n * A simple CAR writer that writes to a pre-allocated buffer.\n *\n * @class\n * @name CarBufferWriter\n * @implements {Writer}\n */\nclass CarBufferWriter {\n /**\n * @param {Uint8Array} bytes\n * @param {number} headerSize\n */\n constructor (bytes, headerSize) {\n /** @readonly */\n this.bytes = bytes\n this.byteOffset = headerSize\n\n /**\n * @readonly\n * @type {CID[]}\n */\n this.roots = []\n this.headerSize = headerSize\n }\n\n /**\n * Add a root to this writer, to be used to create a header when the CAR is\n * finalized with {@link CarBufferWriter.close `close()`}\n *\n * @param {CID} root\n * @param {{resize?:boolean}} [options]\n * @returns {CarBufferWriter}\n */\n addRoot (root, options) {\n addRoot(this, root, options)\n return this\n }\n\n /**\n * Write a `Block` (a `{ cid:CID, bytes:Uint8Array }` pair) to the archive.\n * Throws if there is not enough capacity.\n *\n * @param {Block} block - A `{ cid:CID, bytes:Uint8Array }` pair.\n * @returns {CarBufferWriter}\n */\n write (block) {\n addBlock(this, block)\n return this\n }\n\n /**\n * Finalize the CAR and return it as a `Uint8Array`.\n *\n * @param {object} [options]\n * @param {boolean} [options.resize]\n * @returns {Uint8Array}\n */\n close (options) {\n return close(this, options)\n }\n}\n\n/**\n * @param {CarBufferWriter} writer\n * @param {CID} root\n * @param {{resize?:boolean}} [options]\n */\nexport const addRoot = (writer, root, options = {}) => {\n const { resize = false } = options\n const { bytes, headerSize, byteOffset, roots } = writer\n writer.roots.push(root)\n const size = headerLength(writer)\n // If there is not enough space for the new root\n if (size > headerSize) {\n // Check if we root would fit if we were to resize the head.\n if (size - headerSize + byteOffset < bytes.byteLength) {\n // If resize is enabled resize head\n if (resize) {\n resizeHeader(writer, size)\n // otherwise remove head and throw an error suggesting to resize\n } else {\n roots.pop()\n throw new RangeError(`Header of size ${headerSize} has no capacity for new root ${root}.\n However there is a space in the buffer and you could call addRoot(root, { resize: root }) to resize header to make a space for this root.`)\n }\n // If head would not fit even with resize pop new root and throw error\n } else {\n roots.pop()\n throw new RangeError(`Buffer has no capacity for a new root ${root}`)\n }\n }\n}\n\n/**\n * Calculates number of bytes required for storing given block in CAR. Useful in\n * estimating size of an `ArrayBuffer` for the `CarBufferWriter`.\n *\n * @name CarBufferWriter.blockLength(Block)\n * @param {Block} block\n * @returns {number}\n */\nexport const blockLength = ({ cid, bytes }) => {\n const size = cid.bytes.byteLength + bytes.byteLength\n return varint.encodingLength(size) + size\n}\n\n/**\n * @param {CarBufferWriter} writer\n * @param {Block} block\n */\nexport const addBlock = (writer, { cid, bytes }) => {\n const byteLength = cid.bytes.byteLength + bytes.byteLength\n const size = varint.encode(byteLength)\n if (writer.byteOffset + size.length + byteLength > writer.bytes.byteLength) {\n throw new RangeError('Buffer has no capacity for this block')\n } else {\n writeBytes(writer, size)\n writeBytes(writer, cid.bytes)\n writeBytes(writer, bytes)\n }\n}\n\n/**\n * @param {CarBufferWriter} writer\n * @param {object} [options]\n * @param {boolean} [options.resize]\n */\nexport const close = (writer, options = {}) => {\n const { resize = false } = options\n const { roots, bytes, byteOffset, headerSize } = writer\n\n const headerBytes = CBOR.encode({ version: 1, roots })\n const varintBytes = varint.encode(headerBytes.length)\n\n const size = varintBytes.length + headerBytes.byteLength\n const offset = headerSize - size\n\n // If header size estimate was accurate we just write header and return\n // view into buffer.\n if (offset === 0) {\n writeHeader(writer, varintBytes, headerBytes)\n return bytes.subarray(0, byteOffset)\n // If header was overestimated and `{resize: true}` is passed resize header\n } else if (resize) {\n resizeHeader(writer, size)\n writeHeader(writer, varintBytes, headerBytes)\n return bytes.subarray(0, writer.byteOffset)\n } else {\n throw new RangeError(`Header size was overestimated.\nYou can use close({ resize: true }) to resize header`)\n }\n}\n\n/**\n * @param {CarBufferWriter} writer\n * @param {number} byteLength\n */\nexport const resizeHeader = (writer, byteLength) => {\n const { bytes, headerSize } = writer\n // Move data section to a new offset\n bytes.set(bytes.subarray(headerSize, writer.byteOffset), byteLength)\n // Update header size & byteOffset\n writer.byteOffset += byteLength - headerSize\n writer.headerSize = byteLength\n}\n\n/**\n * @param {CarBufferWriter} writer\n * @param {number[]|Uint8Array} bytes\n */\n\nconst writeBytes = (writer, bytes) => {\n writer.bytes.set(bytes, writer.byteOffset)\n writer.byteOffset += bytes.length\n}\n/**\n * @param {{bytes:Uint8Array}} writer\n * @param {number[]} varint\n * @param {Uint8Array} header\n */\nconst writeHeader = ({ bytes }, varint, header) => {\n bytes.set(varint)\n bytes.set(header, varint.length)\n}\n\nconst headerPreludeTokens = [\n new Token(Type.map, 2),\n new Token(Type.string, 'version'),\n new Token(Type.uint, 1),\n new Token(Type.string, 'roots')\n]\n\nconst CID_TAG = new Token(Type.tag, 42)\n\n/**\n * Calculates header size given the array of byteLength for roots.\n *\n * @name CarBufferWriter.calculateHeaderLength(rootLengths)\n * @param {number[]} rootLengths\n * @returns {number}\n */\nexport const calculateHeaderLength = (rootLengths) => {\n const tokens = [...headerPreludeTokens]\n tokens.push(new Token(Type.array, rootLengths.length))\n for (const rootLength of rootLengths) {\n tokens.push(CID_TAG)\n tokens.push(new Token(Type.bytes, { length: rootLength + 1 }))\n }\n const length = tokensToLength(tokens) // no options needed here because we have simple tokens\n return varint.encodingLength(length) + length\n}\n\n/**\n * Calculates header size given the array of roots.\n *\n * @name CarBufferWriter.headerLength({ roots })\n * @param {object} options\n * @param {CID[]} options.roots\n * @returns {number}\n */\nexport const headerLength = ({ roots }) =>\n calculateHeaderLength(roots.map(cid => cid.bytes.byteLength))\n\n/**\n * Estimates header size given a count of the roots and the expected byte length\n * of the root CIDs. The default length works for a standard CIDv1 with a\n * single-byte multihash code, such as SHA2-256 (i.e. the most common CIDv1).\n *\n * @name CarBufferWriter.estimateHeaderLength(rootCount[, rootByteLength])\n * @param {number} rootCount\n * @param {number} [rootByteLength]\n * @returns {number}\n */\nexport const estimateHeaderLength = (rootCount, rootByteLength = 36) =>\n calculateHeaderLength(new Array(rootCount).fill(rootByteLength))\n\n/**\n * Creates synchronous CAR writer that can be used to encode blocks into a given\n * buffer. Optionally you could pass `byteOffset` and `byteLength` to specify a\n * range inside buffer to write into. If car file is going to have `roots` you\n * need to either pass them under `options.roots` (from which header size will\n * be calculated) or provide `options.headerSize` to allocate required space\n * in the buffer. You may also provide known `roots` and `headerSize` to\n * allocate space for the roots that may not be known ahead of time.\n *\n * Note: Incorrect `headerSize` may lead to copying bytes inside a buffer\n * which will have a negative impact on performance.\n *\n * @name CarBufferWriter.createWriter(buffer[, options])\n * @param {ArrayBuffer} buffer\n * @param {object} [options]\n * @param {CID[]} [options.roots]\n * @param {number} [options.byteOffset]\n * @param {number} [options.byteLength]\n * @param {number} [options.headerSize]\n * @returns {CarBufferWriter}\n */\nexport const createWriter = (buffer, options = {}) => {\n const {\n roots = [],\n byteOffset = 0,\n byteLength = buffer.byteLength,\n headerSize = headerLength({ roots })\n } = options\n const bytes = new Uint8Array(buffer, byteOffset, byteLength)\n\n const writer = new CarBufferWriter(bytes, headerSize)\n for (const root of roots) {\n writer.addRoot(root)\n }\n\n return writer\n}\n", "import { decode as decodeDagCbor } from '@ipld/dag-cbor'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { CIDV0_BYTES, decodeV2Header, decodeVarint, getMultihashLength, V2_HEADER_LENGTH } from './decoder-common.js'\nimport { CarV1HeaderOrV2Pragma } from './header-validator.js'\n\n/**\n * @typedef {import('./api.js').Block} Block\n * @typedef {import('./api.js').BlockHeader} BlockHeader\n * @typedef {import('./api.js').BlockIndex} BlockIndex\n * @typedef {import('./coding.js').BytesReader} BytesReader\n * @typedef {import('./coding.js').CarHeader} CarHeader\n * @typedef {import('./coding.js').CarV2Header} CarV2Header\n * @typedef {import('./coding.js').CarV2FixedHeader} CarV2FixedHeader\n * @typedef {import('./coding.js').CarDecoder} CarDecoder\n */\n\n/**\n * Reads header data from a `BytesReader`. The header may either be in the form\n * of a `CarHeader` or `CarV2Header` depending on the CAR being read.\n *\n * @name async decoder.readHeader(reader)\n * @param {BytesReader} reader\n * @param {number} [strictVersion]\n * @returns {Promise<CarHeader|CarV2Header>}\n */\nexport async function readHeader (reader, strictVersion) {\n const length = decodeVarint(await reader.upTo(8), reader)\n if (length === 0) {\n throw new Error('Invalid CAR header (zero length)')\n }\n const header = await reader.exactly(length, true)\n const block = decodeDagCbor(header)\n if (CarV1HeaderOrV2Pragma.toTyped(block) === undefined) {\n throw new Error('Invalid CAR header format')\n }\n if ((block.version !== 1 && block.version !== 2) || (strictVersion !== undefined && block.version !== strictVersion)) {\n throw new Error(`Invalid CAR version: ${block.version}${strictVersion !== undefined ? ` (expected ${strictVersion})` : ''}`)\n }\n if (block.version === 1) {\n // CarV1HeaderOrV2Pragma makes roots optional, let's make it mandatory\n if (!Array.isArray(block.roots)) {\n throw new Error('Invalid CAR header format')\n }\n return block\n }\n // version 2\n if (block.roots !== undefined) {\n throw new Error('Invalid CAR header format')\n }\n const v2Header = decodeV2Header(await reader.exactly(V2_HEADER_LENGTH, true))\n reader.seek(v2Header.dataOffset - reader.pos)\n const v1Header = await readHeader(reader, 1)\n return Object.assign(v1Header, v2Header)\n}\n\n/**\n * @param {BytesReader} reader\n * @returns {Promise<CID>}\n */\nasync function readCid (reader) {\n const first = await reader.exactly(2, false)\n if (first[0] === CIDV0_BYTES.SHA2_256 && first[1] === CIDV0_BYTES.LENGTH) {\n // cidv0 32-byte sha2-256\n const bytes = await reader.exactly(34, true)\n const multihash = Digest.decode(bytes)\n return CID.create(0, CIDV0_BYTES.DAG_PB, multihash)\n }\n\n const version = decodeVarint(await reader.upTo(8), reader)\n if (version !== 1) {\n throw new Error(`Unexpected CID version (${version})`)\n }\n const codec = decodeVarint(await reader.upTo(8), reader)\n const bytes = await reader.exactly(getMultihashLength(await reader.upTo(8)), true)\n const multihash = Digest.decode(bytes)\n return CID.create(version, codec, multihash)\n}\n\n/**\n * Reads the leading data of an individual block from CAR data from a\n * `BytesReader`. Returns a `BlockHeader` object which contains\n * `{ cid, length, blockLength }` which can be used to either index the block\n * or read the block binary data.\n *\n * @name async decoder.readBlockHead(reader)\n * @param {BytesReader} reader\n * @returns {Promise<BlockHeader>}\n */\nexport async function readBlockHead (reader) {\n // length includes a CID + Binary, where CID has a variable length\n // we have to deal with\n const start = reader.pos\n let length = decodeVarint(await reader.upTo(8), reader)\n if (length === 0) {\n throw new Error('Invalid CAR section (zero length)')\n }\n length += (reader.pos - start)\n const cid = await readCid(reader)\n const blockLength = length - Number(reader.pos - start) // subtract CID length\n\n return { cid, length, blockLength }\n}\n\n/**\n * @param {BytesReader} reader\n * @returns {Promise<Block>}\n */\nasync function readBlock (reader) {\n const { cid, blockLength } = await readBlockHead(reader)\n const bytes = await reader.exactly(blockLength, true)\n return { bytes, cid }\n}\n\n/**\n * @param {BytesReader} reader\n * @returns {Promise<BlockIndex>}\n */\nasync function readBlockIndex (reader) {\n const offset = reader.pos\n const { cid, length, blockLength } = await readBlockHead(reader)\n const index = { cid, length, blockLength, offset, blockOffset: reader.pos }\n reader.seek(index.blockLength)\n return index\n}\n\n/**\n * Creates a `CarDecoder` from a `BytesReader`. The `CarDecoder` is as async\n * interface that will consume the bytes from the `BytesReader` to yield a\n * `header()` and either `blocks()` or `blocksIndex()` data.\n *\n * @name decoder.createDecoder(reader)\n * @param {BytesReader} reader\n * @returns {CarDecoder}\n */\nexport function createDecoder (reader) {\n const headerPromise = (async () => {\n const header = await readHeader(reader)\n if (header.version === 2) {\n const v1length = reader.pos - header.dataOffset\n reader = limitReader(reader, header.dataSize - v1length)\n }\n return header\n })()\n\n return {\n header: () => headerPromise,\n\n async * blocks () {\n await headerPromise\n while ((await reader.upTo(8)).length > 0) {\n yield await readBlock(reader)\n }\n },\n\n async * blocksIndex () {\n await headerPromise\n while ((await reader.upTo(8)).length > 0) {\n yield await readBlockIndex(reader)\n }\n }\n }\n}\n\n/**\n * Creates a `BytesReader` from a `Uint8Array`.\n *\n * @name decoder.bytesReader(bytes)\n * @param {Uint8Array} bytes\n * @returns {BytesReader}\n */\nexport function bytesReader (bytes) {\n let pos = 0\n\n /** @type {BytesReader} */\n return {\n async upTo (length) {\n const out = bytes.subarray(pos, pos + Math.min(length, bytes.length - pos))\n return out\n },\n\n async exactly (length, seek = false) {\n if (length > bytes.length - pos) {\n throw new Error('Unexpected end of data')\n }\n const out = bytes.subarray(pos, pos + length)\n if (seek) {\n pos += length\n }\n return out\n },\n\n seek (length) {\n pos += length\n },\n\n get pos () {\n return pos\n }\n }\n}\n\n/**\n * reusable reader for streams and files, we just need a way to read an\n * additional chunk (of some undetermined size) and a way to close the\n * reader when finished\n *\n * @param {() => Promise<Uint8Array|null>} readChunk\n * @returns {BytesReader}\n */\nexport function chunkReader (readChunk /*, closer */) {\n let pos = 0\n let have = 0\n let offset = 0\n let currentChunk = new Uint8Array(0)\n\n const read = async (/** @type {number} */ length) => {\n have = currentChunk.length - offset\n const bufa = /** @type {Uint8Array<ArrayBufferLike>[]} */([currentChunk.subarray(offset)])\n while (have < length) {\n const chunk = await readChunk()\n if (chunk == null) {\n break\n }\n /* c8 ignore next 8 */\n // undo this ignore ^ when we have a fd implementation that can seek()\n if (have < 0) { // because of a seek()\n /* c8 ignore next 4 */\n // toohard to test the else\n if (chunk.length > have) {\n bufa.push(chunk.subarray(-have))\n } // else discard\n } else {\n bufa.push(chunk)\n }\n have += chunk.length\n }\n currentChunk = new Uint8Array(bufa.reduce((p, c) => p + c.length, 0))\n let off = 0\n for (const b of bufa) {\n currentChunk.set(b, off)\n off += b.length\n }\n offset = 0\n }\n\n /** @type {BytesReader} */\n return {\n async upTo (length) {\n if (currentChunk.length - offset < length) {\n await read(length)\n }\n return currentChunk.subarray(offset, offset + Math.min(currentChunk.length - offset, length))\n },\n\n async exactly (length, seek = false) {\n if (currentChunk.length - offset < length) {\n await read(length)\n }\n if (currentChunk.length - offset < length) {\n throw new Error('Unexpected end of data')\n }\n const out = currentChunk.subarray(offset, offset + length)\n if (seek) {\n pos += length\n offset += length\n }\n return out\n },\n\n seek (length) {\n pos += length\n offset += length\n },\n\n get pos () {\n return pos\n }\n }\n}\n\n/**\n * Creates a `BytesReader` from an `AsyncIterable<Uint8Array>`, which allows for\n * consumption of CAR data from a streaming source.\n *\n * @name decoder.asyncIterableReader(asyncIterable)\n * @param {AsyncIterable<Uint8Array>} asyncIterable\n * @returns {BytesReader}\n */\nexport function asyncIterableReader (asyncIterable) {\n const iterator = asyncIterable[Symbol.asyncIterator]()\n\n async function readChunk () {\n const next = await iterator.next()\n if (next.done) {\n return null\n }\n return next.value\n }\n\n return chunkReader(readChunk)\n}\n\n/**\n * Wraps a `BytesReader` in a limiting `BytesReader` which limits maximum read\n * to `byteLimit` bytes. It _does not_ update `pos` of the original\n * `BytesReader`.\n *\n * @name decoder.limitReader(reader, byteLimit)\n * @param {BytesReader} reader\n * @param {number} byteLimit\n * @returns {BytesReader}\n */\nexport function limitReader (reader, byteLimit) {\n let bytesRead = 0\n\n /** @type {BytesReader} */\n return {\n async upTo (length) {\n let bytes = await reader.upTo(length)\n if (bytes.length + bytesRead > byteLimit) {\n bytes = bytes.subarray(0, byteLimit - bytesRead)\n }\n return bytes\n },\n\n async exactly (length, seek = false) {\n const bytes = await reader.exactly(length, seek)\n if (bytes.length + bytesRead > byteLimit) {\n throw new Error('Unexpected end of data')\n }\n if (seek) {\n bytesRead += length\n }\n return bytes\n },\n\n seek (length) {\n bytesRead += length\n reader.seek(length)\n },\n\n get pos () {\n return reader.pos\n }\n }\n}\n", "import { encode as dagCborEncode } from '@ipld/dag-cbor'\nimport varint from 'varint'\n\n/**\n * @typedef {import('multiformats').CID} CID\n * @typedef {import('./api.js').Block} Block\n * @typedef {import('./coding.js').CarEncoder} CarEncoder\n * @typedef {import('./coding.js').IteratorChannel_Writer<Uint8Array>} IteratorChannel_Writer\n */\n\nconst CAR_V1_VERSION = 1\n\n/**\n * Create a header from an array of roots.\n *\n * @param {CID[]} roots\n * @returns {Uint8Array}\n */\nexport function createHeader (roots) {\n const headerBytes = dagCborEncode({ version: CAR_V1_VERSION, roots })\n const varintBytes = varint.encode(headerBytes.length)\n const header = new Uint8Array(varintBytes.length + headerBytes.length)\n header.set(varintBytes, 0)\n header.set(headerBytes, varintBytes.length)\n return header\n}\n\n/**\n * @param {IteratorChannel_Writer} writer\n * @returns {CarEncoder}\n */\nfunction createEncoder (writer) {\n // none of this is wrapped in a mutex, that needs to happen above this to\n // avoid overwrites\n\n return {\n /**\n * @param {CID[]} roots\n * @returns {Promise<void>}\n */\n async setRoots (roots) {\n const bytes = createHeader(roots)\n await writer.write(bytes)\n },\n\n /**\n * @param {Block} block\n * @returns {Promise<void>}\n */\n async writeBlock (block) {\n const { cid, bytes } = block\n await writer.write(new Uint8Array(varint.encode(cid.bytes.length + bytes.length)))\n await writer.write(cid.bytes)\n if (bytes.length) {\n // zero-length blocks are valid, but it'd be safer if we didn't write them\n await writer.write(bytes)\n }\n },\n\n /**\n * @returns {Promise<void>}\n */\n async close () {\n await writer.end()\n },\n\n /**\n * @returns {number}\n */\n version () {\n return CAR_V1_VERSION\n }\n }\n}\n\nexport { createEncoder }\n", "/**\n * @template {any} T\n * @typedef {import('./coding.js').IteratorChannel<T>} IteratorChannel\n */\n\nfunction noop () {}\n\n/**\n * @template {any} T\n * @returns {IteratorChannel<T>}\n */\nexport function create () {\n /** @type {T[]} */\n const chunkQueue = []\n /** @type {Promise<void> | null} */\n let drainer = null\n let drainerResolver = noop\n let ended = false\n /** @type {Promise<IteratorResult<T>> | null} */\n let outWait = null\n let outWaitResolver = noop\n\n const makeDrainer = () => {\n if (!drainer) {\n drainer = new Promise((resolve) => {\n drainerResolver = () => {\n drainer = null\n drainerResolver = noop\n resolve()\n }\n })\n }\n return drainer\n }\n\n /**\n * @returns {IteratorChannel<T>}\n */\n const writer = {\n /**\n * @param {T} chunk\n * @returns {Promise<void>}\n */\n write (chunk) {\n chunkQueue.push(chunk)\n const drainer = makeDrainer()\n outWaitResolver()\n return drainer\n },\n\n async end () {\n ended = true\n const drainer = makeDrainer()\n outWaitResolver()\n await drainer\n }\n }\n\n /** @type {AsyncIterator<T>} */\n const iterator = {\n /** @returns {Promise<IteratorResult<T>>} */\n async next () {\n const chunk = chunkQueue.shift()\n if (chunk) {\n if (chunkQueue.length === 0) {\n drainerResolver()\n }\n return { done: false, value: chunk }\n }\n\n if (ended) {\n drainerResolver()\n return { done: true, value: undefined }\n }\n\n if (!outWait) {\n outWait = new Promise((resolve) => {\n outWaitResolver = () => {\n outWait = null\n outWaitResolver = noop\n return resolve(iterator.next())\n }\n })\n }\n\n return outWait\n }\n }\n\n return { writer, iterator }\n}\n", "import { CID } from 'multiformats/cid'\nimport { bytesReader, readHeader } from './decoder.js'\nimport { createEncoder, createHeader } from './encoder.js'\nimport { create as iteratorChannel } from './iterator-channel.js'\n\n/**\n * @typedef {import('./api.js').Block} Block\n * @typedef {import('./api.js').BlockWriter} BlockWriter\n * @typedef {import('./api.js').WriterChannel} WriterChannel\n * @typedef {import('./coding.js').CarEncoder} CarEncoder\n * @typedef {import('./coding.js').IteratorChannel<Uint8Array>} IteratorChannel\n */\n\n/**\n * Provides a writer interface for the creation of CAR files.\n *\n * Creation of a `CarWriter` involves the instatiation of an input / output pair\n * in the form of a `WriterChannel`, which is a\n * `{ writer:CarWriter, out:AsyncIterable<Uint8Array> }` pair. These two\n * components form what can be thought of as a stream-like interface. The\n * `writer` component (an instantiated `CarWriter`), has methods to\n * {@link CarWriter.put `put()`} new blocks and {@link CarWriter.put `close()`}\n * the writing operation (finalising the CAR archive). The `out` component is\n * an `AsyncIterable` that yields the bytes of the archive. This can be\n * redirected to a file or other sink. In Node.js, you can use the\n * [`Readable.from()`](https://nodejs.org/api/stream.html#stream_stream_readable_from_iterable_options)\n * API to convert this to a standard Node.js stream, or it can be directly fed\n * to a\n * [`stream.pipeline()`](https://nodejs.org/api/stream.html#stream_stream_pipeline_source_transforms_destination_callback).\n *\n * The channel will provide a form of backpressure. The `Promise` from a\n * `write()` won't resolve until the resulting data is drained from the `out`\n * iterable.\n *\n * It is also possible to ignore the `Promise` from `write()` calls and allow\n * the generated data to queue in memory. This should be avoided for large CAR\n * archives of course due to the memory costs and potential for memory overflow.\n *\n * Load this class with either\n * `import { CarWriter } from '@ipld/car/writer'`\n * (`const { CarWriter } = require('@ipld/car/writer')`). Or\n * `import { CarWriter } from '@ipld/car'`\n * (`const { CarWriter } = require('@ipld/car')`). The former will likely\n * result in smaller bundle sizes where this is important.\n *\n * @name CarWriter\n * @class\n * @implements {BlockWriter}\n */\nexport class CarWriter {\n /**\n * @param {CID[]} roots\n * @param {CarEncoder} encoder\n */\n constructor (roots, encoder) {\n this._encoder = encoder\n /** @type {Promise<void>} */\n this._mutex = encoder.setRoots(roots)\n this._ended = false\n }\n\n /**\n * Write a `Block` (a `{ cid:CID, bytes:Uint8Array }` pair) to the archive.\n *\n * @function\n * @memberof CarWriter\n * @instance\n * @async\n * @param {Block} block - A `{ cid:CID, bytes:Uint8Array }` pair.\n * @returns {Promise<void>} The returned promise will only resolve once the\n * bytes this block generates are written to the `out` iterable.\n */\n async put (block) {\n if (!(block.bytes instanceof Uint8Array) || !block.cid) {\n throw new TypeError('Can only write {cid, bytes} objects')\n }\n if (this._ended) {\n throw new Error('Already closed')\n }\n const cid = CID.asCID(block.cid)\n if (!cid) {\n throw new TypeError('Can only write {cid, bytes} objects')\n }\n this._mutex = this._mutex.then(() => this._encoder.writeBlock({ cid, bytes: block.bytes }))\n return this._mutex\n }\n\n /**\n * Finalise the CAR archive and signal that the `out` iterable should end once\n * any remaining bytes are written.\n *\n * @function\n * @memberof CarWriter\n * @instance\n * @async\n * @returns {Promise<void>}\n */\n async close () {\n if (this._ended) {\n throw new Error('Already closed')\n }\n await this._mutex\n this._ended = true\n return this._encoder.close()\n }\n\n /**\n * Returns the version number of the CAR file being written\n *\n * @returns {number}\n */\n version () {\n return this._encoder.version()\n }\n\n /**\n * Create a new CAR writer \"channel\" which consists of a\n * `{ writer:CarWriter, out:AsyncIterable<Uint8Array> }` pair.\n *\n * @async\n * @static\n * @memberof CarWriter\n * @param {CID[] | CID | void} roots\n * @returns {WriterChannel} The channel takes the form of\n * `{ writer:CarWriter, out:AsyncIterable<Uint8Array> }`.\n */\n static create (roots) {\n roots = toRoots(roots)\n const { encoder, iterator } = encodeWriter()\n const writer = new CarWriter(roots, encoder)\n const out = new CarWriterOut(iterator)\n return { writer, out }\n }\n\n /**\n * Create a new CAR appender \"channel\" which consists of a\n * `{ writer:CarWriter, out:AsyncIterable<Uint8Array> }` pair.\n * This appender does not consider roots and does not produce a CAR header.\n * It is designed to append blocks to an _existing_ CAR archive. It is\n * expected that `out` will be concatenated onto the end of an existing\n * archive that already has a properly formatted header.\n *\n * @async\n * @static\n * @memberof CarWriter\n * @returns {WriterChannel} The channel takes the form of\n * `{ writer:CarWriter, out:AsyncIterable<Uint8Array> }`.\n */\n static createAppender () {\n const { encoder, iterator } = encodeWriter()\n encoder.setRoots = () => Promise.resolve()\n const writer = new CarWriter([], encoder)\n const out = new CarWriterOut(iterator)\n return { writer, out }\n }\n\n /**\n * Update the list of roots in the header of an existing CAR as represented\n * in a Uint8Array.\n *\n * This operation is an _overwrite_, the total length of the CAR will not be\n * modified. A rejection will occur if the new header will not be the same\n * length as the existing header, in which case the CAR will not be modified.\n * It is the responsibility of the user to ensure that the roots being\n * replaced encode as the same length as the new roots.\n *\n * The byte array passed in an argument will be modified and also returned\n * upon successful modification.\n *\n * @async\n * @static\n * @memberof CarWriter\n * @param {Uint8Array} bytes\n * @param {CID[]} roots - A new list of roots to replace the existing list in\n * the CAR header. The new header must take up the same number of bytes as the\n * existing header, so the roots should collectively be the same byte length\n * as the existing roots.\n * @returns {Promise<Uint8Array>}\n */\n static async updateRootsInBytes (bytes, roots) {\n const reader = bytesReader(bytes)\n await readHeader(reader)\n const newHeader = createHeader(roots)\n if (Number(reader.pos) !== newHeader.length) {\n throw new Error(`updateRoots() can only overwrite a header of the same length (old header is ${reader.pos} bytes, new header is ${newHeader.length} bytes)`)\n }\n bytes.set(newHeader, 0)\n return bytes\n }\n}\n\n/**\n * @class\n * @implements {AsyncIterable<Uint8Array>}\n */\nexport class CarWriterOut {\n /**\n * @param {AsyncIterator<Uint8Array>} iterator\n */\n constructor (iterator) {\n this._iterator = iterator\n }\n\n [Symbol.asyncIterator] () {\n if (this._iterating) {\n throw new Error('Multiple iterator not supported')\n }\n this._iterating = true\n return this._iterator\n }\n}\n\nfunction encodeWriter () {\n /** @type {IteratorChannel} */\n const iw = iteratorChannel()\n const { writer, iterator } = iw\n const encoder = createEncoder(writer)\n return { encoder, iterator }\n}\n\n/**\n * @private\n * @param {CID[] | CID | void} roots\n * @returns {CID[]}\n */\nfunction toRoots (roots) {\n if (roots === undefined) {\n return []\n }\n\n if (!Array.isArray(roots)) {\n const cid = CID.asCID(roots)\n if (!cid) {\n throw new TypeError('roots must be a single CID or an array of CIDs')\n }\n return [cid]\n }\n\n const _roots = []\n for (const root of roots) {\n const _root = CID.asCID(root)\n if (!_root) {\n throw new TypeError('roots must be a single CID or an array of CIDs')\n }\n _roots.push(_root)\n }\n return _roots\n}\n\nexport const __browser = true\n", "/**\n * @packageDocumentation\n *\n * Mostly useful for tests or when you want to be explicit about consuming an iterable without doing anything with any yielded values.\n *\n * @example\n *\n * ```javascript\n * import drain from 'it-drain'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * drain(values)\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import drain from 'it-drain'\n *\n * const values = async function * {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * await drain(values())\n * ```\n */\n\nfunction isAsyncIterable <T> (thing: any): thing is AsyncIterable<T> {\n return thing[Symbol.asyncIterator] != null\n}\n\n/**\n * Drains an (async) iterable discarding its' content and does not return\n * anything\n */\nfunction drain (source: Iterable<unknown>): void\nfunction drain (source: Iterable<unknown> | AsyncIterable<unknown>): Promise<void>\nfunction drain (source: Iterable<unknown> | AsyncIterable<unknown>): Promise<void> | void {\n if (isAsyncIterable(source)) {\n return (async () => {\n for await (const _ of source) { } // eslint-disable-line no-empty,@typescript-eslint/no-unused-vars\n })()\n } else {\n for (const _ of source) { } // eslint-disable-line no-empty,@typescript-eslint/no-unused-vars\n }\n}\n\nexport default drain\n", "/**\n * @packageDocumentation\n *\n * Lets you look at the contents of an async iterator and decide what to do\n *\n * @example\n *\n * ```javascript\n * import peekable from 'it-peekable'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const it = peekable(value)\n *\n * const first = it.peek()\n *\n * console.info(first) // 0\n *\n * it.push(first)\n *\n * console.info([...it])\n * // [ 0, 1, 2, 3, 4 ]\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import peekable from 'it-peekable'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const it = peekable(values())\n *\n * const first = await it.peek()\n *\n * console.info(first) // 0\n *\n * it.push(first)\n *\n * console.info(await all(it))\n * // [ 0, 1, 2, 3, 4 ]\n * ```\n */\n\nexport interface Peek <T> {\n peek(): IteratorResult<T, undefined>\n}\n\nexport interface AsyncPeek <T> {\n peek(): Promise<IteratorResult<T, undefined>>\n}\n\nexport interface Push <T> {\n push(value: T): void\n}\n\nexport type Peekable <T> = Iterable<T> & Peek<T> & Push<T> & Iterator<T>\n\nexport type AsyncPeekable <T> = AsyncIterable<T> & AsyncPeek<T> & Push<T> & AsyncIterator<T>\n\nfunction peekable <T> (iterable: Iterable<T>): Peekable<T>\nfunction peekable <T> (iterable: AsyncIterable<T>): AsyncPeekable<T>\nfunction peekable <T> (iterable: Iterable<T> | AsyncIterable<T>): Peekable<T> | AsyncPeekable<T> {\n // @ts-expect-error can't use Symbol.asyncIterator to index iterable since it might be Iterable\n const [iterator, symbol] = iterable[Symbol.asyncIterator] != null\n // @ts-expect-error can't use Symbol.asyncIterator to index iterable since it might be Iterable\n ? [iterable[Symbol.asyncIterator](), Symbol.asyncIterator]\n // @ts-expect-error can't use Symbol.iterator to index iterable since it might be AsyncIterable\n : [iterable[Symbol.iterator](), Symbol.iterator]\n\n const queue: any[] = []\n\n // @ts-expect-error can't use symbol to index peekable\n return {\n peek: () => {\n return iterator.next()\n },\n push: (value: any) => {\n queue.push(value)\n },\n next: () => {\n if (queue.length > 0) {\n return {\n done: false,\n value: queue.shift()\n }\n }\n\n return iterator.next()\n },\n [symbol] () {\n return this\n }\n }\n}\n\nexport default peekable\n", "/**\n * @packageDocumentation\n *\n * Convert one value from an (async)iterator into another.\n *\n * @example\n *\n * ```javascript\n * import map from 'it-map'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const result = map(values, (val, index) => val++)\n *\n * console.info(result) // [1, 2, 3, 4, 5]\n * ```\n *\n * Async sources and transforms must be awaited:\n *\n * ```javascript\n * import map from 'it-map'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const result = await map(values(), async (val, index) => val++)\n *\n * console.info(result) // [1, 2, 3, 4, 5]\n * ```\n */\n\nimport peek from 'it-peekable'\n\nfunction isAsyncIterable <T> (thing: any): thing is AsyncIterable<T> {\n return thing[Symbol.asyncIterator] != null\n}\n\n/**\n * Takes an (async) iterable and returns one with each item mapped by the passed\n * function\n */\nfunction map <I, O> (source: Iterable<I>, func: (val: I, index: number) => Promise<O>): AsyncGenerator<O, void, undefined>\nfunction map <I, O> (source: Iterable<I>, func: (val: I, index: number) => O): Generator<O, void, undefined>\nfunction map <I, O> (source: AsyncIterable<I> | Iterable<I>, func: (val: I, index: number) => O | Promise<O>): AsyncGenerator<O, void, undefined>\nfunction map <I, O> (source: AsyncIterable<I> | Iterable<I>, func: (val: I, index: number) => O | Promise<O>): AsyncGenerator<O, void, undefined> | Generator<O, void, undefined> {\n let index = 0\n\n if (isAsyncIterable(source)) {\n return (async function * () {\n for await (const val of source) {\n yield func(val, index++)\n }\n })()\n }\n\n // if mapping function returns a promise we have to return an async generator\n const peekable = peek(source)\n const { value, done } = peekable.next()\n\n if (done === true) {\n return (function * () {}())\n }\n\n const res = func(value, index++)\n\n // @ts-expect-error .then is not present on O\n if (typeof res.then === 'function') {\n return (async function * () {\n yield await res\n\n for (const val of peekable) {\n yield func(val, index++)\n }\n })()\n }\n\n const fn = func as (val: I, index: number) => O\n\n return (function * () {\n yield res as O\n\n for (const val of peekable) {\n yield fn(val, index++)\n }\n })()\n}\n\nexport default map\n", "import * as Digest from './digest.js'\nimport type { MultihashHasher } from './interface.js'\n\ntype Await<T> = Promise<T> | T\n\nexport function from <Name extends string, Code extends number> ({ name, code, encode }: { name: Name, code: Code, encode(input: Uint8Array): Await<Uint8Array> }): Hasher<Name, Code> {\n return new Hasher(name, code, encode)\n}\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher<Name extends string, Code extends number> implements MultihashHasher<Code> {\n readonly name: Name\n readonly code: Code\n readonly encode: (input: Uint8Array) => Await<Uint8Array>\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await<Uint8Array>) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n digest (input: Uint8Array): Await<Digest.Digest<Code, number>> {\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 } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n", "import { bytes as binary, CID } from './index.js'\nimport type * as API from './interface.js'\n\nfunction readonly ({ enumerable = true, configurable = false } = {}): { enumerable: boolean, configurable: boolean, writable: false } {\n return { enumerable, configurable, writable: false }\n}\n\nfunction * linksWithin (path: [string | number, string], value: any): Iterable<[string, CID]> {\n if (value != null && typeof value === 'object') {\n if (Array.isArray(value)) {\n for (const [index, element] of value.entries()) {\n const elementPath = [...path, index]\n const cid = CID.asCID(element)\n if (cid != null) {\n yield [elementPath.join('/'), cid]\n } else if (typeof element === 'object') {\n yield * links(element, elementPath)\n }\n }\n } else {\n const cid = CID.asCID(value)\n if (cid != null) {\n yield [path.join('/'), cid]\n } else {\n yield * links(value, path)\n }\n }\n }\n}\n\nfunction * links <T> (source: T, base: Array<string | number>): Iterable<[string, CID]> {\n if (source == null || source instanceof Uint8Array) {\n return\n }\n const cid = CID.asCID(source)\n if (cid != null) {\n yield [base.join('/'), cid]\n }\n for (const [key, value] of Object.entries(source)) {\n const path = [...base, key] as [string | number, string]\n yield * linksWithin(path, value)\n }\n}\n\nfunction * treeWithin (path: [string | number, string], value: any): Iterable<string> {\n if (Array.isArray(value)) {\n for (const [index, element] of value.entries()) {\n const elementPath = [...path, index]\n yield elementPath.join('/')\n if (typeof element === 'object' && (CID.asCID(element) == null)) {\n yield * tree(element, elementPath)\n }\n }\n } else {\n yield * tree(value, path)\n }\n}\n\nfunction * tree <T> (source: T, base: Array<string | number>): Iterable<string> {\n if (source == null || typeof source !== 'object') {\n return\n }\n for (const [key, value] of Object.entries(source)) {\n const path = [...base, key] as [string | number, string]\n yield path.join('/')\n if (value != null && !(value instanceof Uint8Array) && typeof value === 'object' && (CID.asCID(value) == null)) {\n yield * treeWithin(path, value)\n }\n }\n}\n\nfunction get <T> (source: T, path: string[]): API.BlockCursorView<unknown> {\n let node = source as Record<string, any>\n for (const [index, key] of path.entries()) {\n node = node[key]\n if (node == null) {\n throw new Error(`Object has no property at ${path.slice(0, index + 1).map(part => `[${JSON.stringify(part)}]`).join('')}`)\n }\n const cid = CID.asCID(node)\n if (cid != null) {\n return { value: cid, remaining: path.slice(index + 1).join('/') }\n }\n }\n return { value: node }\n}\n\n/**\n * @template T - Logical type of the data encoded in the block\n * @template C - multicodec code corresponding to codec used to encode the block\n * @template A - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @template V - CID version\n */\nexport class Block<T, C extends number, A extends number, V extends API.Version> implements API.BlockView<T, C, A, V> {\n readonly cid: CID<T, C, A, V>\n readonly bytes: API.ByteView<T>\n readonly value: T\n readonly asBlock: this\n\n constructor ({ cid, bytes, value }: { cid: CID<T, C, A, V>, bytes: API.ByteView<T>, value: T }) {\n if (cid == null || bytes == null || typeof value === 'undefined') { throw new Error('Missing required argument') }\n\n this.cid = cid\n this.bytes = bytes\n this.value = value\n this.asBlock = this\n\n // Mark all the properties immutable\n Object.defineProperties(this, {\n cid: readonly(),\n bytes: readonly(),\n value: readonly(),\n asBlock: readonly()\n })\n }\n\n links (): Iterable<[string, CID<unknown, number, number, API.Version>]> {\n return links(this.value, [])\n }\n\n tree (): Iterable<string> {\n return tree(this.value, [])\n }\n\n get (path = '/'): API.BlockCursorView<unknown> {\n return get(this.value, path.split('/').filter(Boolean))\n }\n}\n\ninterface EncodeInput <T, Code extends number, Alg extends number> {\n value: T\n codec: API.BlockEncoder<Code, T>\n hasher: API.MultihashHasher<Alg>\n}\n\n/**\n * @template T - Logical type of the data encoded in the block\n * @template Code - multicodec code corresponding to codec used to encode the block\n * @template Alg - multicodec code corresponding to the hashing algorithm used in CID creation.\n */\nexport async function encode <T, Code extends number, Alg extends number> ({ value, codec, hasher }: EncodeInput<T, Code, Alg>): Promise<API.BlockView<T, Code, Alg>> {\n if (typeof value === 'undefined') { throw new Error('Missing required argument \"value\"') }\n if (codec == null || hasher == null) { throw new Error('Missing required argument: codec or hasher') }\n\n const bytes = codec.encode(value)\n const hash = await hasher.digest(bytes)\n\n const cid = CID.create(\n 1,\n codec.code,\n hash\n ) as CID<T, Code, Alg, 1>\n\n return new Block({ value, bytes, cid })\n}\n\ninterface DecodeInput <T, Code extends number, Alg extends number> {\n bytes: API.ByteView<T>\n codec: API.BlockDecoder<Code, T>\n hasher: API.MultihashHasher<Alg>\n}\n\n/**\n * @template T - Logical type of the data encoded in the block\n * @template Code - multicodec code corresponding to codec used to encode the block\n * @template Alg - multicodec code corresponding to the hashing algorithm used in CID creation.\n */\nexport async function decode <T, Code extends number, Alg extends number> ({ bytes, codec, hasher }: DecodeInput<T, Code, Alg>): Promise<API.BlockView<T, Code, Alg>> {\n if (bytes == null) { throw new Error('Missing required argument \"bytes\"') }\n if (codec == null || hasher == null) { throw new Error('Missing required argument: codec or hasher') }\n\n const value = codec.decode(bytes)\n const hash = await hasher.digest(bytes)\n\n const cid = CID.create(1, codec.code, hash) as CID<T, Code, Alg, 1>\n\n return new Block({ value, bytes, cid })\n}\n\ntype CreateUnsafeInput <T, Code extends number, Alg extends number, V extends API.Version> = {\n cid: API.Link<T, Code, Alg, V>\n value: T\n codec?: API.BlockDecoder<Code, T>\n bytes: API.ByteView<T>\n} | {\n cid: API.Link<T, Code, Alg, V>\n value?: undefined\n codec: API.BlockDecoder<Code, T>\n bytes: API.ByteView<T>\n}\n\n/**\n * @template T - Logical type of the data encoded in the block\n * @template Code - multicodec code corresponding to codec used to encode the block\n * @template Alg - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @template V - CID version\n */\nexport function createUnsafe <T, Code extends number, Alg extends number, V extends API.Version> ({ bytes, cid, value: maybeValue, codec }: CreateUnsafeInput<T, Code, Alg, V>): API.BlockView<T, Code, Alg, V> {\n const value = maybeValue !== undefined\n ? maybeValue\n : (codec?.decode(bytes))\n\n if (value === undefined) { throw new Error('Missing required argument, must either provide \"value\" or \"codec\"') }\n\n return new Block({\n cid: cid as CID<T, Code, Alg, V>,\n bytes,\n value\n })\n}\n\ninterface CreateInput <T, Code extends number, Alg extends number, V extends API.Version> {\n bytes: API.ByteView<T>\n cid: API.Link<T, Code, Alg, V>\n hasher: API.MultihashHasher<Alg>\n codec: API.BlockDecoder<Code, T>\n}\n\n/**\n * @template T - Logical type of the data encoded in the block\n * @template Code - multicodec code corresponding to codec used to encode the block\n * @template Alg - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @template V - CID version\n */\nexport async function create <T, Code extends number, Alg extends number, V extends API.Version> ({ bytes, cid, hasher, codec }: CreateInput<T, Code, Alg, V>): Promise<API.BlockView<T, Code, Alg, V>> {\n if (bytes == null) { throw new Error('Missing required argument \"bytes\"') }\n if (hasher == null) { throw new Error('Missing required argument \"hasher\"') }\n const value = codec.decode(bytes)\n const hash = await hasher.digest(bytes)\n if (!binary.equals(cid.multihash.bytes, hash.bytes)) {\n throw new Error('CID hash does not match bytes')\n }\n\n return createUnsafe({\n bytes,\n cid,\n value,\n codec\n })\n}\n", "export default function pDefer() {\n\tconst deferred = {};\n\n\tdeferred.promise = new Promise((resolve, reject) => {\n\t\tdeferred.resolve = resolve;\n\t\tdeferred.reject = reject;\n\t});\n\n\treturn deferred;\n}\n", "import EventEmitter from './index.js'\n\nexport { EventEmitter }\nexport default EventEmitter\n", "export class TimeoutError extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = 'TimeoutError';\n\t}\n}\n\n/**\nAn error to be thrown when the request is aborted by AbortController.\nDOMException is thrown instead of this Error when DOMException is available.\n*/\nexport class AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\n/**\nTODO: Remove AbortError and just throw DOMException when targeting Node 18.\n*/\nconst getDOMException = errorMessage => globalThis.DOMException === undefined\n\t? new AbortError(errorMessage)\n\t: new DOMException(errorMessage);\n\n/**\nTODO: Remove below function and just 'reject(signal.reason)' when targeting Node 18.\n*/\nconst getAbortedReason = signal => {\n\tconst reason = signal.reason === undefined\n\t\t? getDOMException('This operation was aborted.')\n\t\t: signal.reason;\n\n\treturn reason instanceof Error ? reason : getDOMException(reason);\n};\n\nexport default function pTimeout(promise, options) {\n\tconst {\n\t\tmilliseconds,\n\t\tfallback,\n\t\tmessage,\n\t\tcustomTimers = {setTimeout, clearTimeout},\n\t} = options;\n\n\tlet timer;\n\tlet abortHandler;\n\n\tconst wrappedPromise = new Promise((resolve, reject) => {\n\t\tif (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {\n\t\t\tthrow new TypeError(`Expected \\`milliseconds\\` to be a positive number, got \\`${milliseconds}\\``);\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\tconst {signal} = options;\n\t\t\tif (signal.aborted) {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t}\n\n\t\t\tabortHandler = () => {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t};\n\n\t\t\tsignal.addEventListener('abort', abortHandler, {once: true});\n\t\t}\n\n\t\tif (milliseconds === Number.POSITIVE_INFINITY) {\n\t\t\tpromise.then(resolve, reject);\n\t\t\treturn;\n\t\t}\n\n\t\t// We create the error outside of `setTimeout` to preserve the stack trace.\n\t\tconst timeoutError = new TimeoutError();\n\n\t\ttimer = customTimers.setTimeout.call(undefined, () => {\n\t\t\tif (fallback) {\n\t\t\t\ttry {\n\t\t\t\t\tresolve(fallback());\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (typeof promise.cancel === 'function') {\n\t\t\t\tpromise.cancel();\n\t\t\t}\n\n\t\t\tif (message === false) {\n\t\t\t\tresolve();\n\t\t\t} else if (message instanceof Error) {\n\t\t\t\treject(message);\n\t\t\t} else {\n\t\t\t\ttimeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;\n\t\t\t\treject(timeoutError);\n\t\t\t}\n\t\t}, milliseconds);\n\n\t\t(async () => {\n\t\t\ttry {\n\t\t\t\tresolve(await promise);\n\t\t\t} catch (error) {\n\t\t\t\treject(error);\n\t\t\t}\n\t\t})();\n\t});\n\n\tconst cancelablePromise = wrappedPromise.finally(() => {\n\t\tcancelablePromise.clear();\n\t\tif (abortHandler && options.signal) {\n\t\t\toptions.signal.removeEventListener('abort', abortHandler);\n\t\t}\n\t});\n\n\tcancelablePromise.clear = () => {\n\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\ttimer = undefined;\n\t};\n\n\treturn cancelablePromise;\n}\n", "// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound\n// Used to compute insertion index to keep queue sorted after insertion\nexport default function lowerBound(array, value, comparator) {\n let first = 0;\n let count = array.length;\n while (count > 0) {\n const step = Math.trunc(count / 2);\n let it = first + step;\n if (comparator(array[it], value) <= 0) {\n first = ++it;\n count -= step + 1;\n }\n else {\n count = step;\n }\n }\n return first;\n}\n", "import lowerBound from './lower-bound.js';\nexport default class PriorityQueue {\n #queue = [];\n enqueue(run, options) {\n options = {\n priority: 0,\n ...options,\n };\n const element = {\n priority: options.priority,\n id: options.id,\n run,\n };\n if (this.size === 0 || this.#queue[this.size - 1].priority >= options.priority) {\n this.#queue.push(element);\n return;\n }\n const index = lowerBound(this.#queue, element, (a, b) => b.priority - a.priority);\n this.#queue.splice(index, 0, element);\n }\n setPriority(id, priority) {\n const index = this.#queue.findIndex((element) => element.id === id);\n if (index === -1) {\n throw new ReferenceError(`No promise function with the id \"${id}\" exists in the queue.`);\n }\n const [item] = this.#queue.splice(index, 1);\n this.enqueue(item.run, { priority, id });\n }\n dequeue() {\n const item = this.#queue.shift();\n return item?.run;\n }\n filter(options) {\n return this.#queue.filter((element) => element.priority === options.priority).map((element) => element.run);\n }\n get size() {\n return this.#queue.length;\n }\n}\n", "import { EventEmitter } from 'eventemitter3';\nimport pTimeout, { TimeoutError } from 'p-timeout';\nimport PriorityQueue from './priority-queue.js';\n/**\nPromise queue with concurrency control.\n*/\nexport default class PQueue extends EventEmitter {\n #carryoverConcurrencyCount;\n #isIntervalIgnored;\n #intervalCount = 0;\n #intervalCap;\n #interval;\n #intervalEnd = 0;\n #intervalId;\n #timeoutId;\n #queue;\n #queueClass;\n #pending = 0;\n // The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194\n #concurrency;\n #isPaused;\n #throwOnTimeout;\n // Use to assign a unique identifier to a promise function, if not explicitly specified\n #idAssigner = 1n;\n /**\n Per-operation timeout in milliseconds. Operations fulfill once `timeout` elapses if they haven't already.\n\n Applies to each future operation.\n */\n timeout;\n // TODO: The `throwOnTimeout` option should affect the return types of `add()` and `addAll()`\n constructor(options) {\n super();\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n options = {\n carryoverConcurrencyCount: false,\n intervalCap: Number.POSITIVE_INFINITY,\n interval: 0,\n concurrency: Number.POSITIVE_INFINITY,\n autoStart: true,\n queueClass: PriorityQueue,\n ...options,\n };\n if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) {\n throw new TypeError(`Expected \\`intervalCap\\` to be a number from 1 and up, got \\`${options.intervalCap?.toString() ?? ''}\\` (${typeof options.intervalCap})`);\n }\n if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) {\n throw new TypeError(`Expected \\`interval\\` to be a finite number >= 0, got \\`${options.interval?.toString() ?? ''}\\` (${typeof options.interval})`);\n }\n this.#carryoverConcurrencyCount = options.carryoverConcurrencyCount;\n this.#isIntervalIgnored = options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0;\n this.#intervalCap = options.intervalCap;\n this.#interval = options.interval;\n this.#queue = new options.queueClass();\n this.#queueClass = options.queueClass;\n this.concurrency = options.concurrency;\n this.timeout = options.timeout;\n this.#throwOnTimeout = options.throwOnTimeout === true;\n this.#isPaused = options.autoStart === false;\n }\n get #doesIntervalAllowAnother() {\n return this.#isIntervalIgnored || this.#intervalCount < this.#intervalCap;\n }\n get #doesConcurrentAllowAnother() {\n return this.#pending < this.#concurrency;\n }\n #next() {\n this.#pending--;\n this.#tryToStartAnother();\n this.emit('next');\n }\n #onResumeInterval() {\n this.#onInterval();\n this.#initializeIntervalIfNeeded();\n this.#timeoutId = undefined;\n }\n get #isIntervalPaused() {\n const now = Date.now();\n if (this.#intervalId === undefined) {\n const delay = this.#intervalEnd - now;\n if (delay < 0) {\n // Act as the interval was done\n // We don't need to resume it here because it will be resumed on line 160\n this.#intervalCount = (this.#carryoverConcurrencyCount) ? this.#pending : 0;\n }\n else {\n // Act as the interval is pending\n if (this.#timeoutId === undefined) {\n this.#timeoutId = setTimeout(() => {\n this.#onResumeInterval();\n }, delay);\n }\n return true;\n }\n }\n return false;\n }\n #tryToStartAnother() {\n if (this.#queue.size === 0) {\n // We can clear the interval (\"pause\")\n // Because we can redo it later (\"resume\")\n if (this.#intervalId) {\n clearInterval(this.#intervalId);\n }\n this.#intervalId = undefined;\n this.emit('empty');\n if (this.#pending === 0) {\n this.emit('idle');\n }\n return false;\n }\n if (!this.#isPaused) {\n const canInitializeInterval = !this.#isIntervalPaused;\n if (this.#doesIntervalAllowAnother && this.#doesConcurrentAllowAnother) {\n const job = this.#queue.dequeue();\n if (!job) {\n return false;\n }\n this.emit('active');\n job();\n if (canInitializeInterval) {\n this.#initializeIntervalIfNeeded();\n }\n return true;\n }\n }\n return false;\n }\n #initializeIntervalIfNeeded() {\n if (this.#isIntervalIgnored || this.#intervalId !== undefined) {\n return;\n }\n this.#intervalId = setInterval(() => {\n this.#onInterval();\n }, this.#interval);\n this.#intervalEnd = Date.now() + this.#interval;\n }\n #onInterval() {\n if (this.#intervalCount === 0 && this.#pending === 0 && this.#intervalId) {\n clearInterval(this.#intervalId);\n this.#intervalId = undefined;\n }\n this.#intervalCount = this.#carryoverConcurrencyCount ? this.#pending : 0;\n this.#processQueue();\n }\n /**\n Executes all queued functions until it reaches the limit.\n */\n #processQueue() {\n // eslint-disable-next-line no-empty\n while (this.#tryToStartAnother()) { }\n }\n get concurrency() {\n return this.#concurrency;\n }\n set concurrency(newConcurrency) {\n if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) {\n throw new TypeError(`Expected \\`concurrency\\` to be a number from 1 and up, got \\`${newConcurrency}\\` (${typeof newConcurrency})`);\n }\n this.#concurrency = newConcurrency;\n this.#processQueue();\n }\n async #throwOnAbort(signal) {\n return new Promise((_resolve, reject) => {\n signal.addEventListener('abort', () => {\n reject(signal.reason);\n }, { once: true });\n });\n }\n /**\n Updates the priority of a promise function by its id, affecting its execution order. Requires a defined concurrency limit to take effect.\n\n For example, this can be used to prioritize a promise function to run earlier.\n\n ```js\n import PQueue from 'p-queue';\n\n const queue = new PQueue({concurrency: 1});\n\n queue.add(async () => '\uD83E\uDD84', {priority: 1});\n queue.add(async () => '\uD83E\uDD80', {priority: 0, id: '\uD83E\uDD80'});\n queue.add(async () => '\uD83E\uDD84', {priority: 1});\n queue.add(async () => '\uD83E\uDD84', {priority: 1});\n\n queue.setPriority('\uD83E\uDD80', 2);\n ```\n\n In this case, the promise function with `id: '\uD83E\uDD80'` runs second.\n\n You can also deprioritize a promise function to delay its execution:\n\n ```js\n import PQueue from 'p-queue';\n\n const queue = new PQueue({concurrency: 1});\n\n queue.add(async () => '\uD83E\uDD84', {priority: 1});\n queue.add(async () => '\uD83E\uDD80', {priority: 1, id: '\uD83E\uDD80'});\n queue.add(async () => '\uD83E\uDD84');\n queue.add(async () => '\uD83E\uDD84', {priority: 0});\n\n queue.setPriority('\uD83E\uDD80', -1);\n ```\n Here, the promise function with `id: '\uD83E\uDD80'` executes last.\n */\n setPriority(id, priority) {\n this.#queue.setPriority(id, priority);\n }\n async add(function_, options = {}) {\n // In case `id` is not defined.\n options.id ??= (this.#idAssigner++).toString();\n options = {\n timeout: this.timeout,\n throwOnTimeout: this.#throwOnTimeout,\n ...options,\n };\n return new Promise((resolve, reject) => {\n this.#queue.enqueue(async () => {\n this.#pending++;\n this.#intervalCount++;\n try {\n options.signal?.throwIfAborted();\n let operation = function_({ signal: options.signal });\n if (options.timeout) {\n operation = pTimeout(Promise.resolve(operation), { milliseconds: options.timeout });\n }\n if (options.signal) {\n operation = Promise.race([operation, this.#throwOnAbort(options.signal)]);\n }\n const result = await operation;\n resolve(result);\n this.emit('completed', result);\n }\n catch (error) {\n if (error instanceof TimeoutError && !options.throwOnTimeout) {\n resolve();\n return;\n }\n reject(error);\n this.emit('error', error);\n }\n finally {\n this.#next();\n }\n }, options);\n this.emit('add');\n this.#tryToStartAnother();\n });\n }\n async addAll(functions, options) {\n return Promise.all(functions.map(async (function_) => this.add(function_, options)));\n }\n /**\n Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.)\n */\n start() {\n if (!this.#isPaused) {\n return this;\n }\n this.#isPaused = false;\n this.#processQueue();\n return this;\n }\n /**\n Put queue execution on hold.\n */\n pause() {\n this.#isPaused = true;\n }\n /**\n Clear the queue.\n */\n clear() {\n this.#queue = new this.#queueClass();\n }\n /**\n Can be called multiple times. Useful if you for example add additional items at a later time.\n\n @returns A promise that settles when the queue becomes empty.\n */\n async onEmpty() {\n // Instantly resolve if the queue is empty\n if (this.#queue.size === 0) {\n return;\n }\n await this.#onEvent('empty');\n }\n /**\n @returns A promise that settles when the queue size is less than the given limit: `queue.size < limit`.\n\n If you want to avoid having the queue grow beyond a certain size you can `await queue.onSizeLessThan()` before adding a new item.\n\n Note that this only limits the number of items waiting to start. There could still be up to `concurrency` jobs already running that this call does not include in its calculation.\n */\n async onSizeLessThan(limit) {\n // Instantly resolve if the queue is empty.\n if (this.#queue.size < limit) {\n return;\n }\n await this.#onEvent('next', () => this.#queue.size < limit);\n }\n /**\n The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet.\n\n @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle() {\n // Instantly resolve if none pending and if nothing else is queued\n if (this.#pending === 0 && this.#queue.size === 0) {\n return;\n }\n await this.#onEvent('idle');\n }\n async #onEvent(event, filter) {\n return new Promise(resolve => {\n const listener = () => {\n if (filter && !filter()) {\n return;\n }\n this.off(event, listener);\n resolve();\n };\n this.on(event, listener);\n });\n }\n /**\n Size of the queue, the number of queued items waiting to run.\n */\n get size() {\n return this.#queue.size;\n }\n /**\n Size of the queue, filtered by the given options.\n\n For example, this can be used to find the number of items remaining in the queue with a specific priority level.\n */\n sizeBy(options) {\n // eslint-disable-next-line unicorn/no-array-callback-reference\n return this.#queue.filter(options).length;\n }\n /**\n Number of running items (no longer in the queue).\n */\n get pending() {\n return this.#pending;\n }\n /**\n Whether the queue is currently paused.\n */\n get isPaused() {\n return this.#isPaused;\n }\n}\n", "import type { ExportStrategy } from '../index.js'\nimport type { BlockView } from 'multiformats/block/interface'\nimport type { CID } from 'multiformats/cid'\n\n/**\n * Traverses the DAG breadth-first starting at the target CID and yields all\n * encountered blocks.\n *\n * Blocks linked to from the target block are traversed using codecs defined in\n * the helia config.\n */\nexport class SubgraphExporter implements ExportStrategy {\n async * export (_cid: CID, block: BlockView<any, any, any, 0 | 1>): AsyncGenerator<CID, void, undefined> {\n for (const [, linkedCid] of block.links()) {\n yield linkedCid\n }\n }\n}\n", "import type { TraversalStrategy } from '../index.js'\nimport type { BlockView } from 'multiformats/block/interface'\nimport type { CID } from 'multiformats/cid'\n\n/**\n * A traversal strategy that performs a breadth-first search (so as to not load blocks unnecessarily) looking for a\n * target CID. Traversal stops when we reach the target CID or run out of nodes.\n */\nexport class GraphSearch implements TraversalStrategy {\n private readonly target: CID\n\n constructor (target: CID) {\n this.target = target\n }\n\n isTarget (cid: CID): boolean {\n return this.target.equals(cid)\n }\n\n async * traverse <T extends BlockView<any, any, any, 0 | 1>>(cid: CID, block: T): AsyncGenerator<CID, void, undefined> {\n for (const [, linkedCid] of block.links()) {\n yield linkedCid\n }\n }\n}\n", "import { CarWriter } from '@ipld/car'\nimport drain from 'it-drain'\nimport map from 'it-map'\nimport { createUnsafe } from 'multiformats/block'\nimport defer from 'p-defer'\nimport PQueue from 'p-queue'\nimport { DAG_WALK_QUEUE_CONCURRENCY } from './constants.js'\nimport { SubgraphExporter } from './export-strategies/subgraph-exporter.js'\nimport { GraphSearch } from './traversal-strategies/graph-search.js'\nimport type { CarComponents, Car as CarInterface, ExportCarOptions, ExportStrategy, TraversalStrategy } from './index.js'\nimport type { PutManyBlocksProgressEvents } from '@helia/interface/blocks'\nimport type { CarReader } from '@ipld/car'\nimport type { AbortOptions, Logger } from '@libp2p/interface'\nimport type { CID } from 'multiformats/cid'\nimport type { ProgressOptions } from 'progress-events'\n\n/**\n * Context for the traversal process.\n */\ninterface TraversalContext {\n currentPath: CID[]\n pathsToTarget: CID[][] | null // collect all target paths\n}\n\ninterface WalkDagContext<Strategy> {\n cid: CID\n queue: PQueue\n strategy: Strategy\n options?: ExportCarOptions\n}\n\ninterface ExportWalkDagContext extends WalkDagContext<ExportStrategy> {\n writer: Pick<CarWriter, 'put'>\n recursive?: boolean\n}\n\ninterface TraversalWalkDagContext extends WalkDagContext<TraversalStrategy> {\n traversalContext: TraversalContext\n parentPath: CID[]\n}\n\nexport class Car implements CarInterface {\n private readonly components: CarComponents\n private readonly log: Logger\n\n constructor (components: CarComponents, init: any) {\n this.components = components\n this.log = components.logger.forComponent('helia:car')\n }\n\n async import (reader: Pick<CarReader, 'blocks'>, options?: AbortOptions & ProgressOptions<PutManyBlocksProgressEvents>): Promise<void> {\n await drain(this.components.blockstore.putMany(\n map(reader.blocks(), ({ cid, bytes }) => ({ cid, block: bytes })),\n options\n ))\n }\n\n async export (root: CID | CID[], writer: Pick<CarWriter, 'put' | 'close'>, options?: ExportCarOptions): Promise<void> {\n const deferred = defer<Error | undefined>()\n const roots = Array.isArray(root) ? root : [root]\n\n // Create traversal-specific context\n const traversalContext: TraversalContext = {\n currentPath: [],\n pathsToTarget: null\n }\n\n const traversalStrategy = options?.traversal\n const exportStrategy = options?.exporter ?? new SubgraphExporter()\n\n // use a queue to walk the DAG instead of recursion so we can traverse very\n // large DAGs\n const queue = new PQueue({\n concurrency: DAG_WALK_QUEUE_CONCURRENCY\n })\n\n let startedExport = false\n queue.on('idle', () => {\n if (startedExport) {\n // idle event was called, and started exporting, so we are done.\n deferred.resolve()\n } else if (!startedExport && traversalContext.pathsToTarget?.length === roots.length) {\n // queue is idle, we haven't started exporting yet, and we have path(s)\n // to the target(s), so we can start the export process.\n this.log.trace('starting export of blocks to the car file')\n startedExport = true\n\n for (const path of traversalContext.pathsToTarget) {\n const targetIndex = path.length - 1\n const targetCid = path[targetIndex]\n\n // Process all verification blocks in the path except the target\n path.slice(0, -1).forEach(cid => {\n void queue.add(async () => {\n await this.#exportDagNode({ cid, queue, writer, strategy: exportStrategy, options, recursive: false })\n })\n .catch((err) => {\n this.log.error('error during queue operation - %e', err)\n })\n })\n\n // Process the target block (which will recursively export its DAG)\n void queue.add(async () => {\n await this.#exportDagNode({ cid: targetCid, queue, writer, strategy: exportStrategy, options })\n })\n .catch((err) => {\n this.log.error('error during queue operation - %e', err)\n })\n }\n } else {\n // queue is idle, we haven't started exporting yet, and we don't have\n // path(s) to the target(s), so we can't start the export process.\n // this should not happen without a separate error during traversal, but\n // we'll handle it here anyway.\n this.log.trace('no paths to target, skipping export')\n deferred.reject(new Error('Could not traverse to target CID(s)'))\n }\n })\n queue.on('error', (err) => {\n queue.clear()\n deferred.reject(err)\n })\n\n for (const root of roots) {\n void queue.add(async () => {\n this.log.trace('traversing dag from %c', root)\n await this.#traverseDagNode({ cid: root, queue, strategy: traversalStrategy ?? new GraphSearch(root), traversalContext, parentPath: [], options })\n })\n .catch((err) => {\n this.log.error('error during queue operation - %e', err)\n })\n }\n\n // wait for the writer to end\n try {\n await deferred.promise\n } finally {\n await writer.close()\n }\n }\n\n async * stream (root: CID | CID[], options?: ExportCarOptions): AsyncGenerator<Uint8Array, void, undefined> {\n const { writer, out } = CarWriter.create(root)\n\n // has to be done async so we write to `writer` and read from `out` at the\n // same time\n this.export(root, writer, options)\n .catch((err) => {\n this.log.error('error during streaming export - %e', err)\n })\n\n for await (const buf of out) {\n yield buf\n }\n }\n\n /**\n * Traverse a DAG and stop when we reach the target node\n */\n async #traverseDagNode ({ cid, queue, strategy, traversalContext, parentPath, options }: TraversalWalkDagContext): Promise<void> {\n // if we are traversing, we need to gather path(s) to the target(s)\n const currentPath = [...parentPath, cid]\n\n if (strategy.isTarget(cid)) {\n traversalContext.pathsToTarget = traversalContext.pathsToTarget ?? []\n traversalContext.pathsToTarget.push([...currentPath])\n this.log.trace('found path to target %c', cid)\n return\n }\n\n const codec = await this.components.getCodec(cid.code)\n const bytes = await this.components.blockstore.get(cid, options)\n\n // we are recursively traversing the dag\n const decodedBlock = createUnsafe({ bytes, cid, codec })\n\n for await (const nextCid of strategy.traverse(cid, decodedBlock)) {\n void queue.add(async () => {\n await this.#traverseDagNode({ cid: nextCid, queue, strategy, traversalContext, parentPath: currentPath ?? [], options })\n })\n .catch((err) => {\n this.log.error('error during traversal queue operation - %e', err)\n })\n }\n }\n\n /**\n * Use an ExportStrategy to export part of all of a DAG\n */\n async #exportDagNode ({ cid, queue, writer, strategy, options, recursive = true }: ExportWalkDagContext): Promise<void> {\n if (options?.blockFilter?.has(cid.multihash.bytes) === true) {\n return\n }\n\n const codec = await this.components.getCodec(cid.code)\n const bytes = await this.components.blockstore.get(cid, options)\n\n // Mark as processed\n options?.blockFilter?.add(cid.multihash.bytes)\n\n // Write to CAR\n await writer.put({ cid, bytes })\n\n if (recursive) {\n // we are recursively traversing the dag\n const decodedBlock = createUnsafe({ bytes, cid, codec })\n\n for await (const nextCid of strategy.export(cid, decodedBlock)) {\n void queue.add(async () => {\n await this.#exportDagNode({ cid: nextCid, queue, writer, strategy, options })\n })\n .catch((err) => {\n this.log.error('error during export queue operation - %e', err)\n })\n }\n }\n }\n}\n", "import type { ExportStrategy } from '../index.js'\nimport type { BlockView } from 'multiformats/block/interface'\nimport type { CID } from 'multiformats/cid'\n\n/**\n * Yields the first block from the first CID and stops\n */\nexport class BlockExporter implements ExportStrategy {\n async * export (cid: CID, block: BlockView<any, any, any, 0 | 1>): AsyncGenerator<CID, void, undefined> {\n // don't yield the block, index.ts will add it to the car file and then\n // we're done\n }\n}\n", "export class NotUnixFSError extends Error {\n static code = 'ERR_NOT_UNIXFS'\n static message = 'Not a UnixFS node'\n static name = 'NotUnixFSError'\n code = 'ERR_NOT_UNIXFS'\n message = 'Not a UnixFS node'\n name = 'NotUnixFSError'\n}\n", "import { DAG_PB_CODEC_CODE, RAW_PB_CODEC_CODE } from '../constants.js'\nimport { NotUnixFSError } from '../errors.js'\nimport type { ExportStrategy } from '../index.js'\nimport type { BlockView } from 'multiformats/block/interface'\nimport type { CID } from 'multiformats/cid'\n\n/**\n * This exporter is used when you want to generate a car file that contains a\n * single UnixFS file or directory\n */\nexport class UnixFSExporter implements ExportStrategy {\n async * export (cid: CID, block: BlockView<any, any, any, 0 | 1>): AsyncGenerator<CID, void, undefined> {\n if (cid.code !== DAG_PB_CODEC_CODE && cid.code !== RAW_PB_CODEC_CODE) {\n throw new NotUnixFSError('Target CID was not UnixFS - use the SubGraphExporter to export arbitrary graphs')\n }\n\n // yield all the blocks that make up the file or directory\n for (const [, linkedCid] of block.links()) {\n yield linkedCid\n }\n }\n}\n", "import type { TraversalStrategy } from '../index.js'\nimport type { BlockView } from 'multiformats/block/interface'\nimport type { CID } from 'multiformats/cid'\n\n/**\n * Simple strategy that traverses a known path to a target CID.\n *\n * All this strategy does is yield the next CID in the known path.\n */\nexport class CIDPath implements TraversalStrategy {\n private readonly pathToTarget: CID[]\n private readonly target: CID\n\n constructor (pathToTarget: CID[]) {\n this.pathToTarget = pathToTarget\n this.target = pathToTarget[pathToTarget.length - 1]\n }\n\n isTarget (cid: CID): boolean {\n return this.target.equals(cid)\n }\n\n async * traverse <T extends BlockView<any, any, any, 0 | 1>>(cid: CID, _block?: T): AsyncGenerator<CID, void, undefined> {\n const givenCidIndex = this.pathToTarget.indexOf(cid)\n const nextCid = this.pathToTarget[givenCidIndex + 1]\n\n yield nextCid\n }\n}\n", "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/* eslint-disable complexity, no-nested-ternary */\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<T>} ByteView\n */\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ArrayBufferView<T>} 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<T> | ArrayBufferView<T>} buf\n * @returns {ByteView<T>}\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<T>} ByteView\n */\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ArrayBufferView<T>} 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<PBNode>}\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<PBNode> | ArrayBufferView<PBNode>} 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 {\n // ignore parse fail\n }\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", "export class InvalidTypeError extends Error {\n static name = 'InvalidTypeError'\n static code = 'ERR_INVALID_TYPE'\n name = InvalidTypeError.name\n code = InvalidTypeError.code\n\n constructor (message = 'Invalid type') {\n super(message)\n }\n}\n\nexport class InvalidUnixFSMessageError extends Error {\n static name = 'InvalidUnixFSMessageError'\n static code = 'ERR_INVALID_MESSAGE'\n name = InvalidUnixFSMessageError.name\n code = InvalidUnixFSMessageError.code\n\n constructor (message = 'Invalid message') {\n super(message)\n }\n}\n", "/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n", "/* eslint-disable no-fallthrough */\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst N1 = Math.pow(2, 7)\nconst N2 = Math.pow(2, 14)\nconst N3 = Math.pow(2, 21)\nconst N4 = Math.pow(2, 28)\nconst N5 = Math.pow(2, 35)\nconst N6 = Math.pow(2, 42)\nconst N7 = Math.pow(2, 49)\n\n/** Most significant bit of a byte */\nconst MSB = 0x80\n/** Rest of the bits in a byte */\nconst REST = 0x7f\n\nexport function encodingLength (value: number): number {\n if (value < N1) {\n return 1\n }\n\n if (value < N2) {\n return 2\n }\n\n if (value < N3) {\n return 3\n }\n\n if (value < N4) {\n return 4\n }\n\n if (value < N5) {\n return 5\n }\n\n if (value < N6) {\n return 6\n }\n\n if (value < N7) {\n return 7\n }\n\n if (Number.MAX_SAFE_INTEGER != null && value > Number.MAX_SAFE_INTEGER) {\n throw new RangeError('Could not encode varint')\n }\n\n return 8\n}\n\nexport function encodeUint8Array (value: number, buf: Uint8Array, offset: number = 0): Uint8Array {\n switch (encodingLength(value)) {\n case 8: {\n buf[offset++] = (value & 0xFF) | MSB\n value /= 128\n }\n case 7: {\n buf[offset++] = (value & 0xFF) | MSB\n value /= 128\n }\n case 6: {\n buf[offset++] = (value & 0xFF) | MSB\n value /= 128\n }\n case 5: {\n buf[offset++] = (value & 0xFF) | MSB\n value /= 128\n }\n case 4: {\n buf[offset++] = (value & 0xFF) | MSB\n value >>>= 7\n }\n case 3: {\n buf[offset++] = (value & 0xFF) | MSB\n value >>>= 7\n }\n case 2: {\n buf[offset++] = (value & 0xFF) | MSB\n value >>>= 7\n }\n case 1: {\n buf[offset++] = (value & 0xFF)\n value >>>= 7\n break\n }\n default: throw new Error('unreachable')\n }\n return buf\n}\n\nexport function encodeUint8ArrayList (value: number, buf: Uint8ArrayList, offset: number = 0): Uint8ArrayList {\n switch (encodingLength(value)) {\n case 8: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value /= 128\n }\n case 7: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value /= 128\n }\n case 6: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value /= 128\n }\n case 5: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value /= 128\n }\n case 4: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value >>>= 7\n }\n case 3: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value >>>= 7\n }\n case 2: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value >>>= 7\n }\n case 1: {\n buf.set(offset++, (value & 0xFF))\n value >>>= 7\n break\n }\n default: throw new Error('unreachable')\n }\n return buf\n}\n\nexport function decodeUint8Array (buf: Uint8Array, offset: number): number {\n let b = buf[offset]\n let res = 0\n\n res += b & REST\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 1]\n res += (b & REST) << 7\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 2]\n res += (b & REST) << 14\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 3]\n res += (b & REST) << 21\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 4]\n res += (b & REST) * N4\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 5]\n res += (b & REST) * N5\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 6]\n res += (b & REST) * N6\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 7]\n res += (b & REST) * N7\n if (b < MSB) {\n return res\n }\n\n throw new RangeError('Could not decode varint')\n}\n\nexport function decodeUint8ArrayList (buf: Uint8ArrayList, offset: number): number {\n let b = buf.get(offset)\n let res = 0\n\n res += b & REST\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 1)\n res += (b & REST) << 7\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 2)\n res += (b & REST) << 14\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 3)\n res += (b & REST) << 21\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 4)\n res += (b & REST) * N4\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 5)\n res += (b & REST) * N5\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 6)\n res += (b & REST) * N6\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 7)\n res += (b & REST) * N7\n if (b < MSB) {\n return res\n }\n\n throw new RangeError('Could not decode varint')\n}\n\nexport function encode (value: number): Uint8Array\nexport function encode (value: number, buf: Uint8Array, offset?: number): Uint8Array\nexport function encode (value: number, buf: Uint8ArrayList, offset?: number): Uint8ArrayList\nexport function encode <T extends Uint8Array | Uint8ArrayList = Uint8Array> (value: number, buf?: T, offset: number = 0): T {\n if (buf == null) {\n buf = allocUnsafe(encodingLength(value)) as T\n }\n if (buf instanceof Uint8Array) {\n return encodeUint8Array(value, buf, offset) as T\n } else {\n return encodeUint8ArrayList(value, buf, offset) as T\n }\n}\n\nexport function decode (buf: Uint8ArrayList | Uint8Array, offset: number = 0): number {\n if (buf instanceof Uint8Array) {\n return decodeUint8Array(buf, offset)\n } else {\n return decodeUint8ArrayList(buf, offset)\n }\n}\n", "const f32 = new Float32Array([-0])\nconst f8b = new Uint8Array(f32.buffer)\n\n/**\n * Writes a 32 bit float to a buffer using little endian byte order\n */\nexport function writeFloatLE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[0]\n buf[pos + 1] = f8b[1]\n buf[pos + 2] = f8b[2]\n buf[pos + 3] = f8b[3]\n}\n\n/**\n * Writes a 32 bit float to a buffer using big endian byte order\n */\nexport function writeFloatBE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[3]\n buf[pos + 1] = f8b[2]\n buf[pos + 2] = f8b[1]\n buf[pos + 3] = f8b[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using little endian byte order\n */\nexport function readFloatLE (buf: Uint8Array, pos: number): number {\n f8b[0] = buf[pos]\n f8b[1] = buf[pos + 1]\n f8b[2] = buf[pos + 2]\n f8b[3] = buf[pos + 3]\n return f32[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using big endian byte order\n */\nexport function readFloatBE (buf: Uint8Array, pos: number): number {\n f8b[3] = buf[pos]\n f8b[2] = buf[pos + 1]\n f8b[1] = buf[pos + 2]\n f8b[0] = buf[pos + 3]\n return f32[0]\n}\n\nconst f64 = new Float64Array([-0])\nconst d8b = new Uint8Array(f64.buffer)\n\n/**\n * Writes a 64 bit double to a buffer using little endian byte order\n */\nexport function writeDoubleLE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[0]\n buf[pos + 1] = d8b[1]\n buf[pos + 2] = d8b[2]\n buf[pos + 3] = d8b[3]\n buf[pos + 4] = d8b[4]\n buf[pos + 5] = d8b[5]\n buf[pos + 6] = d8b[6]\n buf[pos + 7] = d8b[7]\n}\n\n/**\n * Writes a 64 bit double to a buffer using big endian byte order\n */\nexport function writeDoubleBE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[7]\n buf[pos + 1] = d8b[6]\n buf[pos + 2] = d8b[5]\n buf[pos + 3] = d8b[4]\n buf[pos + 4] = d8b[3]\n buf[pos + 5] = d8b[2]\n buf[pos + 6] = d8b[1]\n buf[pos + 7] = d8b[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using little endian byte order\n */\nexport function readDoubleLE (buf: Uint8Array, pos: number): number {\n d8b[0] = buf[pos]\n d8b[1] = buf[pos + 1]\n d8b[2] = buf[pos + 2]\n d8b[3] = buf[pos + 3]\n d8b[4] = buf[pos + 4]\n d8b[5] = buf[pos + 5]\n d8b[6] = buf[pos + 6]\n d8b[7] = buf[pos + 7]\n return f64[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using big endian byte order\n */\nexport function readDoubleBE (buf: Uint8Array, pos: number): number {\n d8b[7] = buf[pos]\n d8b[6] = buf[pos + 1]\n d8b[5] = buf[pos + 2]\n d8b[4] = buf[pos + 3]\n d8b[3] = buf[pos + 4]\n d8b[2] = buf[pos + 5]\n d8b[1] = buf[pos + 6]\n d8b[0] = buf[pos + 7]\n return f64[0]\n}\n", "// the largest BigInt we can safely downcast to a Number\nconst MAX_SAFE_NUMBER_INTEGER = BigInt(Number.MAX_SAFE_INTEGER)\nconst MIN_SAFE_NUMBER_INTEGER = BigInt(Number.MIN_SAFE_INTEGER)\n\n/**\n * Constructs new long bits.\n *\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @function Object() { [native code] }\n * @param {number} lo - Low 32 bits, unsigned\n * @param {number} hi - High 32 bits, unsigned\n */\nexport class LongBits {\n public lo: number\n public hi: number\n\n constructor (lo: number, hi: number) {\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 */\n this.lo = lo | 0\n\n /**\n * High bits\n */\n this.hi = hi | 0\n }\n\n /**\n * Converts this long bits to a possibly unsafe JavaScript number\n */\n toNumber (unsigned: boolean = false): number {\n if (!unsigned && (this.hi >>> 31) > 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(lo + hi * 4294967296)\n }\n return this.lo + this.hi * 4294967296\n }\n\n /**\n * Converts this long bits to a bigint\n */\n toBigInt (unsigned: boolean = false): bigint {\n if (unsigned) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n if ((this.hi >>> 31) !== 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(BigInt(lo) + (BigInt(hi) << 32n))\n }\n\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n /**\n * Converts this long bits to a string\n */\n toString (unsigned: boolean = false): string {\n return this.toBigInt(unsigned).toString()\n }\n\n /**\n * Zig-zag encodes this long bits\n */\n zzEncode (): this {\n const 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 */\n zzDecode (): this {\n const 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 */\n length (): number {\n const part0 = this.lo\n const part1 = (this.lo >>> 28 | this.hi << 4) >>> 0\n const 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\n /**\n * Constructs new long bits from the specified number\n */\n static fromBigInt (value: bigint): LongBits {\n if (value === 0n) {\n return zero\n }\n\n if (value < MAX_SAFE_NUMBER_INTEGER && value > MIN_SAFE_NUMBER_INTEGER) {\n return this.fromNumber(Number(value))\n }\n\n const negative = value < 0n\n\n if (negative) {\n value = -value\n }\n\n let hi = value >> 32n\n let lo = value - (hi << 32n)\n\n if (negative) {\n hi = ~hi | 0n\n lo = ~lo | 0n\n\n if (++lo > TWO_32) {\n lo = 0n\n if (++hi > TWO_32) { hi = 0n }\n }\n }\n\n return new LongBits(Number(lo), Number(hi))\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromNumber (value: number): LongBits {\n if (value === 0) { return zero }\n const sign = value < 0\n if (sign) { value = -value }\n let lo = value >>> 0\n let 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) { 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 */\n static from (value: bigint | number | string | { low: number, high: number }): LongBits {\n if (typeof value === 'number') {\n return LongBits.fromNumber(value)\n }\n if (typeof value === 'bigint') {\n return LongBits.fromBigInt(value)\n }\n if (typeof value === 'string') {\n return LongBits.fromBigInt(BigInt(value))\n }\n return value.low != null || value.high != null ? new LongBits(value.low >>> 0, value.high >>> 0) : zero\n }\n}\n\nconst zero = new LongBits(0, 0)\nzero.toBigInt = function () { return 0n }\nzero.zzEncode = zero.zzDecode = function () { return this }\nzero.length = function () { return 1 }\n\nconst TWO_32 = 4294967296n\n", "/**\n * Calculates the UTF8 byte length of a string\n */\nexport function length (string: string): number {\n let len = 0\n let c = 0\n for (let i = 0; i < string.length; ++i) {\n c = string.charCodeAt(i)\n\n if (c < 128) {\n len += 1\n } else if (c < 2048) {\n len += 2\n } else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\n ++i\n len += 4\n } else {\n len += 3\n }\n }\n\n return len\n}\n\n/**\n * Reads UTF8 bytes as a string\n */\nexport function read (buffer: Uint8Array, start: number, end: number): string {\n const len = end - start\n\n if (len < 1) {\n return ''\n }\n\n let parts: string[] | undefined\n const chunk: number[] = []\n let i = 0 // char offset\n let t: number // temporary\n\n while (start < end) {\n t = buffer[start++]\n\n if (t < 128) {\n chunk[i++] = t\n } else if (t > 191 && t < 224) {\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63\n } else if (t > 239 && t < 365) {\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000\n chunk[i++] = 0xD800 + (t >> 10)\n chunk[i++] = 0xDC00 + (t & 1023)\n } else {\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63\n }\n\n if (i > 8191) {\n (parts ?? (parts = [])).push(String.fromCharCode.apply(String, chunk))\n i = 0\n }\n }\n\n if (parts != null) {\n if (i > 0) {\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)))\n }\n\n return parts.join('')\n }\n\n return String.fromCharCode.apply(String, chunk.slice(0, i))\n}\n\n/**\n * Writes a string as UTF8 bytes\n */\nexport function write (string: string, buffer: Uint8Array, offset: number): number {\n const start = offset\n let c1 // character 1\n let c2 // character 2\n\n for (let i = 0; i < string.length; ++i) {\n c1 = string.charCodeAt(i)\n\n if (c1 < 128) {\n buffer[offset++] = c1\n } else if (c1 < 2048) {\n buffer[offset++] = c1 >> 6 | 192\n buffer[offset++] = c1 & 63 | 128\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF)\n ++i\n buffer[offset++] = c1 >> 18 | 240\n buffer[offset++] = c1 >> 12 & 63 | 128\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n } else {\n buffer[offset++] = c1 >> 12 | 224\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n }\n }\n\n return offset - start\n}\n", "import { decodeUint8Array, encodingLength } from 'uint8-varint'\nimport { readFloatLE, readDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport * as utf8 from './utf8.js'\nimport type { Reader } from '../index.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\n/* istanbul ignore next */\nfunction indexOutOfRange (reader: Reader, writeLength?: number): RangeError {\n return RangeError(`index out of range: ${reader.pos} + ${writeLength ?? 1} > ${reader.len}`)\n}\n\nfunction readFixed32End (buf: Uint8Array, end: number): number { // 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 * Constructs a new reader instance using the specified buffer.\n */\nexport class Uint8ArrayReader implements Reader {\n public buf: Uint8Array\n public pos: number\n public len: number\n\n public _slice = Uint8Array.prototype.subarray\n\n constructor (buffer: Uint8Array) {\n /**\n * Read buffer\n */\n this.buf = buffer\n\n /**\n * Read buffer position\n */\n this.pos = 0\n\n /**\n * Read buffer length\n */\n this.len = buffer.length\n }\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32 (): number {\n let value = 4294967295\n\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 if ((this.pos += 5) > this.len) {\n this.pos = this.len\n throw indexOutOfRange(this, 10)\n }\n\n return value\n }\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32 (): number {\n return this.uint32() | 0\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32 (): number {\n const value = this.uint32()\n return value >>> 1 ^ -(value & 1) | 0\n }\n\n /**\n * Reads a varint as a boolean\n */\n bool (): boolean {\n return this.uint32() !== 0\n }\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32 (): number {\n if (this.pos + 4 > this.len) { throw indexOutOfRange(this, 4) }\n\n const res = readFixed32End(this.buf, this.pos += 4)\n\n return res\n }\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32 (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const res = readFixed32End(this.buf, this.pos += 4) | 0\n\n return res\n }\n\n /**\n * Reads a float (32 bit) as a number\n */\n float (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const value = 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 */\n double (): number {\n /* istanbul ignore if */\n if (this.pos + 8 > this.len) { throw indexOutOfRange(this, 4) }\n\n const value = readDoubleLE(this.buf, this.pos)\n this.pos += 8\n return value\n }\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes (): Uint8Array {\n const length = this.uint32()\n const start = this.pos\n const end = this.pos + length\n\n /* istanbul ignore if */\n if (end > this.len) {\n throw indexOutOfRange(this, length)\n }\n\n this.pos += length\n\n return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1\n ? new Uint8Array(0)\n : this.buf.subarray(start, end)\n }\n\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string (): string {\n const 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 */\n skip (length?: number): this {\n if (typeof length === 'number') {\n /* istanbul ignore if */\n if (this.pos + length > this.len) { 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 }\n } while ((this.buf[this.pos++] & 128) !== 0)\n }\n return this\n }\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType (wireType: number): this {\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\n private readLongVarint (): LongBits {\n // tends to deopt with local vars for octet etc.\n const bits = new LongBits(0, 0)\n let 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) { 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) { return bits }\n i = 0\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len) { 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) { 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) { return bits }\n }\n } else {\n for (; i < 5; ++i) {\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n }\n\n throw Error('invalid varint encoding')\n }\n\n private readFixed64 (): LongBits {\n if (this.pos + 8 > this.len) {\n throw indexOutOfRange(this, 8)\n }\n\n const lo = readFixed32End(this.buf, this.pos += 4)\n const hi = readFixed32End(this.buf, this.pos += 4)\n\n return new LongBits(lo, hi)\n }\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64 (): bigint {\n return this.readLongVarint().toBigInt()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n int64Number (): number {\n return this.readLongVarint().toNumber()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a string\n */\n int64String (): string {\n return this.readLongVarint().toString()\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64 (): bigint {\n return this.readLongVarint().toBigInt(true)\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n uint64Number (): number {\n const value = decodeUint8Array(this.buf, this.pos)\n this.pos += encodingLength(value)\n return value\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a string\n */\n uint64String (): string {\n return this.readLongVarint().toString(true)\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64 (): bigint {\n return this.readLongVarint().zzDecode().toBigInt()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * possibly unsafe JavaScript number\n */\n sint64Number (): number {\n return this.readLongVarint().zzDecode().toNumber()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * string\n */\n sint64String (): string {\n return this.readLongVarint().zzDecode().toString()\n }\n\n /**\n * Reads fixed 64 bits\n */\n fixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads fixed 64 bits returned as a possibly unsafe JavaScript number\n */\n fixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads fixed 64 bits returned as a string\n */\n fixed64String (): string {\n return this.readFixed64().toString()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a possibly unsafe\n * JavaScript number\n */\n sfixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a string\n */\n sfixed64String (): string {\n return this.readFixed64().toString()\n }\n}\n\nexport function createReader (buf: Uint8Array | Uint8ArrayList): Reader {\n return new Uint8ArrayReader(buf instanceof Uint8Array ? buf : buf.subarray())\n}\n", "import { createReader } from './utils/reader.js'\nimport type { Codec, DecodeOptions } from './codec.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport function decodeMessage <T> (buf: Uint8Array | Uint8ArrayList, codec: Pick<Codec<T>, 'decode'>, opts?: DecodeOptions<T>): T {\n const reader = createReader(buf)\n\n return codec.decode(reader, undefined, opts)\n}\n", "import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n", "import { from } from './base.js'\n\nconst alphabet = Array.from('\uD83D\uDE80\uD83E\uDE90\u2604\uD83D\uDEF0\uD83C\uDF0C\uD83C\uDF11\uD83C\uDF12\uD83C\uDF13\uD83C\uDF14\uD83C\uDF15\uD83C\uDF16\uD83C\uDF17\uD83C\uDF18\uD83C\uDF0D\uD83C\uDF0F\uD83C\uDF0E\uD83D\uDC09\u2600\uD83D\uDCBB\uD83D\uDDA5\uD83D\uDCBE\uD83D\uDCBF\uD83D\uDE02\u2764\uD83D\uDE0D\uD83E\uDD23\uD83D\uDE0A\uD83D\uDE4F\uD83D\uDC95\uD83D\uDE2D\uD83D\uDE18\uD83D\uDC4D\uD83D\uDE05\uD83D\uDC4F\uD83D\uDE01\uD83D\uDD25\uD83E\uDD70\uD83D\uDC94\uD83D\uDC96\uD83D\uDC99\uD83D\uDE22\uD83E\uDD14\uD83D\uDE06\uD83D\uDE44\uD83D\uDCAA\uD83D\uDE09\u263A\uD83D\uDC4C\uD83E\uDD17\uD83D\uDC9C\uD83D\uDE14\uD83D\uDE0E\uD83D\uDE07\uD83C\uDF39\uD83E\uDD26\uD83C\uDF89\uD83D\uDC9E\u270C\u2728\uD83E\uDD37\uD83D\uDE31\uD83D\uDE0C\uD83C\uDF38\uD83D\uDE4C\uD83D\uDE0B\uD83D\uDC97\uD83D\uDC9A\uD83D\uDE0F\uD83D\uDC9B\uD83D\uDE42\uD83D\uDC93\uD83E\uDD29\uD83D\uDE04\uD83D\uDE00\uD83D\uDDA4\uD83D\uDE03\uD83D\uDCAF\uD83D\uDE48\uD83D\uDC47\uD83C\uDFB6\uD83D\uDE12\uD83E\uDD2D\u2763\uD83D\uDE1C\uD83D\uDC8B\uD83D\uDC40\uD83D\uDE2A\uD83D\uDE11\uD83D\uDCA5\uD83D\uDE4B\uD83D\uDE1E\uD83D\uDE29\uD83D\uDE21\uD83E\uDD2A\uD83D\uDC4A\uD83E\uDD73\uD83D\uDE25\uD83E\uDD24\uD83D\uDC49\uD83D\uDC83\uD83D\uDE33\u270B\uD83D\uDE1A\uD83D\uDE1D\uD83D\uDE34\uD83C\uDF1F\uD83D\uDE2C\uD83D\uDE43\uD83C\uDF40\uD83C\uDF37\uD83D\uDE3B\uD83D\uDE13\u2B50\u2705\uD83E\uDD7A\uD83C\uDF08\uD83D\uDE08\uD83E\uDD18\uD83D\uDCA6\u2714\uD83D\uDE23\uD83C\uDFC3\uD83D\uDC90\u2639\uD83C\uDF8A\uD83D\uDC98\uD83D\uDE20\u261D\uD83D\uDE15\uD83C\uDF3A\uD83C\uDF82\uD83C\uDF3B\uD83D\uDE10\uD83D\uDD95\uD83D\uDC9D\uD83D\uDE4A\uD83D\uDE39\uD83D\uDDE3\uD83D\uDCAB\uD83D\uDC80\uD83D\uDC51\uD83C\uDFB5\uD83E\uDD1E\uD83D\uDE1B\uD83D\uDD34\uD83D\uDE24\uD83C\uDF3C\uD83D\uDE2B\u26BD\uD83E\uDD19\u2615\uD83C\uDFC6\uD83E\uDD2B\uD83D\uDC48\uD83D\uDE2E\uD83D\uDE46\uD83C\uDF7B\uD83C\uDF43\uD83D\uDC36\uD83D\uDC81\uD83D\uDE32\uD83C\uDF3F\uD83E\uDDE1\uD83C\uDF81\u26A1\uD83C\uDF1E\uD83C\uDF88\u274C\u270A\uD83D\uDC4B\uD83D\uDE30\uD83E\uDD28\uD83D\uDE36\uD83E\uDD1D\uD83D\uDEB6\uD83D\uDCB0\uD83C\uDF53\uD83D\uDCA2\uD83E\uDD1F\uD83D\uDE41\uD83D\uDEA8\uD83D\uDCA8\uD83E\uDD2C\u2708\uD83C\uDF80\uD83C\uDF7A\uD83E\uDD13\uD83D\uDE19\uD83D\uDC9F\uD83C\uDF31\uD83D\uDE16\uD83D\uDC76\uD83E\uDD74\u25B6\u27A1\u2753\uD83D\uDC8E\uD83D\uDCB8\u2B07\uD83D\uDE28\uD83C\uDF1A\uD83E\uDD8B\uD83D\uDE37\uD83D\uDD7A\u26A0\uD83D\uDE45\uD83D\uDE1F\uD83D\uDE35\uD83D\uDC4E\uD83E\uDD32\uD83E\uDD20\uD83E\uDD27\uD83D\uDCCC\uD83D\uDD35\uD83D\uDC85\uD83E\uDDD0\uD83D\uDC3E\uD83C\uDF52\uD83D\uDE17\uD83E\uDD11\uD83C\uDF0A\uD83E\uDD2F\uD83D\uDC37\u260E\uD83D\uDCA7\uD83D\uDE2F\uD83D\uDC86\uD83D\uDC46\uD83C\uDFA4\uD83D\uDE47\uD83C\uDF51\u2744\uD83C\uDF34\uD83D\uDCA3\uD83D\uDC38\uD83D\uDC8C\uD83D\uDCCD\uD83E\uDD40\uD83E\uDD22\uD83D\uDC45\uD83D\uDCA1\uD83D\uDCA9\uD83D\uDC50\uD83D\uDCF8\uD83D\uDC7B\uD83E\uDD10\uD83E\uDD2E\uD83C\uDFBC\uD83E\uDD75\uD83D\uDEA9\uD83C\uDF4E\uD83C\uDF4A\uD83D\uDC7C\uD83D\uDC8D\uD83D\uDCE3\uD83E\uDD42')\nconst alphabetBytesToChars: string[] = (alphabet.reduce<string[]>((p, c, i) => { p[i] = c; return p }, ([])))\nconst alphabetCharsToBytes: number[] = (alphabet.reduce<number[]>((p, c, i) => {\n const codePoint = c.codePointAt(0)\n if (codePoint == null) {\n throw new Error(`Invalid character: ${c}`)\n }\n p[codePoint] = i\n return p\n}, ([])))\n\nfunction encode (data: Uint8Array): string {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\nfunction decode (str: string): Uint8Array {\n const byts = []\n for (const char of str) {\n const codePoint = char.codePointAt(0)\n if (codePoint == null) {\n throw new Error(`Invalid character: ${char}`)\n }\n const byt = alphabetCharsToBytes[codePoint]\n if (byt == null) {\n throw new Error(`Non-base256emoji character: ${char}`)\n }\n byts.push(byt)\n }\n return new Uint8Array(byts)\n}\n\nexport const base256emoji = from({\n prefix: '\uD83D\uDE80',\n name: 'base256emoji',\n encode,\n decode\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n", "import { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n", "import type { ArrayBufferView, ByteView } from './interface.js'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\nexport function encode <T> (node: T): ByteView<T> {\n return textEncoder.encode(JSON.stringify(node))\n}\n\nexport function decode <T> (data: ByteView<T> | ArrayBufferView<T>): T {\n return JSON.parse(textDecoder.decode(data))\n}\n", "import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code: 0x0 = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array): Digest.Digest<typeof code, number> {\n return Digest.create(code, encode(input))\n}\n\nexport const identity = { code, name, encode, digest }\n", "/* global crypto */\n\nimport { from } from './hasher.js'\n\nfunction sha (name: AlgorithmIdentifier): (data: Uint8Array) => Promise<Uint8Array> {\n return async data => new Uint8Array(await crypto.subtle.digest(name, data))\n}\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n", "import * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.js'\nimport * as base2 from './bases/base2.js'\nimport * as base256emoji from './bases/base256emoji.js'\nimport * as base32 from './bases/base32.js'\nimport * as base36 from './bases/base36.js'\nimport * as base58 from './bases/base58.js'\nimport * as base64 from './bases/base64.js'\nimport * as base8 from './bases/base8.js'\nimport * as identityBase from './bases/identity.js'\nimport * as json from './codecs/json.js'\nimport * as raw from './codecs/raw.js'\nimport * as identity from './hashes/identity.js'\nimport * as sha2 from './hashes/sha2.js'\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nexport const hashes = { ...sha2, ...identity }\nexport const codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes }\n", "import { bases } from 'multiformats/basics'\nimport type { MultibaseCodec } from 'multiformats'\nimport { allocUnsafe } from '#alloc'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec<any> {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n }\n}\n\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8')\n return 'u' + decoder.decode(buf)\n}, (str) => {\n const encoder = new TextEncoder()\n return encoder.encode(str.substring(1))\n})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i])\n }\n return string\n}, (str) => {\n str = str.substring(1)\n const buf = allocUnsafe(str.length)\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record<SupportedEncodings, MultibaseCodec<any>> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n", "import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function fromString (string: string, encoding: SupportedEncodings = 'utf8'): Uint8Array {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n", "import { allocUnsafe } from 'uint8arrays/alloc'\n\n/**\n * A general purpose buffer pool\n */\nexport default function pool (size?: number): (size: number) => Uint8Array {\n const SIZE = size ?? 8192\n const MAX = SIZE >>> 1\n let slab: Uint8Array\n let offset = SIZE\n return function poolAlloc (size: number) {\n if (size < 1 || size > MAX) {\n return allocUnsafe(size)\n }\n\n if (offset + size > SIZE) {\n slab = allocUnsafe(SIZE)\n offset = 0\n }\n\n const buf = slab.subarray(offset, offset += size)\n\n if ((offset & 7) !== 0) {\n // align to 32 bit\n offset = (offset | 7) + 1\n }\n\n return buf\n }\n}\n", "import { encodeUint8Array, encodingLength } from 'uint8-varint'\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { writeFloatLE, writeDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport pool from './pool.js'\nimport * as utf8 from './utf8.js'\nimport type { Writer } from '../index.js'\n\ninterface WriterOperation<T> {\n (val: T, buf: Uint8Array, pos: number): any\n}\n\n/**\n * Constructs a new writer operation instance.\n *\n * @classdesc Scheduled writer operation\n */\nclass Op<T> {\n /**\n * Function to call\n */\n public fn: WriterOperation<T>\n\n /**\n * Value byte length\n */\n public len: number\n\n /**\n * Next operation\n */\n public next?: Op<any>\n\n /**\n * Value to write\n */\n public val: T\n\n constructor (fn: WriterOperation<T>, len: number, val: T) {\n this.fn = fn\n this.len = len\n this.next = undefined\n this.val = val // type varies\n }\n}\n\n/* istanbul ignore next */\nfunction noop (): void {}\n\n/**\n * Constructs a new writer state instance\n */\nclass State {\n /**\n * Current head\n */\n public head: Op<any>\n\n /**\n * Current tail\n */\n public tail: Op<any>\n\n /**\n * Current buffer length\n */\n public len: number\n\n /**\n * Next state\n */\n public next?: State\n\n constructor (writer: Uint8ArrayWriter) {\n this.head = writer.head\n this.tail = writer.tail\n this.len = writer.len\n this.next = writer.states\n }\n}\n\nconst bufferPool = pool()\n\n/**\n * Allocates a buffer of the specified size\n */\nfunction alloc (size: number): Uint8Array {\n if (globalThis.Buffer != null) {\n return allocUnsafe(size)\n }\n\n return bufferPool(size)\n}\n\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 */\nclass Uint8ArrayWriter implements Writer {\n /**\n * Current length\n */\n public len: number\n\n /**\n * Operations head\n */\n public head: Op<any>\n\n /**\n * Operations tail\n */\n public tail: Op<any>\n\n /**\n * Linked forked states\n */\n public states?: any\n\n constructor () {\n this.len = 0\n this.head = new Op(noop, 0, 0)\n this.tail = this.head\n this.states = null\n }\n\n /**\n * Pushes a new operation to the queue\n */\n _push (fn: WriterOperation<any>, len: number, val: any): this {\n this.tail = this.tail.next = new Op(fn, len, val)\n this.len += len\n\n return this\n }\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32 (value: number): this {\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\n ? 1\n : value < 16384\n ? 2\n : value < 2097152\n ? 3\n : value < 268435456\n ? 4\n : 5,\n value)).len\n return this\n }\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32 (value: number): this {\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 */\n sint32 (value: number): this {\n return this.uint32((value << 1 ^ value >> 31) >>> 0)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number (value: number): this {\n return this._push(encodeUint8Array, encodingLength(value), value)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String (value: string): this {\n return this.uint64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64 (value: bigint): this {\n return this.uint64(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number (value: number): this {\n return this.uint64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String (value: string): this {\n return this.uint64String(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number (value: number): this {\n const bits = LongBits.fromNumber(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String (value: string): this {\n return this.sint64(BigInt(value))\n }\n\n /**\n * Writes a boolish value as a varint\n */\n bool (value: boolean): this {\n return this._push(writeByte, 1, value ? 1 : 0)\n }\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32 (value: number): this {\n return this._push(writeFixed32, 4, value >>> 0)\n }\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32 (value: number): this {\n return this.fixed32(value)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number (value: number): this {\n const bits = LongBits.fromNumber(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String (value: string): this {\n return this.fixed64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64 (value: bigint): this {\n return this.fixed64(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number (value: number): this {\n return this.fixed64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String (value: string): this {\n return this.fixed64String(value)\n }\n\n /**\n * Writes a float (32 bit)\n */\n float (value: number): this {\n return this._push(writeFloatLE, 4, value)\n }\n\n /**\n * Writes a double (64 bit float).\n *\n * @function\n * @param {number} value - Value to write\n * @returns {Writer} `this`\n */\n double (value: number): this {\n return this._push(writeDoubleLE, 8, value)\n }\n\n /**\n * Writes a sequence of bytes\n */\n bytes (value: Uint8Array): this {\n const len = value.length >>> 0\n\n if (len === 0) {\n return this._push(writeByte, 1, 0)\n }\n\n return this.uint32(len)._push(writeBytes, len, value)\n }\n\n /**\n * Writes a string\n */\n string (value: string): this {\n const len = utf8.length(value)\n return len !== 0\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 */\n fork (): this {\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 */\n reset (): this {\n if (this.states != null) {\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 */\n ldelim (): this {\n const head = this.head\n const tail = this.tail\n const len = this.len\n this.reset().uint32(len)\n if (len !== 0) {\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 */\n finish (): Uint8Array {\n let head = this.head.next // skip noop\n const buf = alloc(this.len)\n let pos = 0\n while (head != null) {\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}\n\nfunction writeByte (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n}\n\nfunction writeVarint32 (val: number, buf: Uint8Array, pos: number): void {\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 *\n * @classdesc Scheduled varint writer operation\n */\nclass VarintOp extends Op<number> {\n public next?: Op<any>\n\n constructor (len: number, val: number) {\n super(writeVarint32, len, val)\n this.next = undefined\n }\n}\n\nfunction writeVarint64 (val: LongBits, buf: Uint8Array, pos: number): void {\n while (val.hi !== 0) {\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\nfunction writeFixed32 (val: number, buf: Uint8Array, pos: number): void {\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\nfunction writeBytes (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos)\n}\n\nif (globalThis.Buffer != null) {\n Uint8ArrayWriter.prototype.bytes = function (value: Uint8Array) {\n const len = value.length >>> 0\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeBytesBuffer, len, value)\n }\n\n return this\n }\n\n Uint8ArrayWriter.prototype.string = function (value: string) {\n const len = globalThis.Buffer.byteLength(value)\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeStringBuffer, len, value)\n }\n\n return this\n }\n}\n\nfunction writeBytesBuffer (val: Uint8Array, buf: Uint8Array, pos: number): void {\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\nfunction writeStringBuffer (val: string, buf: Uint8Array, pos: number): void {\n if (val.length < 40) {\n // plain js is faster for short strings (probably due to redundant assertions)\n utf8.write(val, buf, pos)\n // @ts-expect-error buf isn't a Uint8Array?\n } else if (buf.utf8Write != null) {\n // @ts-expect-error buf isn't a Uint8Array?\n buf.utf8Write(val, pos)\n } else {\n buf.set(uint8ArrayFromString(val), pos)\n }\n}\n\n/**\n * Creates a new writer\n */\nexport function createWriter (): Writer {\n return new Uint8ArrayWriter()\n}\n", "import { createWriter } from './utils/writer.js'\nimport type { Codec } from './codec.js'\n\nexport function encodeMessage <T> (message: Partial<T>, codec: Pick<Codec<T>, 'encode'>): Uint8Array {\n const w = createWriter()\n\n codec.encode(message, w, {\n lengthDelimited: false\n })\n\n return w.finish()\n}\n", "import type { Writer, Reader } from './index.js'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeOptions {\n lengthDelimited?: boolean\n writeDefaults?: boolean\n}\n\nexport interface EncodeFunction<T> {\n (value: Partial<T>, writer: Writer, opts?: EncodeOptions): void\n}\n\n// protobuf types that contain multiple values\ntype CollectionTypes = any[] | Map<any, any>\n\n// protobuf types that are not collections or messages\ntype PrimitiveTypes = boolean | number | string | bigint | Uint8Array\n\n// recursive array/map field length limits\ntype CollectionLimits <T> = {\n [K in keyof T]: T[K] extends CollectionTypes ? number :\n T[K] extends PrimitiveTypes ? never : Limits<T[K]>\n}\n\n// recursive array member array/map field length limits\ntype ArrayElementLimits <T> = {\n [K in keyof T as `${string & K}$`]: T[K] extends Array<infer ElementType> ?\n (ElementType extends PrimitiveTypes ? never : Limits<ElementType>) :\n (T[K] extends PrimitiveTypes ? never : Limits<T[K]>)\n}\n\n// recursive map value array/map field length limits\ntype MapValueLimits <T> = {\n [K in keyof T as `${string & K}$value`]: T[K] extends Map<any, infer MapValueType> ?\n (MapValueType extends PrimitiveTypes ? never : Limits<MapValueType>) :\n (T[K] extends PrimitiveTypes ? never : Limits<T[K]>)\n}\n\n// union of collection and array elements\ntype Limits<T> = Partial<CollectionLimits<T> & ArrayElementLimits<T> & MapValueLimits<T>>\n\nexport interface DecodeOptions<T> {\n /**\n * Runtime-specified limits for lengths of repeated/map fields\n */\n limits?: Limits<T>\n}\n\nexport interface DecodeFunction<T> {\n (reader: Reader, length?: number, opts?: DecodeOptions<T>): T\n}\n\nexport interface Codec<T> {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction<T>\n decode: DecodeFunction<T>\n}\n\nexport function createCodec <T> (name: string, type: CODEC_TYPES, encode: EncodeFunction<T>, decode: DecodeFunction<T>): Codec<T> {\n return {\n name,\n type,\n encode,\n decode\n }\n}\n", "import { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, Codec } from '../codec.js'\n\nexport function enumeration <T> (v: any): Codec<T> {\n function findValue (val: string | number): number {\n // Use the reverse mapping to look up the enum key for the stored value\n // https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings\n if (v[val.toString()] == null) {\n throw new Error('Invalid enum value')\n }\n\n return v[val]\n }\n\n const encode: EncodeFunction<number | string> = function enumEncode (val, writer) {\n const enumValue = findValue(val)\n\n writer.int32(enumValue)\n }\n\n const decode: DecodeFunction<number | string> = function enumDecode (reader) {\n const val = reader.int32()\n\n return findValue(val)\n }\n\n // @ts-expect-error yeah yeah\n return createCodec('enum', CODEC_TYPES.VARINT, encode, decode)\n}\n", "import { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { EncodeFunction, DecodeFunction, Codec } from '../codec.js'\n\nexport interface Factory<A, T> {\n new (obj: A): T\n}\n\nexport function message <T> (encode: EncodeFunction<T>, decode: DecodeFunction<T>): Codec<T> {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode)\n}\n", "import { enumeration, encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface Data {\n Type?: Data.DataType\n Data?: Uint8Array\n filesize?: bigint\n blocksizes: bigint[]\n hashType?: bigint\n fanout?: bigint\n mode?: number\n mtime?: UnixTime\n}\n\nexport namespace Data {\n export enum DataType {\n Raw = 'Raw',\n Directory = 'Directory',\n File = 'File',\n Metadata = 'Metadata',\n Symlink = 'Symlink',\n HAMTShard = 'HAMTShard'\n }\n\n enum __DataTypeValues {\n Raw = 0,\n Directory = 1,\n File = 2,\n Metadata = 3,\n Symlink = 4,\n HAMTShard = 5\n }\n\n export namespace DataType {\n export const codec = (): Codec<DataType> => {\n return enumeration<DataType>(__DataTypeValues)\n }\n }\n\n let _codec: Codec<Data>\n\n export const codec = (): Codec<Data> => {\n if (_codec == null) {\n _codec = message<Data>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n Data.DataType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (obj.filesize != null) {\n w.uint32(24)\n w.uint64(obj.filesize)\n }\n\n if (obj.blocksizes != null) {\n for (const value of obj.blocksizes) {\n w.uint32(32)\n w.uint64(value)\n }\n }\n\n if (obj.hashType != null) {\n w.uint32(40)\n w.uint64(obj.hashType)\n }\n\n if (obj.fanout != null) {\n w.uint32(48)\n w.uint64(obj.fanout)\n }\n\n if (obj.mode != null) {\n w.uint32(56)\n w.uint32(obj.mode)\n }\n\n if (obj.mtime != null) {\n w.uint32(66)\n UnixTime.codec().encode(obj.mtime, w)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n blocksizes: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.Type = Data.DataType.codec().decode(reader)\n break\n case 2:\n obj.Data = reader.bytes()\n break\n case 3:\n obj.filesize = reader.uint64()\n break\n case 4:\n obj.blocksizes.push(reader.uint64())\n break\n case 5:\n obj.hashType = reader.uint64()\n break\n case 6:\n obj.fanout = reader.uint64()\n break\n case 7:\n obj.mode = reader.uint32()\n break\n case 8:\n obj.mtime = UnixTime.codec().decode(reader, reader.uint32())\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<Data>): Uint8Array => {\n return encodeMessage(obj, Data.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Data => {\n return decodeMessage(buf, Data.codec())\n }\n}\n\nexport interface UnixTime {\n Seconds?: bigint\n FractionalNanoseconds?: number\n}\n\nexport namespace UnixTime {\n let _codec: Codec<UnixTime>\n\n export const codec = (): Codec<UnixTime> => {\n if (_codec == null) {\n _codec = message<UnixTime>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Seconds != null) {\n w.uint32(8)\n w.int64(obj.Seconds)\n }\n\n if (obj.FractionalNanoseconds != null) {\n w.uint32(21)\n w.fixed32(obj.FractionalNanoseconds)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.Seconds = reader.int64()\n break\n case 2:\n obj.FractionalNanoseconds = reader.fixed32()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<UnixTime>): Uint8Array => {\n return encodeMessage(obj, UnixTime.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): UnixTime => {\n return decodeMessage(buf, UnixTime.codec())\n }\n}\n\nexport interface Metadata {\n MimeType?: string\n}\n\nexport namespace Metadata {\n let _codec: Codec<Metadata>\n\n export const codec = (): Codec<Metadata> => {\n if (_codec == null) {\n _codec = message<Metadata>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.MimeType != null) {\n w.uint32(10)\n w.string(obj.MimeType)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.MimeType = reader.string()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<Metadata>): Uint8Array => {\n return encodeMessage(obj, Metadata.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Metadata => {\n return decodeMessage(buf, Metadata.codec())\n }\n}\n", "/**\n * @packageDocumentation\n *\n * This module contains the protobuf definition of the UnixFS data structure found at the root of all UnixFS DAGs.\n *\n * The UnixFS spec can be found in the [ipfs/specs repository](http://github.com/ipfs/specs)\n *\n * @example Create a file composed of several blocks\n *\n * ```TypeScript\n * import { UnixFS } from 'ipfs-unixfs'\n *\n * const data = new UnixFS({ type: 'file' })\n * data.addBlockSize(256n) // add the size of each block\n * data.addBlockSize(256n)\n * // ...\n * ```\n *\n * @example Create a directory that contains several files\n *\n * Creating a directory that contains several files is achieve by creating a unixfs element that identifies a MerkleDAG node as a directory. The links of that MerkleDAG node are the files that are contained in this directory.\n *\n * ```TypeScript\n * import { UnixFS } from 'ipfs-unixfs'\n *\n * const data = new UnixFS({ type: 'directory' })\n * ```\n *\n * @example Create an unixfs Data element\n *\n * ```TypeScript\n * import { UnixFS } from 'ipfs-unixfs'\n *\n * const data = new UnixFS({\n * // ...options\n * })\n * ```\n *\n * `options` is an optional object argument that might include the following keys:\n *\n * - type (string, default `file`): The type of UnixFS entry. Can be:\n * - `raw`\n * - `directory`\n * - `file`\n * - `metadata`\n * - `symlink`\n * - `hamt-sharded-directory`\n * - data (Uint8Array): The optional data field for this node\n * - blockSizes (Array, default: `[]`): If this is a `file` node that is made up of multiple blocks, `blockSizes` is a list numbers that represent the size of the file chunks stored in each child node. It is used to calculate the total file size.\n * - mode (Number, default `0644` for files, `0755` for directories/hamt-sharded-directories) file mode\n * - mtime (`Date`, `{ secs, nsecs }`, `{ Seconds, FractionalNanoseconds }`, `[ secs, nsecs ]`): The modification time of this node\n *\n * @example Add and remove a block size to the block size list\n *\n * ```TypeScript\n * import { UnixFS } from 'ipfs-unixfs'\n *\n * const data = new UnixFS({ type: 'file' })\n * const sizeInBytes = 100n\n * data.addBlockSize(sizeInBytes)\n * ```\n *\n * ```TypeScript\n * import { UnixFS } from 'ipfs-unixfs'\n *\n * const data = new UnixFS({ type: 'file' })\n *\n * const index = 0\n * data.removeBlockSize(index)\n * ```\n *\n * @example Get total fileSize\n *\n * ```TypeScript\n * import { UnixFS } from 'ipfs-unixfs'\n *\n * const data = new UnixFS({ type: 'file' })\n * data.fileSize() // => size in bytes\n * ```\n *\n * @example Marshal and unmarshal\n *\n * ```TypeScript\n * import { UnixFS } from 'ipfs-unixfs'\n *\n * const data = new UnixFS({ type: 'file' })\n * const marshaled = data.marshal()\n * const unmarshaled = UnixFS.unmarshal(marshaled)\n * ```\n *\n * @example Is this UnixFS entry a directory?\n *\n * ```TypeScript\n * import { UnixFS } from 'ipfs-unixfs'\n *\n * const dir = new UnixFS({ type: 'directory' })\n * dir.isDirectory() // true\n *\n * const file = new UnixFS({ type: 'file' })\n * file.isDirectory() // false\n * ```\n *\n * @example Has an mtime been set?\n *\n * If no modification time has been set, no `mtime` property will be present on the `Data` instance:\n *\n * ```TypeScript\n * import { UnixFS } from 'ipfs-unixfs'\n *\n * const file = new UnixFS({ type: 'file' })\n * file.mtime // undefined\n *\n * Object.prototype.hasOwnProperty.call(file, 'mtime') // false\n *\n * const dir = new UnixFS({ type: 'directory', mtime: { secs: 5n } })\n * dir.mtime // { secs: Number, nsecs: Number }\n * ```\n */\n\nimport { InvalidTypeError, InvalidUnixFSMessageError } from './errors.js'\nimport { Data as PBData } from './unixfs.js'\n\nexport interface Mtime {\n secs: bigint\n nsecs?: number\n}\n\nexport type MtimeLike = Mtime | { Seconds: number, FractionalNanoseconds?: number } | [number, number] | Date\n\nexport type UnixFSType = 'raw' | 'directory' | 'file' | 'metadata' | 'symlink' | 'hamt-sharded-directory'\n\nconst types: Record<string, UnixFSType> = {\n Raw: 'raw',\n Directory: 'directory',\n File: 'file',\n Metadata: 'metadata',\n Symlink: 'symlink',\n HAMTShard: 'hamt-sharded-directory'\n}\n\nconst dirTypes = [\n 'directory',\n 'hamt-sharded-directory'\n]\n\nconst DEFAULT_FILE_MODE = parseInt('0644', 8)\nconst DEFAULT_DIRECTORY_MODE = parseInt('0755', 8)\n\n// https://github.com/ipfs/boxo/blob/364c5040ec91ec8e2a61446e9921e9225704c34d/ipld/unixfs/hamt/hamt.go#L778\nconst MAX_FANOUT = BigInt(1 << 10)\n\nexport interface UnixFSOptions {\n type?: UnixFSType\n data?: Uint8Array\n blockSizes?: bigint[]\n hashType?: bigint\n fanout?: bigint\n mtime?: Mtime\n mode?: number\n}\n\nclass UnixFS {\n /**\n * Decode from protobuf https://github.com/ipfs/specs/blob/master/UNIXFS.md\n */\n static unmarshal (marshaled: Uint8Array): UnixFS {\n const message = PBData.decode(marshaled)\n\n if (message.fanout != null && message.fanout > MAX_FANOUT) {\n throw new InvalidUnixFSMessageError(`Fanout size was too large - ${message.fanout} > ${MAX_FANOUT}`)\n }\n\n const data = new UnixFS({\n type: types[message.Type != null ? message.Type.toString() : 'File'],\n data: message.Data,\n blockSizes: message.blocksizes,\n mode: message.mode,\n mtime: message.mtime != null\n ? {\n secs: message.mtime.Seconds ?? 0n,\n nsecs: message.mtime.FractionalNanoseconds\n }\n : undefined,\n fanout: message.fanout\n })\n\n // make sure we honour the original mode\n data._originalMode = message.mode ?? 0\n\n return data\n }\n\n public type: string\n public data?: Uint8Array\n public blockSizes: bigint[]\n public hashType?: bigint\n public fanout?: bigint\n public mtime?: Mtime\n\n private _mode?: number\n private _originalMode: number\n\n constructor (options: UnixFSOptions = {\n type: 'file'\n }) {\n const {\n type,\n data,\n blockSizes,\n hashType,\n fanout,\n mtime,\n mode\n } = options\n\n if (type != null && !Object.values(types).includes(type)) {\n throw new InvalidTypeError('Type: ' + type + ' is not valid')\n }\n\n this.type = type ?? 'file'\n this.data = data\n this.hashType = hashType\n this.fanout = fanout\n this.blockSizes = blockSizes ?? []\n this._originalMode = 0\n this.mode = mode\n this.mtime = mtime\n }\n\n set mode (mode: number | undefined) {\n if (mode == null) {\n this._mode = this.isDirectory() ? DEFAULT_DIRECTORY_MODE : DEFAULT_FILE_MODE\n } else {\n this._mode = (mode & 0xFFF)\n }\n }\n\n get mode (): number | undefined {\n return this._mode\n }\n\n isDirectory (): boolean {\n return dirTypes.includes(this.type)\n }\n\n addBlockSize (size: bigint): void {\n this.blockSizes.push(size)\n }\n\n removeBlockSize (index: number): void {\n this.blockSizes.splice(index, 1)\n }\n\n /**\n * Returns `0n` for directories or `data.length + sum(blockSizes)` for everything else\n */\n fileSize (): bigint {\n if (this.isDirectory()) {\n // dirs don't have file size\n return 0n\n }\n\n let sum = 0n\n this.blockSizes.forEach((size) => {\n sum += size\n })\n\n if (this.data != null) {\n sum += BigInt(this.data.length)\n }\n\n return sum\n }\n\n /**\n * encode to protobuf Uint8Array\n */\n marshal (): Uint8Array {\n let type\n\n switch (this.type) {\n case 'raw': type = PBData.DataType.Raw; break\n case 'directory': type = PBData.DataType.Directory; break\n case 'file': type = PBData.DataType.File; break\n case 'metadata': type = PBData.DataType.Metadata; break\n case 'symlink': type = PBData.DataType.Symlink; break\n case 'hamt-sharded-directory': type = PBData.DataType.HAMTShard; break\n default:\n throw new InvalidTypeError(`Type: ${type} is not valid`)\n }\n\n let data = this.data\n\n if (this.data == null || this.data.length === 0) {\n data = undefined\n }\n\n let mode\n\n if (this.mode != null) {\n mode = (this._originalMode & 0xFFFFF000) | (this.mode ?? 0)\n\n if (mode === DEFAULT_FILE_MODE && !this.isDirectory()) {\n mode = undefined\n }\n\n if (mode === DEFAULT_DIRECTORY_MODE && this.isDirectory()) {\n mode = undefined\n }\n }\n\n let mtime\n\n if (this.mtime != null) {\n mtime = {\n Seconds: this.mtime.secs,\n FractionalNanoseconds: this.mtime.nsecs\n }\n }\n\n return PBData.encode({\n Type: type,\n Data: data,\n filesize: this.isDirectory() ? undefined : this.fileSize(),\n blocksizes: this.blockSizes,\n hashType: this.hashType,\n fanout: this.fanout,\n mode,\n mtime\n })\n }\n}\n\nexport { UnixFS }\nexport * from './errors.js'\n", "import { decode } from '@ipld/dag-pb'\nimport { UnixFS } from 'ipfs-unixfs'\nimport { DAG_PB_CODEC_CODE } from '../constants.js'\nimport { NotUnixFSError } from '../errors.js'\nimport type { TraversalStrategy } from '../index.js'\nimport type { BlockView } from 'multiformats/block/interface'\nimport type { CID } from 'multiformats/cid'\n\n/**\n * Traverses a DAG containing UnixFS directories\n */\nexport class UnixFSPath implements TraversalStrategy {\n private readonly path: string[]\n\n constructor (path: string) {\n // \"/foo/bar/baz.txt\" -> ['foo', 'bar', 'baz.txt']\n this.path = path.replace(/^\\//, '').split('/')\n }\n\n isTarget (): boolean {\n return this.path.length === 0\n }\n\n async * traverse <T extends BlockView<any, any, any, 0 | 1>>(cid: CID, block: T): AsyncGenerator<CID, void, undefined> {\n if (cid.code !== DAG_PB_CODEC_CODE) {\n throw new NotUnixFSError('Target CID is not UnixFS')\n }\n\n const segment = this.path.shift()\n\n if (segment == null) {\n return\n }\n\n const pb = decode(block.bytes)\n\n if (pb.Data == null) {\n throw new NotUnixFSError('Target CID has no UnixFS data in decoded bytes')\n }\n\n const unixfs = UnixFS.unmarshal(pb.Data)\n\n if (unixfs.type === 'directory') {\n const link = pb.Links.filter(link => link.Name === segment).pop()\n\n if (link == null) {\n throw new NotUnixFSError(`Target CID directory has no link with name ${segment}`)\n }\n\n yield link.Hash\n return\n }\n\n // TODO: HAMT support\n\n throw new NotUnixFSError('Target CID is not a UnixFS directory')\n }\n}\n"],
5
5
  "mappings": ";4pB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AAe,8CAA8CC,CAAO,EAAE,EAGlF,MAAMI,EAAK,KACX,MACF,CAIA,MAAM,IAAIL,EAAe,sCAAsC,CACjE,GvF0LI,SAAUM,GAAKC,EAAsBC,EAAY,CAAA,EAAE,CACvD,OAAO,IAAIC,GAASF,EAAOC,CAAI,CACjC",
6
6
  "names": ["require_encode", "__commonJSMin", "exports", "module", "encode", "MSB", "REST", "MSBALL", "INT", "num", "out", "offset", "oldOffset", "require_decode", "__commonJSMin", "exports", "module", "read", "MSB", "REST", "buf", "offset", "res", "shift", "counter", "b", "l", "require_length", "__commonJSMin", "exports", "module", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "N8", "N9", "value", "require_varint", "__commonJSMin", "exports", "module", "require_eventemitter3", "__commonJSMin", "exports", "module", "has", "prefix", "Events", "EE", "fn", "context", "once", "addListener", "emitter", "event", "listener", "evt", "clearEvent", "EventEmitter", "names", "events", "name", "handlers", "i", "l", "ee", "listeners", "a1", "a2", "a3", "a4", "a5", "len", "args", "length", "j", "index_exports", "__export", "BlockExporter", "CIDPath", "GraphSearch", "SubgraphExporter", "UnixFSExporter", "UnixFSPath", "car", "typeofs", "objectTypeNames", "is", "value", "typeOf", "isBuffer", "objectType", "getObjectType", "objectTypeName", "Type", "major", "name", "terminal", "typ", "Token", "type", "value", "encodedLength", "useBuffer", "textDecoder", "textEncoder", "isBuffer", "buf", "asU8A", "toString", "bytes", "start", "end", "utf8Slice", "fromString", "string", "utf8ToBytes", "fromArray", "arr", "slice", "concat", "chunks", "length", "c", "out", "off", "b", "alloc", "size", "compare", "b1", "b2", "isBuffer", "i", "utf8ToBytes", "str", "out", "p", "c", "utf8Slice", "buf", "offset", "end", "res", "firstByte", "codePoint", "bytesPerSequence", "secondByte", "thirdByte", "fourthByte", "tempCodePoint", "decodeCodePointsArray", "MAX_ARGUMENTS_LENGTH", "codePoints", "len", "defaultChunkSize", "Bl", "chunkSize", "bytes", "topChunk", "chunkPos", "alloc", "reset", "byts", "chunk", "slice", "concat", "decodeErrPrefix", "encodeErrPrefix", "uintMinorPrefixBytes", "assertEnoughData", "data", "pos", "need", "uintBoundaries", "readUint8", "data", "offset", "options", "assertEnoughData", "value", "decodeErrPrefix", "readUint16", "readUint32", "readUint64", "hi", "lo", "decodeUint8", "pos", "_minor", "Token", "Type", "decodeUint16", "decodeUint32", "decodeUint64", "encodeUint", "buf", "token", "encodeUintValue", "major", "uint", "nuint", "buint", "set", "tok1", "tok2", "decodeNegint8", "data", "pos", "_minor", "options", "Token", "Type", "readUint8", "decodeNegint16", "readUint16", "decodeNegint32", "readUint32", "neg1b", "pos1b", "decodeNegint64", "int", "readUint64", "value", "decodeErrPrefix", "encodeNegint", "buf", "token", "negint", "unsigned", "encodeUintValue", "uintBoundaries", "tok1", "tok2", "toToken", "data", "pos", "prefix", "length", "assertEnoughData", "buf", "slice", "Token", "Type", "decodeBytesCompact", "minor", "_options", "decodeBytes8", "_minor", "options", "readUint8", "decodeBytes16", "readUint16", "decodeBytes32", "readUint32", "decodeBytes64", "l", "readUint64", "decodeErrPrefix", "tokenBytes", "token", "fromString", "encodeBytes", "bytes", "encodeUintValue", "tok1", "tok2", "compareBytes", "b1", "b2", "compare", "toToken", "data", "pos", "prefix", "length", "options", "totLength", "assertEnoughData", "tok", "Token", "Type", "toString", "slice", "decodeStringCompact", "minor", "decodeString8", "_minor", "readUint8", "decodeString16", "readUint16", "decodeString32", "readUint32", "decodeString64", "l", "readUint64", "decodeErrPrefix", "encodeString", "encodeBytes", "toToken", "_data", "_pos", "prefix", "length", "Token", "Type", "decodeArrayCompact", "data", "pos", "minor", "_options", "decodeArray8", "_minor", "options", "readUint8", "decodeArray16", "readUint16", "decodeArray32", "readUint32", "decodeArray64", "l", "readUint64", "decodeErrPrefix", "decodeArrayIndefinite", "encodeArray", "buf", "token", "encodeUintValue", "encodeUint", "toToken", "_data", "_pos", "prefix", "length", "Token", "Type", "decodeMapCompact", "data", "pos", "minor", "_options", "decodeMap8", "_minor", "options", "readUint8", "decodeMap16", "readUint16", "decodeMap32", "readUint32", "decodeMap64", "l", "readUint64", "decodeErrPrefix", "decodeMapIndefinite", "encodeMap", "buf", "token", "encodeUintValue", "encodeUint", "decodeTagCompact", "_data", "_pos", "minor", "_options", "Token", "Type", "decodeTag8", "data", "pos", "_minor", "options", "readUint8", "decodeTag16", "readUint16", "decodeTag32", "readUint32", "decodeTag64", "readUint64", "encodeTag", "buf", "token", "encodeUintValue", "encodeUint", "MINOR_FALSE", "MINOR_TRUE", "MINOR_NULL", "MINOR_UNDEFINED", "decodeUndefined", "_data", "_pos", "_minor", "options", "decodeErrPrefix", "Token", "Type", "decodeBreak", "createToken", "value", "bytes", "decodeFloat16", "data", "pos", "readFloat16", "decodeFloat32", "readFloat32", "decodeFloat64", "readFloat64", "encodeFloat", "buf", "token", "float", "decoded", "success", "encodeFloat16", "ui8a", "encodeFloat32", "encodeFloat64", "buffer", "dataView", "inp", "valu32", "exponent", "mantissa", "logicalExponent", "half", "exp", "mant", "val", "offset", "encodeUint", "invalidMinor", "data", "pos", "minor", "decodeErrPrefix", "errorer", "msg", "jump", "i", "decodeUint8", "decodeUint16", "decodeUint32", "decodeUint64", "decodeNegint8", "decodeNegint16", "decodeNegint32", "decodeNegint64", "decodeBytesCompact", "decodeBytes8", "decodeBytes16", "decodeBytes32", "decodeBytes64", "decodeStringCompact", "decodeString8", "decodeString16", "decodeString32", "decodeString64", "decodeArrayCompact", "decodeArray8", "decodeArray16", "decodeArray32", "decodeArray64", "decodeArrayIndefinite", "decodeMapCompact", "decodeMap8", "decodeMap16", "decodeMap32", "decodeMap64", "decodeMapIndefinite", "decodeTagCompact", "decodeTag8", "decodeTag16", "decodeTag32", "decodeTag64", "decodeUndefined", "decodeFloat16", "decodeFloat32", "decodeFloat64", "decodeBreak", "quick", "Token", "Type", "quickEncodeToken", "token", "fromArray", "defaultEncodeOptions", "mapSorter", "quickEncodeToken", "makeCborEncoders", "encoders", "Type", "encodeUint", "encodeNegint", "encodeBytes", "encodeString", "encodeArray", "encodeMap", "encodeTag", "encodeFloat", "cborEncoders", "buf", "Bl", "Ref", "_Ref", "obj", "parent", "p", "stack", "encodeErrPrefix", "simpleTokens", "Token", "typeEncoders", "_typ", "_options", "_refStack", "_obj", "options", "refStack", "entries", "e", "objectToTokens", "typ", "isMap", "keys", "length", "i", "key", "sortMapEntries", "is", "customTypeEncoder", "tokens", "typeEncoder", "e1", "e2", "keyToken1", "keyToken2", "major", "tcmp", "tokensToEncoded", "token", "encodeCustom", "data", "quickBytes", "encoder", "size", "asU8A", "encode", "defaultDecodeOptions", "Tokeniser", "data", "options", "byt", "token", "quick", "decoder", "jump", "decodeErrPrefix", "minor", "DONE", "BREAK", "tokenToArray", "tokeniser", "arr", "i", "value", "tokensToObject", "tokenToMap", "useMaps", "obj", "m", "key", "Type", "tagged", "decodeFirst", "decoded", "decode", "remainder", "base32_exports", "__export", "base32", "base32hex", "base32hexpad", "base32hexpadupper", "base32hexupper", "base32pad", "base32padupper", "base32upper", "base32z", "empty", "equals", "aa", "bb", "ii", "coerce", "o", "fromString", "str", "toString", "b", "base", "ALPHABET", "name", "BASE_MAP", "j", "i", "x", "xc", "BASE", "LEADER", "FACTOR", "iFACTOR", "encode", "source", "zeroes", "length", "pbegin", "pend", "size", "b58", "carry", "it1", "it2", "str", "decodeUnsafe", "psz", "b256", "it3", "it4", "vch", "decode", "string", "buffer", "src", "_brrp__multiformats_scope_baseX", "base_x_default", "Encoder", "name", "prefix", "baseEncode", "bytes", "Decoder", "baseDecode", "prefixCodePoint", "text", "decoder", "or", "ComposedDecoder", "decoders", "input", "left", "right", "Codec", "from", "encode", "decode", "baseX", "alphabet", "base_x_default", "coerce", "string", "alphabetIdx", "bitsPerChar", "end", "out", "bits", "buffer", "written", "i", "value", "data", "pad", "mask", "createAlphabetIdx", "rfc4648", "base32", "rfc4648", "base32upper", "base32pad", "base32padupper", "base32hex", "base32hexupper", "base32hexpad", "base32hexpadupper", "base32z", "base36_exports", "__export", "base36", "base36upper", "base36", "baseX", "base36upper", "base58_exports", "__export", "base58btc", "base58flickr", "base58btc", "baseX", "base58flickr", "encode_1", "encode", "MSB", "REST", "MSBALL", "INT", "num", "out", "offset", "oldOffset", "decode", "read", "MSB$1", "REST$1", "buf", "res", "shift", "counter", "b", "l", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "N8", "N9", "length", "value", "varint", "_brrp_varint", "varint_default", "decode", "data", "offset", "varint_default", "encodeTo", "int", "target", "encodingLength", "create", "code", "digest", "size", "sizeOffset", "encodingLength", "digestOffset", "bytes", "encodeTo", "Digest", "decode", "multihash", "coerce", "equals", "a", "b", "data", "format", "link", "base", "bytes", "version", "toStringV0", "baseCache", "base58btc", "toStringV1", "base32", "cache", "baseCache", "cid", "CID", "_CID", "version", "code", "multihash", "bytes", "DAG_PB_CODE", "SHA_256_CODE", "digest", "create", "other", "self", "unknown", "equals", "base", "format", "input", "value", "encodeCID", "cidSymbol", "decode", "remainder", "specs", "prefixSize", "multihashBytes", "coerce", "digestBytes", "Digest", "initialBytes", "offset", "next", "i", "length", "codec", "multihashCode", "digestSize", "size", "multihashSize", "source", "prefix", "parseCIDtoBytes", "decoder", "base58btc", "base32", "base36", "toStringV0", "toStringV1", "codeOffset", "encodingLength", "hashOffset", "encodeTo", "CID_CBOR_TAG", "toByteView", "buf", "cidEncoder", "obj", "cid", "CID", "bytes", "Token", "Type", "undefinedEncoder", "numberEncoder", "num", "_encodeOptions", "encodeOptions", "cidDecoder", "_decodeOptions", "decodeOptions", "encode", "node", "_encodeOptions", "decode", "data", "toByteView", "_decodeOptions", "import_varint", "V2_HEADER_LENGTH", "decodeVarint", "bytes", "seeker", "i", "varint", "decodeV2Header", "dv", "offset", "Kinds", "obj", "Types", "i", "v", "ret", "j", "entries", "requiredCount", "key", "value", "Reprs", "CarV1HeaderOrV2Pragma", "cborEncoders", "makeCborEncoders", "import_varint", "headerPreludeTokens", "Token", "Type", "CID_TAG", "readHeader", "reader", "strictVersion", "length", "decodeVarint", "header", "block", "decode", "CarV1HeaderOrV2Pragma", "v2Header", "decodeV2Header", "V2_HEADER_LENGTH", "v1Header", "bytesReader", "bytes", "pos", "length", "seek", "out", "import_varint", "CAR_V1_VERSION", "createHeader", "roots", "headerBytes", "encode", "varintBytes", "varint", "header", "createEncoder", "writer", "bytes", "block", "cid", "noop", "create", "chunkQueue", "drainer", "drainerResolver", "ended", "outWait", "outWaitResolver", "makeDrainer", "resolve", "writer", "chunk", "iterator", "CarWriter", "_CarWriter", "roots", "encoder", "block", "cid", "CID", "toRoots", "iterator", "encodeWriter", "writer", "out", "CarWriterOut", "bytes", "reader", "bytesReader", "readHeader", "newHeader", "createHeader", "iw", "create", "createEncoder", "_roots", "root", "_root", "isAsyncIterable", "thing", "drain", "source", "_", "src_default", "peekable", "iterable", "iterator", "symbol", "queue", "value", "src_default", "isAsyncIterable", "thing", "map", "source", "func", "index", "val", "peekable", "src_default", "value", "done", "res", "fn", "from", "name", "code", "encode", "Hasher", "input", "result", "create", "digest", "readonly", "enumerable", "configurable", "linksWithin", "path", "value", "index", "element", "elementPath", "cid", "CID", "links", "source", "base", "key", "treeWithin", "tree", "get", "node", "part", "Block", "bytes", "createUnsafe", "bytes", "cid", "maybeValue", "codec", "value", "Block", "pDefer", "deferred", "resolve", "reject", "import_index", "TimeoutError", "message", "AbortError", "getDOMException", "errorMessage", "getAbortedReason", "signal", "reason", "pTimeout", "promise", "options", "milliseconds", "fallback", "customTimers", "timer", "abortHandler", "cancelablePromise", "resolve", "reject", "timeoutError", "error", "lowerBound", "array", "value", "comparator", "first", "count", "step", "it", "PriorityQueue", "#queue", "run", "options", "element", "index", "lowerBound", "a", "b", "id", "priority", "item", "PQueue", "EventEmitter", "#carryoverConcurrencyCount", "#isIntervalIgnored", "#intervalCount", "#intervalCap", "#interval", "#intervalEnd", "#intervalId", "#timeoutId", "#queue", "#queueClass", "#pending", "#concurrency", "#isPaused", "#throwOnTimeout", "#idAssigner", "options", "PriorityQueue", "#doesIntervalAllowAnother", "#doesConcurrentAllowAnother", "#next", "#tryToStartAnother", "#onResumeInterval", "#onInterval", "#initializeIntervalIfNeeded", "#isIntervalPaused", "now", "delay", "canInitializeInterval", "job", "#processQueue", "newConcurrency", "#throwOnAbort", "signal", "_resolve", "reject", "id", "priority", "function_", "resolve", "operation", "pTimeout", "result", "error", "TimeoutError", "functions", "#onEvent", "limit", "event", "filter", "listener", "SubgraphExporter", "_cid", "block", "linkedCid", "GraphSearch", "target", "cid", "block", "linkedCid", "Car", "components", "init", "reader", "options", "src_default", "cid", "bytes", "root", "writer", "deferred", "pDefer", "roots", "traversalContext", "traversalStrategy", "exportStrategy", "SubgraphExporter", "queue", "PQueue", "startedExport", "path", "targetIndex", "targetCid", "#exportDagNode", "err", "#traverseDagNode", "GraphSearch", "out", "CarWriter", "buf", "strategy", "parentPath", "currentPath", "codec", "decodedBlock", "createUnsafe", "nextCid", "recursive", "BlockExporter", "cid", "block", "NotUnixFSError", "UnixFSExporter", "cid", "block", "NotUnixFSError", "linkedCid", "CIDPath", "pathToTarget", "cid", "_block", "givenCidIndex", "textDecoder", "decodeVarint", "bytes", "offset", "v", "shift", "b", "decodeBytes", "byteLen", "postOffset", "decodeKey", "index", "wire", "decodeLink", "link", "l", "wireType", "fieldNum", "byts", "decodeNode", "links", "linksBeforeData", "data", "node", "textEncoder", "maxInt32", "maxUInt32", "textEncoder", "toByteView", "buf", "decode", "bytes", "buf", "toByteView", "pbn", "decodeNode", "node", "l", "link", "CID", "InvalidTypeError", "_InvalidTypeError", "message", "InvalidUnixFSMessageError", "_InvalidUnixFSMessageError", "allocUnsafe", "size", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "MSB", "REST", "encodingLength", "value", "encodeUint8Array", "buf", "offset", "decodeUint8Array", "buf", "offset", "b", "res", "REST", "MSB", "N4", "N5", "N6", "N7", "f32", "f8b", "writeFloatLE", "val", "buf", "pos", "readFloatLE", "buf", "pos", "f8b", "f32", "f64", "d8b", "writeDoubleLE", "val", "buf", "pos", "readDoubleLE", "buf", "pos", "d8b", "f64", "MAX_SAFE_NUMBER_INTEGER", "MIN_SAFE_NUMBER_INTEGER", "LongBits", "_LongBits", "lo", "hi", "unsigned", "mask", "part0", "part1", "part2", "value", "zero", "negative", "TWO_32", "sign", "length", "string", "len", "c", "i", "read", "buffer", "start", "end", "parts", "chunk", "t", "write", "offset", "c1", "c2", "indexOutOfRange", "reader", "writeLength", "readFixed32End", "buf", "end", "Uint8ArrayReader", "buffer", "value", "readFloatLE", "readDoubleLE", "length", "start", "bytes", "read", "wireType", "bits", "LongBits", "i", "lo", "hi", "decodeUint8Array", "encodingLength", "createReader", "decodeMessage", "buf", "codec", "opts", "reader", "createReader", "base10_exports", "__export", "base10", "base10", "baseX", "base16_exports", "__export", "base16", "base16upper", "base16", "rfc4648", "base16upper", "base2_exports", "__export", "base2", "base2", "rfc4648", "base256emoji_exports", "__export", "base256emoji", "alphabet", "alphabetBytesToChars", "p", "c", "i", "alphabetCharsToBytes", "codePoint", "encode", "data", "decode", "str", "byts", "char", "byt", "base256emoji", "from", "base64_exports", "__export", "base64", "base64pad", "base64url", "base64urlpad", "base64", "rfc4648", "base64pad", "base64url", "base64urlpad", "base8_exports", "__export", "base8", "base8", "rfc4648", "identity_exports", "__export", "identity", "identity", "from", "buf", "toString", "str", "fromString", "textEncoder", "textDecoder", "identity_exports", "__export", "identity", "code", "name", "encode", "coerce", "digest", "input", "create", "identity", "sha2_browser_exports", "__export", "sha256", "sha512", "sha", "name", "data", "sha256", "from", "sha512", "bases", "identity_exports", "base2_exports", "base8_exports", "base10_exports", "base16_exports", "base32_exports", "base36_exports", "base58_exports", "base64_exports", "base256emoji_exports", "hashes", "sha2_browser_exports", "createCodec", "name", "prefix", "encode", "decode", "string", "buf", "str", "ascii", "i", "allocUnsafe", "BASES", "bases", "bases_default", "fromString", "string", "encoding", "base", "bases_default", "pool", "size", "SIZE", "MAX", "slab", "offset", "allocUnsafe", "buf", "Op", "fn", "len", "val", "noop", "State", "writer", "bufferPool", "pool", "alloc", "size", "allocUnsafe", "Uint8ArrayWriter", "value", "VarintOp", "writeVarint64", "LongBits", "bits", "encodeUint8Array", "encodingLength", "writeByte", "writeFixed32", "writeFloatLE", "writeDoubleLE", "writeBytes", "length", "write", "head", "tail", "buf", "pos", "writeVarint32", "writeBytesBuffer", "writeStringBuffer", "fromString", "createWriter", "encodeMessage", "message", "codec", "w", "createWriter", "CODEC_TYPES", "createCodec", "name", "type", "encode", "decode", "enumeration", "v", "findValue", "val", "encode", "writer", "enumValue", "decode", "reader", "createCodec", "CODEC_TYPES", "message", "encode", "decode", "createCodec", "CODEC_TYPES", "Data", "DataType", "__DataTypeValues", "enumeration", "_codec", "message", "obj", "w", "opts", "value", "UnixTime", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "Metadata", "types", "dirTypes", "DEFAULT_FILE_MODE", "DEFAULT_DIRECTORY_MODE", "MAX_FANOUT", "UnixFS", "_UnixFS", "marshaled", "message", "Data", "InvalidUnixFSMessageError", "data", "options", "type", "blockSizes", "hashType", "fanout", "mtime", "mode", "InvalidTypeError", "size", "index", "sum", "UnixFSPath", "path", "cid", "block", "NotUnixFSError", "segment", "pb", "decode", "UnixFS", "link", "car", "helia", "init", "Car"]
7
7
  }