@helia/utils 2.5.2-9114743f → 2.5.2-a464d83a

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/truncate-utf8-bytes/lib/truncate.js", "../../../node_modules/utf8-byte-length/browser.js", "../../../node_modules/truncate-utf8-bytes/browser.js", "../../../node_modules/sanitize-filename/index.js", "../../../node_modules/eventemitter3/index.js", "../../../node_modules/hashlru/index.js", "../src/index.ts", "../../../node_modules/uint8arrays/src/alloc.ts", "../../../node_modules/uint8-varint/src/index.ts", "../../../node_modules/uint8arrays/src/with-array-buffer.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/bytes.ts", "../../../node_modules/multiformats/src/vendor/base-x.js", "../../../node_modules/multiformats/src/bases/base.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/base32.ts", "../../../node_modules/multiformats/src/bases/base36.ts", "../../../node_modules/multiformats/src/bases/base58.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/codecs/raw.ts", "../../../node_modules/multiformats/src/hashes/identity.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/hashes/sha2-browser.ts", "../../../node_modules/multiformats/src/hashes/hasher.ts", "../../../node_modules/multiformats/src/cid.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/stream.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/@ipshipyard/crypto/src/pb.ts", "../../../node_modules/uint8arrays/src/to-string.ts", "../../../node_modules/interface-datastore/src/key.ts", "../../../node_modules/@ipshipyard/keychain/src/keychain.ts", "../../../node_modules/uint8arrays/src/util/as-uint8array.ts", "../../../node_modules/uint8arrays/src/concat.ts", "../../../node_modules/@ipshipyard/keychain/src/errors.ts", "../../../node_modules/uint8arrays/src/equals.ts", "../../../node_modules/uint8arraylist/src/index.ts", "../../../node_modules/@ipshipyard/crypto/src/der.ts", "../../../node_modules/@ipshipyard/crypto/src/errors.ts", "../../../node_modules/@ipshipyard/crypto/src/ecdsa.ts", "../../../node_modules/@ipshipyard/crypto/src/ed25519.ts", "../../../node_modules/@ipshipyard/crypto/src/rsa.ts", "../../../node_modules/@ipshipyard/keychain/src/legacy.ts", "../../../node_modules/@ipshipyard/keychain/src/index.ts", "../../../node_modules/@libp2p/interface/src/errors.ts", "../../../node_modules/@libp2p/interface/src/startable.ts", "../../../node_modules/main-event/src/index.ts", "../../../node_modules/progress-events/src/index.ts", "../../../node_modules/@multiformats/dns/src/errors.ts", "../../../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", "../../../node_modules/@multiformats/dns/src/utils/get-types.ts", "../../../node_modules/@multiformats/dns/src/utils/to-dns-response.ts", "../../../node_modules/@multiformats/dns/src/resolvers/dns-json-over-https.ts", "../../../node_modules/@multiformats/dns/src/resolvers/default.browser.ts", "../../../node_modules/@multiformats/dns/src/utils/cache.ts", "../../../node_modules/@multiformats/dns/src/dns.ts", "../../../node_modules/@multiformats/dns/src/index.ts", "../../../node_modules/weald/node_modules/ms/dist/index.js", "../../../node_modules/weald/src/common.ts", "../../../node_modules/weald/src/browser.ts", "../../../node_modules/weald/src/index.ts", "../../../node_modules/birnam/src/index.ts", "../../../node_modules/blockstore-core/src/base.ts", "../../../node_modules/interface-store/src/errors.ts", "../../../node_modules/it-all/src/index.ts", "../../../node_modules/blockstore-core/src/memory.ts", "../../../node_modules/@libp2p/logger/src/index.ts", "../../../node_modules/it-peekable/src/index.ts", "../../../node_modules/it-filter/src/index.ts", "../../../node_modules/p-defer/index.js", "../../../node_modules/race-signal/src/index.ts", "../../../node_modules/it-queueless-pushable/src/index.ts", "../../../node_modules/it-merge/src/index.ts", "../../../node_modules/blockstore-core/src/tiered.ts", "../../../node_modules/datastore-core/src/shard.ts", "../../../node_modules/it-drain/src/index.ts", "../../../node_modules/it-sort/src/index.ts", "../../../node_modules/it-take/src/index.ts", "../../../node_modules/datastore-core/src/base.ts", "../../../node_modules/datastore-core/src/memory.ts", "../../../node_modules/it-pushable/src/fifo.ts", "../../../node_modules/it-pushable/src/index.ts", "../../../node_modules/datastore-core/src/sharding.ts", "../../../node_modules/datastore-core/src/tiered.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/cborg/lib/tagged.js", "../src/errors.ts", "../../../node_modules/@sindresorhus/fnv1a/index.js", "../../../node_modules/@libp2p/utils/src/filters/hashes.ts", "../../../node_modules/@libp2p/utils/src/filters/fingerprint.ts", "../../../node_modules/@libp2p/utils/src/filters/utils.ts", "../../../node_modules/@libp2p/utils/src/filters/bucket.ts", "../../../node_modules/@libp2p/utils/src/filters/cuckoo-filter.ts", "../../../node_modules/@libp2p/utils/src/filters/scalable-cuckoo-filter.ts", "../../../node_modules/@libp2p/utils/node_modules/p-event/index.js", "../../../node_modules/@libp2p/utils/src/debounce.ts", "../../../node_modules/@libp2p/utils/src/errors.ts", "../../../node_modules/@libp2p/utils/src/queue/recipient.ts", "../../../node_modules/@libp2p/utils/src/queue/job.ts", "../../../node_modules/@libp2p/utils/src/queue/index.ts", "../../../node_modules/any-signal/src/index.ts", "../../../node_modules/it-to-buffer/src/index.ts", "../../../node_modules/multiformats/src/block.ts", "../src/graph-walker.ts", "../src/pins.ts", "../../interface/src/errors.ts", "../src/routing.ts", "../../../node_modules/abort-error/src/index.ts", "../../../node_modules/race-event/src/index.ts", "../../../node_modules/it-queue/src/errors.ts", "../../../node_modules/it-queue/src/recipient.ts", "../../../node_modules/it-queue/src/job.ts", "../../../node_modules/it-queue/src/utils.ts", "../../../node_modules/it-queue/src/index.ts", "../../../node_modules/mortice/src/constants.ts", "../../../node_modules/mortice/src/main/channel.ts", "../../../node_modules/mortice/src/utils.ts", "../../../node_modules/mortice/src/workers/channel.ts", "../../../node_modules/mortice/src/browser.ts", "../../../node_modules/mortice/src/mortice.ts", "../../../node_modules/mortice/src/index.ts", "../src/storage.ts", "../src/utils/datastore-version.ts", "../../../node_modules/@ipld/dag-cbor/src/index.js", "../../../node_modules/@ipld/dag-json/src/index.js", "../../../node_modules/cborg/lib/json/encode.js", "../../../node_modules/cborg/lib/json/decode.js", "../../../node_modules/@ipld/dag-pb/src/index.js", "../../../node_modules/@ipld/dag-pb/src/pb-decode.js", "../../../node_modules/@ipld/dag-pb/src/pb-encode.js", "../../../node_modules/@ipld/dag-pb/src/util.js", "../src/utils/is-promise.ts", "../src/utils/get-codec.ts", "../src/utils/get-crypto.ts", "../src/utils/get-hasher.ts", "../../../node_modules/blockstore-core/src/identity.ts", "../../../node_modules/it-foreach/src/index.ts", "../src/utils/storage.ts", "../src/utils/session-storage.ts", "../src/utils/networked-storage.ts", "../src/abstract-session.ts", "../src/utils/is-cid.ts"],
4
- "sourcesContent": ["'use strict';\n\nfunction isHighSurrogate(codePoint) {\n return codePoint >= 0xd800 && codePoint <= 0xdbff;\n}\n\nfunction isLowSurrogate(codePoint) {\n return codePoint >= 0xdc00 && codePoint <= 0xdfff;\n}\n\n// Truncate string by size in bytes\nmodule.exports = function truncate(getLength, string, byteLength) {\n if (typeof string !== \"string\") {\n throw new Error(\"Input must be string\");\n }\n\n var charLength = string.length;\n var curByteLength = 0;\n var codePoint;\n var segment;\n\n for (var i = 0; i < charLength; i += 1) {\n codePoint = string.charCodeAt(i);\n segment = string[i];\n\n if (isHighSurrogate(codePoint) && isLowSurrogate(string.charCodeAt(i + 1))) {\n i += 1;\n segment += string[i];\n }\n\n curByteLength += getLength(segment);\n\n if (curByteLength === byteLength) {\n return string.slice(0, i + 1);\n }\n else if (curByteLength > byteLength) {\n return string.slice(0, i - segment.length + 1);\n }\n }\n\n return string;\n};\n\n", "'use strict';\n\nfunction isHighSurrogate(codePoint) {\n return codePoint >= 0xd800 && codePoint <= 0xdbff;\n}\n\nfunction isLowSurrogate(codePoint) {\n return codePoint >= 0xdc00 && codePoint <= 0xdfff;\n}\n\n// Truncate string by size in bytes\nmodule.exports = function getByteLength(string) {\n if (typeof string !== \"string\") {\n throw new Error(\"Input must be string\");\n }\n\n var charLength = string.length;\n var byteLength = 0;\n var codePoint = null;\n var prevCodePoint = null;\n for (var i = 0; i < charLength; i++) {\n codePoint = string.charCodeAt(i);\n // handle 4-byte non-BMP chars\n // low surrogate\n if (isLowSurrogate(codePoint)) {\n // when parsing previous hi-surrogate, 3 is added to byteLength\n if (prevCodePoint != null && isHighSurrogate(prevCodePoint)) {\n byteLength += 1;\n }\n else {\n byteLength += 3;\n }\n }\n else if (codePoint <= 0x7f ) {\n byteLength += 1;\n }\n else if (codePoint >= 0x80 && codePoint <= 0x7ff) {\n byteLength += 2;\n }\n else if (codePoint >= 0x800 && codePoint <= 0xffff) {\n byteLength += 3;\n }\n prevCodePoint = codePoint;\n }\n\n return byteLength;\n};\n", "'use strict';\n\nvar truncate = require(\"./lib/truncate\");\nvar getLength = require(\"utf8-byte-length/browser\");\nmodule.exports = truncate.bind(null, getLength);\n", "/*jshint node:true*/\n'use strict';\n\n/**\n * Replaces characters in strings that are illegal/unsafe for filenames.\n * Unsafe characters are either removed or replaced by a substitute set\n * in the optional `options` object.\n *\n * Illegal Characters on Various Operating Systems\n * / ? < > \\ : * | \"\n * https://kb.acronis.com/content/39790\n *\n * Unicode Control codes\n * C0 0x00-0x1f & C1 (0x80-0x9f)\n * http://en.wikipedia.org/wiki/C0_and_C1_control_codes\n *\n * Reserved filenames on Unix-based systems (\".\", \"..\")\n * Reserved filenames in Windows (\"CON\", \"PRN\", \"AUX\", \"NUL\", \"COM1\",\n * \"COM2\", \"COM3\", \"COM4\", \"COM5\", \"COM6\", \"COM7\", \"COM8\", \"COM9\",\n * \"LPT1\", \"LPT2\", \"LPT3\", \"LPT4\", \"LPT5\", \"LPT6\", \"LPT7\", \"LPT8\", and\n * \"LPT9\") case-insesitively and with or without filename extensions.\n *\n * Capped at 255 characters in length.\n * http://unix.stackexchange.com/questions/32795/what-is-the-maximum-allowed-filename-and-folder-size-with-ecryptfs\n *\n * @param {String} input Original filename\n * @param {Object} options {replacement: String | Function }\n * @return {String} Sanitized filename\n */\n\nvar truncate = require(\"truncate-utf8-bytes\");\n\nvar illegalRe = /[\\/\\?<>\\\\:\\*\\|\"]/g;\nvar controlRe = /[\\x00-\\x1f\\x80-\\x9f]/g;\nvar reservedRe = /^\\.+$/;\nvar windowsReservedRe = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\\..*)?$/i;\n\n/**\n * Strip trailing spaces and dots, which are not allowed on some Windows file\n * systems. Does not use a regex to avoid a quadratic ReDoS vulnerability\n * (CWE-1333).\n */\nfunction replaceTrailingDotsAndSpaces(str, replacement) {\n var end = str.length;\n while (end > 0 && (str[end - 1] === '.' || str[end - 1] === ' ')) end--;\n return end < str.length ? str.slice(0, end) + replacement : str;\n}\n\nfunction sanitize(input, replacement) {\n if (typeof input !== 'string') {\n throw new Error('Input must be string');\n }\n var sanitized = input\n .replace(illegalRe, replacement)\n .replace(controlRe, replacement)\n .replace(reservedRe, replacement)\n .replace(windowsReservedRe, replacement);\n sanitized = replaceTrailingDotsAndSpaces(sanitized, replacement);\n return truncate(sanitized, 255);\n}\n\nmodule.exports = function (input, options) {\n var replacement = (options && options.replacement) || '';\n var output = sanitize(input, replacement);\n if (replacement === '') {\n return output;\n }\n return sanitize(output, '');\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", "module.exports = function (max) {\n\n if (!max) throw Error('hashlru must have a max value, of type number, greater than 0')\n\n var size = 0, cache = Object.create(null), _cache = Object.create(null)\n\n function update (key, value) {\n cache[key] = value\n size ++\n if(size >= max) {\n size = 0\n _cache = cache\n cache = Object.create(null)\n }\n }\n\n return {\n has: function (key) {\n return cache[key] !== undefined || _cache[key] !== undefined\n },\n remove: function (key) {\n if(cache[key] !== undefined)\n cache[key] = undefined\n if(_cache[key] !== undefined)\n _cache[key] = undefined\n },\n get: function (key) {\n var v = cache[key]\n if(v !== undefined) return v\n if((v = _cache[key]) !== undefined) {\n update(key, v)\n return v\n }\n },\n set: function (key, value) {\n if(cache[key] !== undefined) cache[key] = value\n else update(key, value)\n },\n clear: function () {\n cache = Object.create(null)\n _cache = Object.create(null)\n }\n }\n}\n\n\n\n\n\n\n\n", "/**\n * @packageDocumentation\n *\n * This module contains utility code that is shared between various Helia\n * modules such as `helia`, `@helia/http`, etc.\n */\n\nimport { keychain } from '@ipshipyard/keychain'\nimport { start, stop, TypedEventEmitter } from '@libp2p/interface'\nimport { dns } from '@multiformats/dns'\nimport { defaultLogger } from 'birnam'\nimport { MemoryBlockstore } from 'blockstore-core'\nimport { MemoryDatastore } from 'datastore-core'\nimport drain from 'it-drain'\nimport { CustomProgressEvent } from 'progress-events'\nimport { PinsImpl } from './pins.ts'\nimport { Routing as RoutingClass } from './routing.ts'\nimport { BlockStorage } from './storage.ts'\nimport { assertDatastoreVersionIsCurrent } from './utils/datastore-version.ts'\nimport { getCodec } from './utils/get-codec.ts'\nimport { getCrypto } from './utils/get-crypto.ts'\nimport { getHasher } from './utils/get-hasher.ts'\nimport { NetworkedStorage } from './utils/networked-storage.ts'\nimport type { BlockStorageInit } from './storage.ts'\nimport type { CodecLoader, GCOptions, HasherLoader, Helia as HeliaInterface, HeliaEvents, Routing, CryptoLoader, Crypto, NodeInfo, Router, HeliaMixin } from '@helia/interface'\nimport type { BlockBroker } from '@helia/interface/blocks'\nimport type { Pins } from '@helia/interface/pins'\nimport type { Keychain, KeychainInit } from '@ipshipyard/keychain'\nimport type { ComponentLogger, Logger, Metrics } from '@libp2p/interface'\nimport type { DNS } from '@multiformats/dns'\nimport type { Blockstore } from 'interface-blockstore'\nimport type { Datastore } from 'interface-datastore'\nimport type { BlockCodec } from 'multiformats'\nimport type { CID } from 'multiformats/cid'\nimport type { MultihashHasher } from 'multiformats/hashes/interface'\n\nexport { AbstractSession } from './abstract-session.ts'\nexport type { AbstractCreateSessionOptions, BlockstoreSessionEvents, AbstractSessionComponents } from './abstract-session.ts'\n\nexport { isCID } from './utils/is-cid.ts'\n\nexport type { BlockStorage, BlockStorageInit }\n\nexport { breadthFirstWalker, depthFirstWalker, naturalOrderWalker } from './graph-walker.ts'\nexport type { GraphWalkerComponents, GraphWalkerInit, GraphNode, GraphWalker } from './graph-walker.ts'\n\n/**\n * Options used to create a Helia node.\n */\nexport interface HeliaInit {\n /**\n * By default Helia stores the node's PeerId in an encrypted form in a\n * libp2p keystore. These options control how that keystore is configured.\n */\n keychain?: KeychainInit\n\n /**\n * The blockstore is where blocks are stored\n */\n blockstore?: Blockstore\n\n /**\n * The datastore is where data is stored\n */\n datastore?: Datastore\n\n /**\n * By default sha256, sha512 and identity hashes are supported for\n * bitswap operations. To bitswap blocks with CIDs using other hashes\n * pass appropriate MultihashHashers here.\n */\n hashers?: MultihashHasher[]\n\n /**\n * An optional function that can load a MultihashHasher on demand. May return\n * a promise.\n */\n loadHasher?(code: number): MultihashHasher | Promise<MultihashHasher>\n\n /**\n * In order to pin CIDs that correspond to a DAG, it's necessary to know\n * how to traverse that DAG. DAGWalkers take a block and yield any CIDs\n * encoded within that block.\n */\n codecs?: Array<BlockCodec<any, any>>\n\n /**\n * An optional function that can load a BlockCodec on demand. May return a\n * promise.\n */\n loadCodec?(code: number): BlockCodec<any, any> | Promise<BlockCodec<any, any>>\n\n /**\n * A list of pre-supported public/private key implementations\n */\n cryptos?: Array<Crypto>\n\n /**\n * Dynamically load a cryptography implementation\n */\n loadCrypto?: CryptoLoader\n\n /**\n * Garbage collection requires preventing blockstore writes during searches\n * for unpinned blocks as DAGs are typically pinned after they've been\n * imported - without locking this could lead to the deletion of blocks while\n * they are being added to the blockstore.\n *\n * By default this lock is held on the current process and other processes\n * will contact this process for access.\n *\n * If Helia is being run in multiple processes, one process must hold the GC\n * lock so use this option to control which process that is.\n *\n * @default true\n */\n holdGcLock?: boolean\n\n /**\n * An optional logging component to pass to libp2p. If not specified the\n * default implementation from libp2p will be used.\n */\n logger?: ComponentLogger\n\n /**\n * A list of strategies used to fetch blocks when they are not present in\n * the local blockstore\n */\n blockBrokers?: Array<BlockBroker | ((components: any) => BlockBroker)>\n\n /**\n * Routers perform operations such as looking up content providers,\n * information about network peers or getting/putting records.\n */\n routers?: Array<Router | ((components: any) => Router)>\n\n /**\n * During provider lookups, peers can be returned from routing implementations\n * with no multiaddrs.\n *\n * This can happen when they've been retrieved from network peers that only\n * store multiaddrs for a limited amount of time.\n *\n * When this happens the peer's info has to be looked up with a further query.\n *\n * To not have this query block the yielding of other providers returned with\n * multiaddrs, a separate queue is used to perform this lookup.\n *\n * This config value controls the concurrency of that queue.\n *\n * @default 5\n */\n providerLookupConcurrency?: number\n\n /**\n * Components used by subclasses\n */\n components?: Record<string, any>\n\n /**\n * An optional DNS implementation used to perform queries for DNS records.\n */\n dns?: DNS\n\n /**\n * A metrics object that can be used to collected arbitrary stats about node\n * usage.\n */\n metrics?: Metrics\n\n /**\n * Limit the maximum supported size of identity hash digests to this value\n *\n * @default 128\n */\n maxIdentityHashDigestLength?: number\n}\n\ninterface Components {\n blockstore: Blockstore\n datastore: Datastore\n logger: ComponentLogger\n blockBrokers: BlockBroker[]\n routing: Routing\n dns: DNS\n keychain: Keychain\n metrics?: Metrics\n getCodec: CodecLoader\n getHasher: HasherLoader\n getCrypto: CryptoLoader\n}\n\nexport class Helia implements HeliaInterface {\n public info: NodeInfo\n public blockstore: BlockStorage\n public datastore: Datastore\n public events: TypedEventEmitter<HeliaEvents<this>>\n public pins: Pins\n public logger: ComponentLogger\n public routing: RoutingClass\n public getCodec: CodecLoader\n public getHasher: HasherLoader\n public getCrypto: CryptoLoader\n public dns: DNS\n public keychain: Keychain\n public metrics?: Metrics\n public status: 'stopped' | 'stopping' | 'starting' | 'started'\n private readonly log: Logger\n private readonly blockBrokers: BlockBroker[]\n private readonly mixins: HeliaMixin[]\n\n constructor (init: HeliaInit & { name: string, version: string }) {\n this.info = {\n name: init.name,\n version: init.version\n }\n this.logger = init.logger ?? defaultLogger()\n this.log = this.logger.forComponent('helia')\n this.getHasher = getHasher(init.hashers, init.loadHasher)\n this.getCodec = getCodec(init.codecs, init.loadCodec)\n this.getCrypto = getCrypto(init.cryptos, init.loadCrypto)\n this.dns = init.dns ?? dns()\n this.metrics = init.metrics\n this.events = new TypedEventEmitter<HeliaEvents<typeof this>>()\n this.status = 'stopped'\n this.mixins = []\n\n // @ts-expect-error routing and keychain are not set\n const components: Components = {\n blockstore: init.blockstore ?? new MemoryBlockstore(),\n datastore: init.datastore ?? new MemoryDatastore(),\n logger: this.logger,\n blockBrokers: [],\n getHasher: this.getHasher,\n getCodec: this.getCodec,\n getCrypto: this.getCrypto,\n dns: this.dns,\n metrics: this.metrics,\n ...(init.components ?? {})\n }\n\n this.keychain = components.keychain = keychain()(components)\n\n this.routing = components.routing = new RoutingClass(components, {\n routers: (init.routers ?? []).flatMap((router: Router | ((components: any) => Router)) => {\n if (typeof router === 'function') {\n router = router(components)\n }\n\n // if the router itself is a router\n const routers = [\n router\n ]\n\n return routers\n }),\n providerLookupConcurrency: init.providerLookupConcurrency\n })\n\n this.blockBrokers = components.blockBrokers = (init.blockBrokers ?? []).map((broker) => {\n if (typeof broker === 'function') {\n broker = broker(components)\n }\n\n return broker\n })\n\n const networkedStorage = new NetworkedStorage(components, init)\n this.pins = new PinsImpl(components.datastore, networkedStorage, this.getCodec)\n this.blockstore = new BlockStorage(networkedStorage, this.pins, this.routing, {\n holdGcLock: init.holdGcLock ?? true\n })\n this.datastore = components.datastore\n }\n\n hasRouter (name: string): boolean {\n return this.routing.hasRouter(name)\n }\n\n addRouter (router: Router): void {\n this.routing.addRouter(router)\n }\n\n hasBlockBroker (name: string): boolean {\n return this.blockBrokers.findIndex(b => b.name === name) !== -1\n }\n\n addBlockBroker (blockBroker: BlockBroker): void {\n this.blockBrokers.push(blockBroker)\n }\n\n addMixin (mixin: HeliaMixin): void {\n this.mixins.push(mixin)\n }\n\n async start (): Promise<this> {\n this.status = 'starting'\n\n await assertDatastoreVersionIsCurrent(this.datastore)\n await start(\n this.blockstore,\n this.datastore,\n this.routing,\n ...this.blockBrokers\n )\n\n for (const mixin of this.mixins) {\n await mixin.start?.(this)\n }\n\n this.status = 'started'\n this.events.dispatchEvent(new CustomEvent('start', { detail: this }))\n\n return this\n }\n\n async stop (): Promise<this> {\n this.status = 'stopping'\n\n for (const mixin of this.mixins) {\n await mixin.stop?.(this)\n }\n\n await stop(\n this.blockstore,\n this.datastore,\n this.routing,\n ...this.blockBrokers\n )\n\n this.status = 'stopped'\n this.events.dispatchEvent(new CustomEvent('stop', { detail: this }))\n\n return this\n }\n\n async gc (options: GCOptions = {}): Promise<void> {\n const releaseLock = await this.blockstore.lock.writeLock()\n\n try {\n const helia = this\n const blockstore = this.blockstore.unwrap()\n\n this.log('gc start')\n\n await drain(blockstore.deleteMany((async function * (): AsyncGenerator<CID> {\n for await (const { cid } of blockstore.getAll()) {\n try {\n if (await helia.pins.isPinned(cid, options)) {\n continue\n }\n\n yield cid\n\n options.onProgress?.(new CustomProgressEvent<CID>('helia:gc:deleted', cid))\n } catch (err: any) {\n helia.log.error('error during gc - %e', err)\n options.onProgress?.(new CustomProgressEvent<Error>('helia:gc:error', err))\n }\n }\n }())))\n } finally {\n releaseLock()\n }\n\n this.log('gc finished')\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<ArrayBuffer> {\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<ArrayBuffer> {\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 <T extends ArrayBufferLike> (value: number, buf: Uint8Array<T>, offset: number = 0): Uint8Array<T> {\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 <T extends ArrayBufferLike> (value: number, buf: Uint8ArrayList<T>, offset: number = 0): Uint8ArrayList<T> {\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<ArrayBuffer>\nexport function encode <T extends ArrayBufferLike> (value: number, buf: Uint8Array<T>, offset?: number): Uint8Array<T>\nexport function encode <T extends ArrayBufferLike> (value: number, buf: Uint8ArrayList<T>, offset?: number): Uint8ArrayList<T>\nexport function encode <B extends ArrayBufferLike, T extends Uint8Array<B> | Uint8ArrayList<B> = Uint8Array<B>> (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", "function isArrayBufferBacked (arr: Uint8Array): arr is Uint8Array<ArrayBuffer> {\n return arr.buffer instanceof ArrayBuffer\n}\n\n/**\n * If the passed `arr` is of type `Uint8Array<ArrayBuffer>`, it is returned\n * unchanged, otherwise a new `Uint8Array<ArrayBuffer>` is created with the\n * data being a copy of the data in the passed `arr`.\n */\nexport function withArrayBuffer (arr: Uint8Array): Uint8Array<ArrayBuffer> {\n if (isArrayBufferBacked(arr)) {\n return arr\n }\n\n return arr.slice()\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 { withArrayBuffer } from 'uint8arrays/with-array-buffer'\nimport { readFloatLE, readDoubleLE } from './float.ts'\nimport { LongBits } from './longbits.ts'\nimport * as utf8 from './utf8.ts'\nimport type { Reader } from '../index.ts'\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<ArrayBuffer>\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 = withArrayBuffer(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<ArrayBuffer> {\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.ts'\nimport type { Codec, DecodeOptions } from './codec.ts'\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.ts'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\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<ArrayBuffer> {\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\n/**\r\n * Normalize binary input to a plain `Uint8Array` backed by an `ArrayBuffer`.\r\n *\r\n * Returns the input itself when it is already a plain `Uint8Array` over an\r\n * `ArrayBuffer`, otherwise a fresh view (or, for `SharedArrayBuffer`-backed\r\n * input, a copy) over the same bytes.\r\n *\r\n * Throws if input is not a recognised binary type.\r\n */\r\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array<ArrayBuffer> {\r\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') {\n return toArrayBufferBackedArray(o)\n }\n if (o instanceof ArrayBuffer) {\n return new Uint8Array(o)\n }\n if (ArrayBuffer.isView(o)) {\n return toArrayBufferBackedArray(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<ArrayBuffer> {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n\nfunction isByteArrayWithArrayBuffer (b?: Uint8Array): b is Uint8Array<ArrayBuffer> {\n return b?.buffer instanceof ArrayBuffer\n}\n\n/**\n * Ensures `b` is backed by an ArrayBuffer - if not a new Uint8Array will be\n * created and the contents of `b` copied into it.\n */\nexport function toArrayBufferBackedArray (b: Uint8Array): Uint8Array<ArrayBuffer> {\n if (isByteArrayWithArrayBuffer(b)) {\n return b\n }\n\n return b.slice()\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.ts'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.ts'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array<ArrayBuffer> }\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<ArrayBuffer> {\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<ArrayBuffer> {\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<ArrayBuffer> {\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<ArrayBuffer> => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabetIdx: Record<string, number>, bitsPerChar: number, name: string): Uint8Array<ArrayBuffer> {\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<ArrayBuffer> {\n return decode(input, alphabetIdx, bitsPerChar, name)\n }\n })\n}\n", "import { rfc4648 } from './base.ts'\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.ts'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n", "import { from } from './base.ts'\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<ArrayBuffer> {\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.ts'\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", "import { baseX } from './base.ts'\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.ts'\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", "import { rfc4648 } from './base.ts'\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.ts'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n", "import { fromString, toString } from '../bytes.ts'\nimport { from } from './base.ts'\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.ts'\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.ts'\nimport type { ArrayBufferView, ByteView } from './interface.ts'\n\nexport const name = 'raw'\nexport const code = 0x55\n\nexport function encode (node: Uint8Array): ByteView<Uint8Array> {\n return coerce(node)\n}\n\nexport function decode (data: ByteView<Uint8Array> | ArrayBufferView<Uint8Array>): Uint8Array {\n return coerce(data)\n}\n", "import { coerce } from '../bytes.ts'\nimport * as Digest from './digest.ts'\nimport type { DigestOptions } from './hasher.ts'\nimport type { SyncMultihashHasher } from './interface.ts'\n\nconst code: 0x0 = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array<ArrayBuffer> = coerce\n\nfunction digest (input: Uint8Array, options?: DigestOptions): Digest.Digest<typeof code, number> {\n if (options?.truncate != null && options.truncate !== input.byteLength) {\n if (options.truncate < 0 || options.truncate > input.byteLength) {\n throw new Error(`Invalid truncate option, must be less than or equal to ${input.byteLength}`)\n }\n\n input = input.subarray(0, options.truncate)\n }\n\n return Digest.create(code, encode(input))\n}\n\nexport const identity: SyncMultihashHasher<0x00> = { code, name, encode, digest }\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, toArrayBufferBackedArray } from '../bytes.ts'\nimport * as varint from '../varint.ts'\nimport type { MultihashDigest } from './interface.ts'\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<ArrayBuffer>\n readonly bytes: Uint8Array<ArrayBuffer>\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 = toArrayBufferBackedArray(digest)\n this.bytes = toArrayBufferBackedArray(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 { from } from './hasher.ts'\n\nfunction sha (name: AlgorithmIdentifier): (data: Uint8Array<ArrayBuffer>) => Promise<Uint8Array<ArrayBuffer>> {\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 Digest from './digest.ts'\nimport type { MultihashHasher } from './interface.ts'\n\ntype Await<T> = Promise<T> | T\n\nconst DEFAULT_MIN_DIGEST_LENGTH = 20\n\nexport interface HasherInit <Name extends string, Code extends number> {\n name: Name\n code: Code\n encode(input: Uint8Array): Await<Uint8Array<ArrayBuffer>>\n\n /**\n * The minimum length a hash is allowed to be truncated to in bytes\n *\n * @default 20\n */\n minDigestLength?: number\n\n /**\n * The maximum length a hash is allowed to be truncated to in bytes. If not\n * specified it will be inferred from the length of the digest.\n */\n maxDigestLength?: number\n}\n\nexport function from <Name extends string, Code extends number> ({ name, code, encode, minDigestLength, maxDigestLength }: HasherInit<Name, Code>): MultihashHasher<Code> {\n return new Hasher(name, code, encode, minDigestLength, maxDigestLength)\n}\n\nexport interface DigestOptions {\n /**\n * Truncate the returned digest to this number of bytes.\n *\n * This may cause the digest method to throw/reject if the passed value is\n * greater than the digest length or below a threshold under which the risk of\n * hash collisions is significant.\n *\n * The actual value of this threshold can depend on the hashing algorithm in\n * use.\n */\n truncate?: number\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<ArrayBuffer>>\n readonly minDigestLength: number\n readonly maxDigestLength?: number\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await<Uint8Array<ArrayBuffer>>, minDigestLength?: number, maxDigestLength?: number) {\n this.name = name\n this.code = code\n this.encode = encode\n this.minDigestLength = minDigestLength ?? DEFAULT_MIN_DIGEST_LENGTH\n this.maxDigestLength = maxDigestLength\n }\n\n digest (input: Uint8Array, options?: DigestOptions): Await<Digest.Digest<Code, number>> {\n if (options?.truncate != null) {\n if (options.truncate < this.minDigestLength) {\n throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`)\n }\n\n if (this.maxDigestLength != null && options.truncate > this.maxDigestLength) {\n throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)\n }\n }\n\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n\n if (result instanceof Uint8Array) {\n return createDigest(result, this.code, options?.truncate)\n }\n\n return result.then(digest => createDigest(digest, this.code, options?.truncate))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n\n/**\n * Create a Digest from the passed uint8array and code, optionally truncating it\n * first.\n */\nfunction createDigest <Code extends number> (digest: Uint8Array, code: Code, truncate?: number): Digest.Digest<Code, number> {\n if (truncate != null && truncate !== digest.byteLength) {\n if (truncate > digest.byteLength) {\n throw new Error(`Invalid truncate option, must be less than or equal to ${digest.byteLength}`)\n }\n\n digest = digest.subarray(0, truncate)\n }\n\n return Digest.create(code, digest)\n}\n", "import { base32 } from './bases/base32.ts'\nimport { base36 } from './bases/base36.ts'\nimport { base58btc } from './bases/base58.ts'\nimport { coerce, toArrayBufferBackedArray } from './bytes.ts'\nimport * as Digest from './hashes/digest.ts'\nimport * as varint from './varint.ts'\nimport type * as API from './link/interface.ts'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.ts'\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<ArrayBuffer>\n readonly '/': Uint8Array<ArrayBuffer>\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 = toArrayBufferBackedArray(bytes)\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = 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 base10 from './bases/base10.ts'\nimport * as base16 from './bases/base16.ts'\nimport * as base2 from './bases/base2.ts'\nimport * as base256emoji from './bases/base256emoji.ts'\nimport * as base32 from './bases/base32.ts'\nimport * as base36 from './bases/base36.ts'\nimport * as base58 from './bases/base58.ts'\nimport * as base64 from './bases/base64.ts'\nimport * as base8 from './bases/base8.ts'\nimport * as identityBase from './bases/identity.ts'\nimport * as json from './codecs/json.ts'\nimport * as raw from './codecs/raw.ts'\nimport * as identity from './hashes/identity.ts'\nimport * as sha2 from './hashes/sha2.ts'\nimport { CID, hasher, digest, varint, bytes } from './index.ts'\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<ArrayBuffer>): 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 from './util/bases.ts'\nimport type { SupportedEncodings } from './util/bases.ts'\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<ArrayBuffer> {\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}`)\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<ArrayBuffer> {\n const SIZE = size ?? 8192\n const MAX = SIZE >>> 1\n let slab: Uint8Array<ArrayBuffer>\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.ts'\nimport { LongBits } from './longbits.ts'\nimport pool from './pool.ts'\nimport * as utf8 from './utf8.ts'\nimport type { Writer } from '../index.ts'\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<ArrayBuffer> {\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<ArrayBuffer> {\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.ts'\nimport type { Codec } from './codec.ts'\n\nexport function encodeMessage <T> (message: Partial<T>, codec: Pick<Codec<T>, 'encode'>): Uint8Array<ArrayBuffer> {\n const w = createWriter()\n\n codec.encode(message, w, {\n lengthDelimited: false\n })\n\n return w.finish()\n}\n", "import { createReader } from './utils/reader.ts'\nimport type { Codec } from './codec.ts'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport function * streamMessage <T> (buf: Uint8Array | Uint8ArrayList, codec: Pick<Codec<T>, 'stream'>, opts?: any): Generator<any> {\n const reader = createReader(buf)\n\n yield * codec.stream(reader, undefined, '$', opts)\n}\n", "import type { Writer, Reader } from './index.ts'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport const CODEC_TYPES = {\n VARINT: 0,\n BIT64: 1,\n LENGTH_DELIMITED: 2,\n START_GROUP: 3,\n END_GROUP: 4,\n BIT32: 5\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 StreamFunction<T> {\n (reader: Reader, length?: number, prefix?: string, opts?: DecodeOptions<T>): Generator<any>\n}\n\nexport interface Codec<T> {\n name: string\n type: number\n encode: EncodeFunction<T>\n decode: DecodeFunction<T>\n stream: StreamFunction<T>\n}\n\nexport function createCodec <T> (name: string, type: number, encode: EncodeFunction<T>, decode: DecodeFunction<T>, stream: StreamFunction<T>): Codec<T> {\n return {\n name,\n type,\n encode,\n decode,\n stream\n }\n}\n", "import { createCodec, CODEC_TYPES } from '../codec.ts'\nimport type { DecodeFunction, EncodeFunction, Codec, StreamFunction } from '../codec.ts'\n\nexport function enumeration <T> (v: any): Codec<T> {\n function findValue (val: any): 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<T> = function enumEncode (val, writer) {\n const enumValue = findValue(val)\n\n writer.int32(enumValue)\n }\n\n const decode: DecodeFunction<any> = function enumDecode (reader) {\n const val = reader.int32()\n\n return findValue(val)\n }\n\n const stream: StreamFunction<T> = function * enumStream (reader) {\n const val = reader.int32()\n\n yield findValue(val)\n }\n\n return createCodec<T>('enum', CODEC_TYPES.VARINT, encode, decode, stream)\n}\n", "import { createCodec, CODEC_TYPES } from '../codec.ts'\nimport type { EncodeFunction, DecodeFunction, Codec, StreamFunction } from '../codec.ts'\n\nexport interface Factory<A, T> {\n new (obj: A): T\n}\n\nexport function message <T> (encode: EncodeFunction<T>, decode: DecodeFunction<T>, stream: StreamFunction<T>): Codec<T> {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode, stream)\n}\n", "import { decodeMessage, encodeMessage, enumeration, message, streamMessage } from 'protons-runtime'\nimport type { Codec, DecodeOptions } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport enum KeyType {\n RSA = 'RSA',\n Ed25519 = 'Ed25519',\n secp256k1 = 'secp256k1',\n ECDSA = 'ECDSA'\n}\n\nenum __KeyTypeValues {\n RSA = 0,\n Ed25519 = 1,\n secp256k1 = 2,\n ECDSA = 3\n}\n\nexport namespace KeyType {\n export const codec = (): Codec<KeyType> => {\n return enumeration<KeyType>(__KeyTypeValues)\n }\n}\n\nexport interface PublicKeyMessage {\n Type?: number\n Data?: Uint8Array\n}\n\nexport namespace PublicKeyMessage {\n let _codec: Codec<PublicKeyMessage>\n\n export const codec = (): Codec<PublicKeyMessage> => {\n if (_codec == null) {\n _codec = message<PublicKeyMessage>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n w.int32(obj.Type)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\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.Type = reader.int32()\n break\n }\n case 2: {\n obj.Data = reader.bytes()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n }, function * (reader, length, prefix, opts = {}) {\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 yield {\n field: `${prefix}.Type`,\n value: reader.int32()\n }\n break\n }\n case 2: {\n yield {\n field: `${prefix}.Data`,\n value: reader.bytes()\n }\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n })\n }\n\n return _codec\n }\n\n export interface PublicKeyMessageTypeFieldEvent {\n field: '$.Type'\n value: number\n }\n\n export interface PublicKeyMessageDataFieldEvent {\n field: '$.Data'\n value: Uint8Array\n }\n\n export function encode (obj: Partial<PublicKeyMessage>): Uint8Array<ArrayBuffer> {\n return encodeMessage(obj, PublicKeyMessage.codec())\n }\n\n export function decode (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<PublicKeyMessage>): PublicKeyMessage {\n return decodeMessage(buf, PublicKeyMessage.codec(), opts)\n }\n\n export function stream (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<PublicKeyMessage>): Generator<PublicKeyMessageTypeFieldEvent | PublicKeyMessageDataFieldEvent> {\n return streamMessage(buf, PublicKeyMessage.codec(), opts)\n }\n}\n\nexport interface PrivateKeyMessage {\n Type?: number\n Data?: Uint8Array\n}\n\nexport namespace PrivateKeyMessage {\n let _codec: Codec<PrivateKeyMessage>\n\n export const codec = (): Codec<PrivateKeyMessage> => {\n if (_codec == null) {\n _codec = message<PrivateKeyMessage>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n w.int32(obj.Type)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\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.Type = reader.int32()\n break\n }\n case 2: {\n obj.Data = reader.bytes()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n }, function * (reader, length, prefix, opts = {}) {\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 yield {\n field: `${prefix}.Type`,\n value: reader.int32()\n }\n break\n }\n case 2: {\n yield {\n field: `${prefix}.Data`,\n value: reader.bytes()\n }\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n })\n }\n\n return _codec\n }\n\n export interface PrivateKeyMessageTypeFieldEvent {\n field: '$.Type'\n value: number\n }\n\n export interface PrivateKeyMessageDataFieldEvent {\n field: '$.Data'\n value: Uint8Array\n }\n\n export function encode (obj: Partial<PrivateKeyMessage>): Uint8Array<ArrayBuffer> {\n return encodeMessage(obj, PrivateKeyMessage.codec())\n }\n\n export function decode (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<PrivateKeyMessage>): PrivateKeyMessage {\n return decodeMessage(buf, PrivateKeyMessage.codec(), opts)\n }\n\n export function stream (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<PrivateKeyMessage>): Generator<PrivateKeyMessageTypeFieldEvent | PrivateKeyMessageDataFieldEvent> {\n return streamMessage(buf, PrivateKeyMessage.codec(), opts)\n }\n}\n", "import bases from './util/bases.ts'\nimport type { SupportedEncodings } from './util/bases.ts'\n\nexport type { SupportedEncodings }\n\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function toString (array: Uint8Array, encoding: SupportedEncodings = 'utf8'): string {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // strip multibase prefix\n return base.encoder.encode(array).substring(1)\n}\n", "import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { SupportedEncodings } from 'uint8arrays/to-string'\n\nconst pathSepS = '/'\nconst pathSepB = new TextEncoder().encode(pathSepS)\nconst pathSep = pathSepB[0]\n\n/**\n * A Key represents the unique identifier of an object.\n * Our Key scheme is inspired by file systems and Google App Engine key model.\n * Keys are meant to be unique across a system. Keys are hierarchical,\n * incorporating more and more specific namespaces. Thus keys can be deemed\n * 'children' or 'ancestors' of other keys:\n * - `new Key('/Comedy')`\n * - `new Key('/Comedy/MontyPython')`\n * Also, every namespace can be parametrized to embed relevant object\n * information. For example, the Key `name` (most specific namespace) could\n * include the object type:\n * - `new Key('/Comedy/MontyPython/Actor:JohnCleese')`\n * - `new Key('/Comedy/MontyPython/Sketch:CheeseShop')`\n * - `new Key('/Comedy/MontyPython/Sketch:CheeseShop/Character:Mousebender')`\n *\n */\nexport class Key {\n private _buf: Uint8Array\n\n /**\n * @param {string | Uint8Array} s\n * @param {boolean} [clean]\n */\n constructor (s: string | Uint8Array, clean?: boolean) {\n if (typeof s === 'string') {\n this._buf = uint8ArrayFromString(s)\n } else if (s instanceof Uint8Array) {\n this._buf = s\n } else {\n throw new Error('Invalid key, should be String of Uint8Array')\n }\n\n if (clean == null) {\n clean = true\n }\n\n if (clean) {\n this.clean()\n }\n\n if (this._buf.byteLength === 0 || this._buf[0] !== pathSep) {\n throw new Error('Invalid key')\n }\n }\n\n /**\n * Convert to the string representation\n *\n * @param {import('uint8arrays/to-string').SupportedEncodings} [encoding] - The encoding to use.\n * @returns {string}\n */\n toString (encoding: SupportedEncodings = 'utf8'): string {\n return uint8ArrayToString(this._buf, encoding)\n }\n\n /**\n * Return the Uint8Array representation of the key\n *\n * @returns {Uint8Array}\n */\n uint8Array (): Uint8Array {\n return this._buf\n }\n\n /**\n * Return string representation of the key\n *\n * @returns {string}\n */\n get [Symbol.toStringTag] (): string {\n return `Key(${this.toString()})`\n }\n\n /**\n * Constructs a key out of a namespace array.\n *\n * @param {Array<string>} list - The array of namespaces\n * @returns {Key}\n *\n * @example\n * ```js\n * Key.withNamespaces(['one', 'two'])\n * // => Key('/one/two')\n * ```\n */\n static withNamespaces (list: string[]): Key {\n return new Key(list.join(pathSepS))\n }\n\n /**\n * Returns a randomly (uuid) generated key.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * Key.random()\n * // => Key('/344502982398')\n * ```\n */\n static random (): Key {\n return new Key(Math.random().toString().substring(2))\n }\n\n /**\n * @param {*} other\n */\n static asKey (other: any): Key | null {\n if (other instanceof Uint8Array || typeof other === 'string') {\n // we can create a key from this\n return new Key(other)\n }\n\n if (typeof other.uint8Array === 'function') {\n // this is an older version or may have crossed the esm/cjs boundary\n return new Key(other.uint8Array())\n }\n\n return null\n }\n\n /**\n * Cleanup the current key\n *\n * @returns {void}\n */\n clean (): void {\n if (this._buf == null || this._buf.byteLength === 0) {\n this._buf = pathSepB\n }\n\n if (this._buf[0] !== pathSep) {\n const bytes = new Uint8Array(this._buf.byteLength + 1)\n bytes.fill(pathSep, 0, 1)\n bytes.set(this._buf, 1)\n this._buf = bytes\n }\n\n // normalize does not remove trailing slashes\n while (this._buf.byteLength > 1 && this._buf[this._buf.byteLength - 1] === pathSep) {\n this._buf = this._buf.subarray(0, -1)\n }\n }\n\n /**\n * Check if the given key is sorted lower than ourself.\n *\n * @param {Key} key - The other Key to check against\n * @returns {boolean}\n */\n less (key: Key): boolean {\n const list1 = this.list()\n const list2 = key.list()\n\n for (let i = 0; i < list1.length; i++) {\n if (list2.length < i + 1) {\n return false\n }\n\n const c1 = list1[i]\n const c2 = list2[i]\n\n if (c1 < c2) {\n return true\n } else if (c1 > c2) {\n return false\n }\n }\n\n return list1.length < list2.length\n }\n\n /**\n * Returns the key with all parts in reversed order.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').reverse()\n * // => Key('/Actor:JohnCleese/MontyPython/Comedy')\n * ```\n */\n reverse (): Key {\n return Key.withNamespaces(this.list().slice().reverse())\n }\n\n /**\n * Returns the `namespaces` making up this Key.\n *\n * @returns {Array<string>}\n */\n namespaces (): string[] {\n return this.list()\n }\n\n /**\n * Returns the \"base\" namespace of this key.\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').baseNamespace()\n * // => 'Actor:JohnCleese'\n * ```\n */\n baseNamespace (): string {\n const ns = this.namespaces()\n return ns[ns.length - 1]\n }\n\n /**\n * Returns the `list` representation of this key.\n *\n * @returns {Array<string>}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').list()\n * // => ['Comedy', 'MontyPythong', 'Actor:JohnCleese']\n * ```\n */\n list (): string[] {\n return this.toString().split(pathSepS).slice(1)\n }\n\n /**\n * Returns the \"type\" of this key (value of last namespace).\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').type()\n * // => 'Actor'\n * ```\n */\n type (): string {\n return namespaceType(this.baseNamespace())\n }\n\n /**\n * Returns the \"name\" of this key (field of last namespace).\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').name()\n * // => 'JohnCleese'\n * ```\n */\n name (): string {\n return namespaceValue(this.baseNamespace())\n }\n\n /**\n * Returns an \"instance\" of this type key (appends value to namespace).\n *\n * @param {string} s - The string to append.\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor').instance('JohnClesse')\n * // => Key('/Comedy/MontyPython/Actor:JohnCleese')\n * ```\n */\n instance (s: string): Key {\n return new Key(this.toString() + ':' + s)\n }\n\n /**\n * Returns the \"path\" of this key (parent + type).\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').path()\n * // => Key('/Comedy/MontyPython/Actor')\n * ```\n */\n path (): Key {\n let p = this.parent().toString()\n if (!p.endsWith(pathSepS)) {\n p += pathSepS\n }\n p += this.type()\n return new Key(p)\n }\n\n /**\n * Returns the `parent` Key of this Key.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key(\"/Comedy/MontyPython/Actor:JohnCleese\").parent()\n * // => Key(\"/Comedy/MontyPython\")\n * ```\n */\n parent (): Key {\n const list = this.list()\n if (list.length === 1) {\n return new Key(pathSepS)\n }\n\n return new Key(list.slice(0, -1).join(pathSepS))\n }\n\n /**\n * Returns the `child` Key of this Key.\n *\n * @param {Key} key - The child Key to add\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython').child(new Key('Actor:JohnCleese'))\n * // => Key('/Comedy/MontyPython/Actor:JohnCleese')\n * ```\n */\n child (key: Key): Key {\n if (this.toString() === pathSepS) {\n return key\n } else if (key.toString() === pathSepS) {\n return this\n }\n\n return new Key(this.toString() + key.toString(), false)\n }\n\n /**\n * Returns whether this key is a prefix of `other`\n *\n * @param {Key} other - The other key to test against\n * @returns {boolean}\n *\n * @example\n * ```js\n * new Key('/Comedy').isAncestorOf('/Comedy/MontyPython')\n * // => true\n * ```\n */\n isAncestorOf (other: Key): boolean {\n if (other.toString() === this.toString()) {\n return false\n }\n\n return other.toString().startsWith(this.toString())\n }\n\n /**\n * Returns whether this key is a contains another as prefix.\n *\n * @param {Key} other - The other Key to test against\n * @returns {boolean}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython').isDecendantOf('/Comedy')\n * // => true\n * ```\n */\n isDecendantOf (other: Key): boolean {\n if (other.toString() === this.toString()) {\n return false\n }\n\n return this.toString().startsWith(other.toString())\n }\n\n /**\n * Checks if this key has only one namespace.\n *\n * @returns {boolean}\n */\n isTopLevel (): boolean {\n return this.list().length === 1\n }\n\n /**\n * Concats one or more Keys into one new Key.\n *\n * @param {Array<Key>} keys - The array of keys to concatenate\n * @returns {Key}\n */\n concat (...keys: Key[]): Key {\n return Key.withNamespaces([...this.namespaces(), ...flatten(keys.map(key => key.namespaces()))])\n }\n}\n\n/**\n * The first component of a namespace. `foo` in `foo:bar`\n *\n * @param {string} ns\n * @returns {string}\n */\nfunction namespaceType (ns: string): string {\n const parts = ns.split(':')\n if (parts.length < 2) {\n return ''\n }\n return parts.slice(0, -1).join(':')\n}\n\n/**\n * The last component of a namespace, `baz` in `foo:bar:baz`.\n *\n * @param {string} ns\n * @returns {string}\n */\nfunction namespaceValue (ns: string): string {\n const parts = ns.split(':')\n return parts[parts.length - 1]\n}\n\n/**\n * Flatten array of arrays (only one level)\n *\n * @template T\n * @param {Array<any>} arr\n * @returns {T[]}\n */\nfunction flatten (arr: any[]): string[] {\n return ([]).concat(...arr)\n}\n", "import { PrivateKeyMessage, PublicKeyMessage } from '@ipshipyard/crypto/pb'\nimport { Key } from 'interface-datastore/key'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base64 } from 'multiformats/bases/base64'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport sanitize from 'sanitize-filename'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { withArrayBuffer } from 'uint8arrays/with-array-buffer'\nimport { DecryptionFailedError, InvalidParametersError } from './errors.ts'\nimport { privateKeyFromPEM } from './legacy.ts'\nimport type { Keychain as KeychainInterface, KeyInfo, GenerateKeyOptions, KeychainComponents, KeychainInit, Cipher, EncryptionResult, CipherOptions } from './index.ts'\nimport type { Crypto, PrivateKey, PublicKey } from '@ipshipyard/crypto'\nimport type { AbortOptions } from 'abort-error'\nimport type { Batch } from 'interface-datastore'\n\nconst keyPrefix = '/pkcs8/'\nconst infoPrefix = '/info/'\n\nconst serviceCapabilities = Symbol.for('@libp2p/service-capabilities')\n\n/**\n * Default options for key derivation for the keychain Data Encryption Key.\n *\n * Inherited from js-libp2p.\n *\n * @see https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#pbkdf2\n */\nconst KEYCHAIN_DEK_INIT = {\n iterations: 10_000,\n salt: uint8ArrayFromString('you should override this value with a crypto secure random number'),\n hash: 'SHA-512',\n algorithm: 'AES-GCM'\n}\n\n/**\n * Each private key is encrypted at rest with a Data Encryption Key created\n * from these parameters.\n *\n * Inherited from js-libp2p.\n */\nconst PRIVATE_KEY_DEK_INIT = {\n iterations: 32_767,\n saltLength: 16,\n ivLength: 12,\n hash: 'SHA-256',\n keyLength: 128,\n algorithm: 'AES-GCM'\n}\n\nconst MIN_PASS_LENGTH = 20\n\n// NIST SP 800-132\nconst NIST = {\n minKeyLength: 112 / 8,\n minSaltLength: 128 / 8,\n minIterations: 1_000\n}\n\nconst KEY_LENGTHS: Record<string, number> = {\n 'SHA-256': 128,\n 'SHA-384': 192,\n 'SHA-512': 256\n}\n\nfunction validateKeyName (name: string): boolean {\n if (name == null) {\n return false\n }\n\n if (typeof name !== 'string') {\n return false\n }\n\n return name === sanitize(name.trim()) && name.length > 0\n}\n\n/**\n * Converts a key name into a datastore name\n */\nfunction dsName (name: string): Key {\n return new Key(keyPrefix + name)\n}\n\n/**\n * Converts a key name into a datastore info name\n */\nfunction dsInfoName (name: string): Key {\n return new Key(infoPrefix + name)\n}\n\nasync function keyId (key: PrivateKey, options?: AbortOptions): Promise<string> {\n const pb = key.toProtobuf()\n const hash = await sha256.digest(pb)\n\n options?.signal?.throwIfAborted()\n\n return base58btc.encode(hash.bytes).substring(1)\n}\n\nfunction getSalt (salt?: string | Uint8Array): Uint8Array<ArrayBuffer> | undefined {\n if (typeof salt === 'string') {\n return uint8ArrayFromString(salt)\n }\n\n if (salt instanceof Uint8Array) {\n return withArrayBuffer(salt)\n }\n}\n\n/**\n * Manages the life cycle of a key. Keys are encrypted at rest using PKCS #8.\n *\n * A key in the store has two entries\n * - '/info/*key-name*', contains the KeyInfo for the key\n * - '/pkcs8/*key-name*', contains the PKCS #8 for the key\n */\nexport class Keychain implements KeychainInterface {\n private readonly components: KeychainComponents\n private readonly self: string\n private cipher: Cipher\n private salt: Uint8Array<ArrayBuffer>\n private keychainDekOptions: DeriveKeyOptions\n private privateKeyDekOptions: PrivateKeyDeriveKeyOptions\n\n /**\n * Creates a new instance of a key chain\n */\n constructor (components: KeychainComponents, init: KeychainInit = {}) {\n this.components = components\n this.self = init.selfKey ?? 'self'\n this.salt = getSalt(init.salt) ?? KEYCHAIN_DEK_INIT.salt\n\n this.keychainDekOptions = {\n iterations: init.iterations ?? KEYCHAIN_DEK_INIT.iterations,\n hash: init.hash ?? KEYCHAIN_DEK_INIT.hash,\n keyLength: KEY_LENGTHS[init.hash ?? KEYCHAIN_DEK_INIT.hash],\n algorithm: KEYCHAIN_DEK_INIT.algorithm\n }\n this.privateKeyDekOptions = {\n iterations: PRIVATE_KEY_DEK_INIT.iterations,\n hash: PRIVATE_KEY_DEK_INIT.hash,\n saltLength: PRIVATE_KEY_DEK_INIT.saltLength,\n ivLength: PRIVATE_KEY_DEK_INIT.ivLength,\n keyLength: PRIVATE_KEY_DEK_INIT.keyLength,\n algorithm: PRIVATE_KEY_DEK_INIT.algorithm\n }\n\n // Enforce NIST SP 800-132\n if (init.password != null && init.password.length < MIN_PASS_LENGTH) {\n throw new Error('password must be least 20 characters')\n }\n /*\n if (this.keyLength < NIST.minKeyLength) {\n throw new Error(`dek.keyLength must be least ${NIST.minKeyLength} bytes`)\n }\n*/\n if (this.salt.byteLength != null && this.salt.byteLength < NIST.minSaltLength) {\n throw new Error(`salt must be least ${NIST.minSaltLength} bytes`)\n }\n\n if (init.iterations != null && init.iterations < NIST.minIterations) {\n throw new Error(`iterations must be least ${NIST.minIterations}`)\n }\n\n if (KEY_LENGTHS[this.keychainDekOptions.hash] == null) {\n throw new InvalidParametersError('Unsupported hash')\n }\n\n this.cipher = createAESCipher(init.password ?? '', this.salt, this.keychainDekOptions, this.privateKeyDekOptions)\n }\n\n readonly [serviceCapabilities]: string[] = [\n '@ipshipyard/keychain'\n ]\n\n async generateKey (name: string, options?: GenerateKeyOptions): Promise<PrivateKey> {\n const crypto = await this.components.getCrypto(options?.type ?? 'Ed25519', options)\n const key = await crypto.generatePrivateKey(options)\n\n return this.importKey(name, key, options)\n }\n\n async importKey (name: string, key: PrivateKey, options?: AbortOptions): Promise<PrivateKey> {\n if (!validateKeyName(name)) {\n throw new InvalidParametersError(`Invalid key name '${name}'`)\n }\n\n if (key == null) {\n throw new InvalidParametersError('Key is required')\n }\n\n const exists = await this.components.datastore.has(dsName(name), options)\n\n if (exists) {\n throw new InvalidParametersError(`Key '${name}' already exists`)\n }\n\n const batch = this.components.datastore.batch()\n await this._importKey(name, key, this.cipher, batch, options)\n await batch.commit(options)\n\n return key\n }\n\n private async _importKey (name: string, privateKey: PrivateKey, cipher: Cipher, batch: Batch, options?: AbortOptions): Promise<void> {\n const pb = privateKey.toProtobuf()\n const result = await cipher.encrypt(pb)\n const cipherText = uint8ArrayConcat([\n result.salt,\n result.iv,\n result.cipherText\n ], result.salt.byteLength + result.iv.byteLength + result.cipherText.byteLength)\n const encodedText = base64.encode(cipherText)\n\n const keyInfo: KeyInfo = {\n name,\n id: await keyId(privateKey, options)\n }\n\n batch.put(dsName(name), uint8ArrayFromString(encodedText))\n batch.put(dsInfoName(name), uint8ArrayFromString(JSON.stringify(keyInfo)))\n }\n\n async exportKey (name: string, options?: AbortOptions): Promise<PrivateKey> {\n if (!validateKeyName(name)) {\n throw new InvalidParametersError(`Invalid key name '${name}'`)\n }\n\n return this._exportKey(name, this.cipher, options)\n }\n\n private async _exportKey (name: string, cipher: Cipher, options?: AbortOptions): Promise<PrivateKey> {\n const keyBuf = await this.components.datastore.get(dsName(name), options)\n const keyText = uint8ArrayToString(keyBuf)\n let cryptoImpl: Crypto | undefined\n\n // if the stored key is encrypted PEM it's legacy RSA, otherwise derive\n // from the protobuf data\n if (keyText.includes('BEGIN ENCRYPTED PRIVATE KEY')) {\n return privateKeyFromPEM(keyText, cipher, options)\n }\n\n try {\n const decoded = base64.decode(keyText)\n const salt = decoded.subarray(0, 16)\n const iv = decoded.subarray(16, 16 + 12)\n const cipherText = decoded.subarray(16 + 12)\n const plainText = await cipher.decrypt(salt, iv, cipherText, options)\n const pb = PrivateKeyMessage.decode(plainText)\n\n if (pb.Type == null) {\n throw new DecryptionFailedError('Unknown key type')\n }\n\n cryptoImpl = await this.components.getCrypto(pb.Type, options)\n return await cryptoImpl.privateKeyFromProtobuf(plainText)\n } catch (err: any) {\n if (err.name === 'OperationError') {\n throw new DecryptionFailedError(err.message)\n }\n\n throw err\n }\n }\n\n async removeKey (name: string, options?: AbortOptions): Promise<void> {\n if (!validateKeyName(name) || name === this.self) {\n throw new InvalidParametersError(`Invalid key name '${name}'`)\n }\n\n const batch = this.components.datastore.batch()\n batch.delete(dsName(name))\n batch.delete(dsInfoName(name))\n await batch.commit(options)\n }\n\n /**\n * List all the keys\n */\n async * listKeys (options?: AbortOptions): AsyncGenerator <KeyInfo> {\n const query = {\n prefix: infoPrefix\n }\n\n for await (const value of this.components.datastore.query(query, options)) {\n yield JSON.parse(uint8ArrayToString(value.value))\n }\n }\n\n /**\n * Rename a key\n *\n * @param {string} oldName - The old local key name; must already exist.\n * @param {string} newName - The new local key name; must not already exist.\n * @returns {Promise<KeyInfo>}\n */\n async renameKey (oldName: string, newName: string, options?: AbortOptions): Promise<void> {\n if (!validateKeyName(oldName) || oldName === this.self) {\n throw new InvalidParametersError(`Invalid old key name '${oldName}'`)\n }\n\n if (!validateKeyName(newName) || newName === this.self) {\n throw new InvalidParametersError(`Invalid new key name '${newName}'`)\n }\n\n const oldDatastoreName = dsName(oldName)\n const newDatastoreName = dsName(newName)\n const oldInfoName = dsInfoName(oldName)\n const newInfoName = dsInfoName(newName)\n\n const exists = await this.components.datastore.has(newDatastoreName, options)\n\n if (exists) {\n throw new InvalidParametersError(`Key '${newName}' already exists`)\n }\n\n const pem = await this.components.datastore.get(oldDatastoreName, options)\n const res = await this.components.datastore.get(oldInfoName, options)\n\n const keyInfo: KeyInfo = JSON.parse(uint8ArrayToString(res))\n keyInfo.name = newName\n\n const batch = this.components.datastore.batch()\n batch.put(newDatastoreName, pem)\n batch.put(newInfoName, uint8ArrayFromString(JSON.stringify(keyInfo)))\n batch.delete(oldDatastoreName)\n batch.delete(oldInfoName)\n\n await batch.commit(options)\n }\n\n /**\n * Rotate keychain password and re-encrypt all associated keys\n */\n async rotateKeychainPass (password: string, options?: AbortOptions): Promise<void> {\n if (typeof password !== 'string') {\n throw new InvalidParametersError(`Invalid new pass type '${typeof password}'`)\n }\n\n if (password.length < MIN_PASS_LENGTH) {\n throw new InvalidParametersError(`Invalid pass length ${password.length}, must be at least ${MIN_PASS_LENGTH}`)\n }\n\n const oldCipher = this.cipher\n const newCipher = this.cipher = createAESCipher(password, this.salt, this.keychainDekOptions, this.privateKeyDekOptions)\n\n const batch = this.components.datastore.batch()\n\n for await (const info of this.listKeys(options)) {\n const key = await this._exportKey(info.name, oldCipher)\n\n // Update stored key\n await this._importKey(info.name, key, newCipher, batch, options)\n }\n\n await batch.commit(options)\n }\n\n async loadPublicKeyFromProtobuf (buf: Uint8Array, options?: AbortOptions): Promise<PublicKey> {\n const pb = PublicKeyMessage.decode(buf)\n\n if (pb.Type == null) {\n throw new InvalidParametersError('Protobuf was missing Type')\n }\n\n const crypto = await this.components.getCrypto(pb.Type, options)\n\n return crypto.publicKeyFromProtobuf(buf, options)\n }\n}\n\n/**\n * WebKit on Linux does not support deriving a key from an empty PBKDF2 key.\n * So, as a workaround, we provide the generated key as a constant.\n *\n * Generated via:\n *\n * ```ts\n * const key = await crypto.subtle.importKey('raw', new Uint8Array(0), {\n * name: 'PBKDF2'\n * }, false, ['deriveKey'])\n *\n * const derivedKey = await crypto.subtle.deriveKey({\n * name: 'PBKDF2',\n * salt: new Uint8Array(16),\n * iterations: 32767,\n * hash: {\n * name: 'SHA-256'\n * }\n * }, key, {\n * name: 'AES-GCM',\n * length: 128\n * }, true, ['encrypt', 'decrypt'])\n *\n * const jwk = await crypto.subtle.exportKey('jwk', derivedKey)\n * ```\n */\nconst derivedEmptyPasswordKey = {\n alg: 'A128GCM',\n ext: true,\n /* spell-checker:disable-next-line */\n k: 'scm9jmO_4BJAgdwWGVulLg',\n key_ops: ['encrypt', 'decrypt'],\n kty: 'oct'\n}\n\ninterface DeriveKeyOptions {\n iterations: number\n hash: string\n keyLength: number\n algorithm: string\n}\n\ninterface PrivateKeyDeriveKeyOptions extends DeriveKeyOptions {\n /**\n * A random salt will be generated of this many bytes\n *\n * @default 16\n */\n saltLength: number\n\n /**\n * A random initialization vector will be generated of this many bytes\n *\n * @default 12\n */\n ivLength: number\n}\n\n// Based on code from https://github.com/luke-park/SecureCompatibleEncryptionExamples\n\nfunction createAESCipher (password: string, salt: Uint8Array<ArrayBuffer>, keychainDekOpts: DeriveKeyOptions, privateKeyDekOpts: PrivateKeyDeriveKeyOptions): Cipher {\n let keychainDek: string | undefined\n\n async function deriveKey (password: string, salt: Uint8Array, usages: KeyUsage[], opts: DeriveKeyOptions): Promise<CryptoKey> {\n let cryptoKey: CryptoKey\n const pass = uint8ArrayFromString(password)\n const rawKey = await crypto.subtle.importKey('raw', pass, {\n name: 'PBKDF2'\n }, false, ['deriveKey'])\n\n try {\n cryptoKey = await crypto.subtle.deriveKey({\n name: 'PBKDF2',\n salt: withArrayBuffer(salt),\n iterations: opts.iterations,\n hash: {\n name: opts.hash\n }\n }, rawKey, {\n name: opts.algorithm ?? 'AES-GCM',\n length: opts.keyLength\n }, true, usages)\n } catch (err) {\n if (password === '') {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, {\n name: opts.algorithm ?? 'AES-GCM'\n }, true, usages)\n } else {\n throw err\n }\n }\n\n return cryptoKey\n }\n\n async function createKeychainDek (): Promise<string> {\n if (password === '') {\n return password\n }\n\n const key = await deriveKey(password, salt, ['encrypt', 'decrypt'], keychainDekOpts)\n const jwk = await crypto.subtle.exportKey('jwk', key)\n\n return jwk.k ?? ''\n }\n\n /**\n * Encrypt data using the derived encryption key\n */\n async function encrypt (data: Uint8Array<ArrayBuffer>, opts?: AbortOptions): Promise<EncryptionResult> {\n if (keychainDek == null) {\n keychainDek = await createKeychainDek()\n }\n\n const salt = crypto.getRandomValues(new Uint8Array(privateKeyDekOpts.saltLength))\n const iv = crypto.getRandomValues(new Uint8Array(privateKeyDekOpts.ivLength))\n const cryptoKey = await deriveKey(keychainDek, salt, ['encrypt'], privateKeyDekOpts)\n const ciphertext = await crypto.subtle.encrypt({\n name: 'AES-GCM',\n iv\n }, cryptoKey, data)\n\n opts?.signal?.throwIfAborted()\n\n return {\n salt,\n iv,\n cipherText: new Uint8Array(ciphertext)\n }\n }\n\n /**\n * Decrypt data using the derived encryption key\n */\n async function decrypt (salt: Uint8Array, iv: Uint8Array, cipherText: Uint8Array, opts?: CipherOptions): Promise<Uint8Array<ArrayBuffer>> {\n if (keychainDek == null) {\n keychainDek = await createKeychainDek()\n }\n\n const cryptoKey = await deriveKey(keychainDek, salt, ['decrypt'], {\n iterations: opts?.iterations ?? privateKeyDekOpts.iterations,\n keyLength: opts?.keyLength ?? privateKeyDekOpts.keyLength,\n hash: opts?.hash ?? privateKeyDekOpts.hash,\n algorithm: opts?.algorithm ?? 'AES-GCM'\n })\n\n const plaintext = await crypto.subtle.decrypt({\n name: opts?.algorithm ?? 'AES-GCM',\n iv: withArrayBuffer(iv)\n }, cryptoKey, withArrayBuffer(cipherText))\n\n opts?.signal?.throwIfAborted()\n\n return new Uint8Array(plaintext)\n }\n\n return {\n encrypt,\n decrypt\n }\n}\n", "function isByteArrayWithArrayBuffer (b?: Uint8Array): b is Uint8Array<ArrayBuffer> {\n return b?.buffer instanceof ArrayBuffer\n}\n\n/**\n * To guarantee Uint8Array semantics, convert nodejs Buffers\n * into vanilla Uint8Arrays\n */\nexport function asUint8Array (buf: Uint8Array): Uint8Array<ArrayBuffer> {\n if (isByteArrayWithArrayBuffer(buf)) {\n return buf\n }\n\n const b = buf.slice()\n\n return new Uint8Array(b.buffer, 0, b.byteLength)\n}\n", "import { allocUnsafe } from '#alloc'\nimport { asUint8Array } from '#util/as-uint8array'\n\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nexport function concat (arrays: Uint8Array[], length?: number): Uint8Array<ArrayBuffer> {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0)\n }\n\n const output = allocUnsafe(length)\n let offset = 0\n\n for (const arr of arrays) {\n output.set(arr, offset)\n offset += arr.length\n }\n\n return asUint8Array(output)\n}\n", "export class InvalidParametersError extends Error {\n static name = 'InvalidParametersError'\n name = 'InvalidParametersError'\n}\n\nexport class DecryptionFailedError extends Error {\n static name = 'DecryptionFailedError'\n name = 'DecryptionFailedError'\n}\n", "/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n", "/**\n * @packageDocumentation\n *\n * A class that lets you do operations over a list of Uint8Arrays without\n * copying them.\n *\n * ```js\n * import { Uint8ArrayList } from 'uint8arraylist'\n *\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray()\n * // -> Uint8Array([0, 1, 2, 3, 4, 5])\n *\n * list.consume(3)\n * list.subarray()\n * // -> Uint8Array([3, 4, 5])\n *\n * // you can also iterate over the list\n * for (const buf of list) {\n * // ..do something with `buf`\n * }\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ## Converting Uint8ArrayLists to Uint8Arrays\n *\n * There are two ways to turn a `Uint8ArrayList` into a `Uint8Array` - `.slice` and `.subarray` and one way to turn a `Uint8ArrayList` into a `Uint8ArrayList` with different contents - `.sublist`.\n *\n * ### slice\n *\n * Slice follows the same semantics as [Uint8Array.slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice) in that it creates a new `Uint8Array` and copies bytes into it using an optional offset & length.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.slice(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ### subarray\n *\n * Subarray attempts to follow the same semantics as [Uint8Array.subarray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray) with one important different - this is a no-copy operation, unless the requested bytes span two internal buffers in which case it is a copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0]) - no-copy\n *\n * list.subarray(2, 5)\n * // -> Uint8Array([2, 3, 4]) - copy\n * ```\n *\n * ### sublist\n *\n * Sublist creates and returns a new `Uint8ArrayList` that shares the underlying buffers with the original so is always a no-copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.sublist(0, 1)\n * // -> Uint8ArrayList([0]) - no-copy\n *\n * list.sublist(2, 5)\n * // -> Uint8ArrayList([2], [3, 4]) - no-copy\n * ```\n *\n * ## Inspiration\n *\n * Borrows liberally from [bl](https://www.npmjs.com/package/bl) but only uses native JS types.\n */\nimport { allocUnsafe, alloc } from 'uint8arrays/alloc'\nimport { concat } from 'uint8arrays/concat'\nimport { equals } from 'uint8arrays/equals'\n\nconst symbol = Symbol.for('@achingbrain/uint8arraylist')\n\nexport type Appendable<T extends ArrayBufferLike = ArrayBuffer> = Uint8ArrayList<T> | Uint8Array<T>\n\nfunction findBufAndOffset (bufs: Uint8Array[], index: number): { buf: Uint8Array, index: number } {\n if (index == null || index < 0) {\n throw new RangeError('index is out of bounds')\n }\n\n let offset = 0\n\n for (const buf of bufs) {\n const bufEnd = offset + buf.byteLength\n\n if (index < bufEnd) {\n return {\n buf,\n index: index - offset\n }\n }\n\n offset = bufEnd\n }\n\n throw new RangeError('index is out of bounds')\n}\n\n/**\n * Check if object is a CID instance\n *\n * @example\n *\n * ```js\n * import { isUint8ArrayList, Uint8ArrayList } from 'uint8arraylist'\n *\n * isUint8ArrayList(true) // false\n * isUint8ArrayList([]) // false\n * isUint8ArrayList(new Uint8ArrayList()) // true\n * ```\n */\nexport function isUint8ArrayList (value: any): value is Uint8ArrayList {\n return Boolean(value?.[symbol])\n}\n\nexport class Uint8ArrayList <T extends ArrayBufferLike = ArrayBufferLike> implements Iterable<Uint8Array<T>> {\n private bufs: Uint8Array<T>[]\n public length: number\n public readonly [symbol] = true\n\n constructor (...data: Appendable<T>[]) {\n this.bufs = []\n this.length = 0\n\n if (data.length > 0) {\n this.appendAll(data)\n }\n }\n\n * [Symbol.iterator] (): Iterator<Uint8Array<T>> {\n yield * this.bufs\n }\n\n get byteLength (): number {\n return this.length\n }\n\n /**\n * Add one or more `bufs` to the end of this Uint8ArrayList\n */\n append (...bufs: Appendable<T>[]): void {\n this.appendAll(bufs)\n }\n\n /**\n * Add all `bufs` to the end of this Uint8ArrayList\n */\n appendAll (bufs: Appendable<T>[]): void {\n let length = 0\n\n for (const buf of bufs) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.push(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n for (const chunk of buf.bufs) {\n this.bufs.push(chunk)\n }\n } else {\n throw new Error('Could not append value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Add one or more `bufs` to the start of this Uint8ArrayList\n */\n prepend (...bufs: Appendable<T>[]): void {\n this.prependAll(bufs)\n }\n\n /**\n * Add all `bufs` to the start of this Uint8ArrayList\n */\n prependAll (bufs: Appendable<T>[]): void {\n let length = 0\n\n for (const buf of bufs.reverse()) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.unshift(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.unshift(...buf.bufs)\n } else {\n throw new Error('Could not prepend value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Read the value at `index`\n */\n get (index: number): number {\n const res = findBufAndOffset(this.bufs, index)\n\n return res.buf[res.index]\n }\n\n /**\n * Set the value at `index` to `value`\n */\n set (index: number, value: number): void {\n const res = findBufAndOffset(this.bufs, index)\n\n res.buf[res.index] = value\n }\n\n /**\n * Copy bytes from `buf` to the index specified by `offset`\n */\n write (buf: Appendable<T | ArrayBuffer>, offset: number = 0): void {\n if (buf instanceof Uint8Array) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf[i])\n }\n } else if (isUint8ArrayList(buf)) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf.get(i))\n }\n } else {\n throw new Error('Could not write value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n /**\n * Remove bytes from the front of the pool\n */\n consume (bytes: number): void {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes)\n\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) {\n return\n }\n\n // if consuming all bytes, skip iterating\n if (bytes === this.byteLength) {\n this.bufs = []\n this.length = 0\n return\n }\n\n while (this.bufs.length > 0) {\n if (bytes >= this.bufs[0].byteLength) {\n bytes -= this.bufs[0].byteLength\n this.length -= this.bufs[0].byteLength\n this.bufs.shift()\n } else {\n this.bufs[0] = this.bufs[0].subarray(bytes)\n this.length -= bytes\n break\n }\n }\n }\n\n /**\n * Extracts a section of an array and returns a new array.\n *\n * This is a copy operation as it is with Uint8Arrays and Arrays\n * - note this is different to the behaviour of Node Buffers.\n */\n slice (beginInclusive?: number, endExclusive?: number): Uint8Array<ArrayBuffer> {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n return concat(bufs, length)\n }\n\n /**\n * Returns a section of the array from the given start and end element index.\n *\n * This is a no-copy operation where the data extracted data comes from a\n * single Uint8Array internally, otherwise it is a copy operation.\n */\n subarray (beginInclusive?: number, endExclusive?: number): Uint8Array<T | ArrayBuffer> {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n if (bufs.length === 1) {\n return bufs[0]\n }\n\n return concat(bufs, length)\n }\n\n /**\n * Returns a new Uint8ArrayList from the given start and end element index.\n *\n * This is a no-copy operation.\n */\n sublist (beginInclusive?: number, endExclusive?: number): Uint8ArrayList<T> {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n const list = new Uint8ArrayList<T>()\n list.length = length\n // don't loop, just set the bufs\n list.bufs = bufs\n\n return list\n }\n\n private _subList (beginInclusive?: number, endExclusive?: number): { bufs: Uint8Array<T>[], length: number } {\n beginInclusive = beginInclusive ?? 0\n endExclusive = endExclusive ?? this.length\n\n if (beginInclusive < 0) {\n beginInclusive = this.length + beginInclusive\n }\n\n if (endExclusive < 0) {\n endExclusive = this.length + endExclusive\n }\n\n if (beginInclusive < 0 || endExclusive > this.length) {\n throw new RangeError('index is out of bounds')\n }\n\n if (beginInclusive === endExclusive) {\n return { bufs: [], length: 0 }\n }\n\n if (beginInclusive === 0 && endExclusive === this.length) {\n return { bufs: [...this.bufs], length: this.length }\n }\n\n const bufs: Uint8Array<T>[] = []\n let offset = 0\n\n for (let i = 0; i < this.bufs.length; i++) {\n const buf = this.bufs[i]\n const bufStart = offset\n const bufEnd = bufStart + buf.byteLength\n\n // for next loop\n offset = bufEnd\n\n if (beginInclusive >= bufEnd) {\n // start after this buf\n continue\n }\n\n const sliceStartInBuf = beginInclusive >= bufStart && beginInclusive < bufEnd\n const sliceEndsInBuf = endExclusive > bufStart && endExclusive <= bufEnd\n\n if (sliceStartInBuf && sliceEndsInBuf) {\n // slice is wholly contained within this buffer\n if (beginInclusive === bufStart && endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n const start = beginInclusive - bufStart\n bufs.push(buf.subarray(start, start + (endExclusive - beginInclusive)))\n break\n }\n\n if (sliceStartInBuf) {\n // slice starts in this buffer\n if (beginInclusive === 0) {\n // requested whole buffer\n bufs.push(buf)\n continue\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(beginInclusive - bufStart))\n continue\n }\n\n if (sliceEndsInBuf) {\n if (endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(0, endExclusive - bufStart))\n break\n }\n\n // slice started before this buffer and ends after it\n bufs.push(buf)\n }\n\n return { bufs, length: endExclusive - beginInclusive }\n }\n\n indexOf (search: Uint8ArrayList | Uint8Array, offset: number = 0): number {\n if (!isUint8ArrayList(search) && !(search instanceof Uint8Array)) {\n throw new TypeError('The \"value\" argument must be a Uint8ArrayList or Uint8Array')\n }\n\n const needle = search instanceof Uint8Array ? search : search.subarray()\n\n offset = Number(offset ?? 0)\n\n if (isNaN(offset)) {\n offset = 0\n }\n\n if (offset < 0) {\n offset = this.length + offset\n }\n\n if (offset < 0) {\n offset = 0\n }\n\n if (search.length === 0) {\n return offset > this.length ? this.length : offset\n }\n\n // https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm\n const M: number = needle.byteLength\n\n if (M === 0) {\n throw new TypeError('search must be at least 1 byte long')\n }\n\n // radix\n const radix: number = 256\n const rightmostPositions: Int32Array = new Int32Array(radix)\n\n // position of the rightmost occurrence of the byte c in the pattern\n for (let c: number = 0; c < radix; c++) {\n // -1 for bytes not in pattern\n rightmostPositions[c] = -1\n }\n\n for (let j = 0; j < M; j++) {\n // rightmost position for bytes in pattern\n rightmostPositions[needle[j]] = j\n }\n\n // Return offset of first match, -1 if no match\n const right = rightmostPositions\n const lastIndex = this.byteLength - needle.byteLength\n const lastPatIndex = needle.byteLength - 1\n let skip: number\n\n for (let i = offset; i <= lastIndex; i += skip) {\n skip = 0\n\n for (let j = lastPatIndex; j >= 0; j--) {\n const char: number = this.get(i + j)\n\n if (needle[j] !== char) {\n skip = Math.max(1, j - right[char])\n break\n }\n }\n\n if (skip === 0) {\n return i\n }\n }\n\n return -1\n }\n\n getInt8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt8(0)\n }\n\n setInt8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getInt16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt16(0, littleEndian)\n }\n\n setInt16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getInt32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt32(0, littleEndian)\n }\n\n setInt32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigInt64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigInt64(0, littleEndian)\n }\n\n setBigInt64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigInt64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint8(0)\n }\n\n setUint8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getUint16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint16(0, littleEndian)\n }\n\n setUint16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint32(0, littleEndian)\n }\n\n setUint32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigUint64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigUint64(0, littleEndian)\n }\n\n setBigUint64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigUint64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat32(0, littleEndian)\n }\n\n setFloat32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat64 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat64(0, littleEndian)\n }\n\n setFloat64 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n equals (other: any): other is Uint8ArrayList {\n if (other == null) {\n return false\n }\n\n if (!(other instanceof Uint8ArrayList)) {\n return false\n }\n\n if (other.bufs.length !== this.bufs.length) {\n return false\n }\n\n for (let i = 0; i < this.bufs.length; i++) {\n if (!equals(this.bufs[i], other.bufs[i])) {\n return false\n }\n }\n\n return true\n }\n\n /**\n * Create a Uint8ArrayList from a pre-existing list of Uint8Arrays. Use this\n * method if you know the total size of all the Uint8Arrays ahead of time.\n */\n static fromUint8Arrays <T extends ArrayBufferLike> (bufs: Uint8Array<T>[], length?: number): Uint8ArrayList<T> {\n const list = new Uint8ArrayList<T>()\n list.bufs = bufs\n\n if (length == null) {\n length = bufs.reduce((acc, curr) => acc + curr.byteLength, 0)\n }\n\n list.length = length\n\n return list\n }\n}\n\n/*\nfunction indexOf (needle: Uint8Array, haystack: Uint8Array, offset = 0) {\n for (let i = offset; i < haystack.byteLength; i++) {\n for (let j = 0; j < needle.length; j++) {\n if (haystack[i + j] !== needle[j]) {\n break\n }\n\n if (j === needle.byteLength -1) {\n return i\n }\n }\n\n if (haystack.byteLength - i < needle.byteLength) {\n break\n }\n }\n\n return -1\n}\n*/\n", "import { Uint8ArrayList } from 'uint8arraylist'\nimport { withArrayBuffer } from 'uint8arrays/with-array-buffer'\n\nexport interface Context {\n offset: number\n}\n\nconst TAG_MASK = parseInt('11111', 2)\nconst LONG_LENGTH_MASK = parseInt('10000000', 2)\nconst LONG_LENGTH_BYTES_MASK = parseInt('01111111', 2)\n\ninterface Decoder {\n (buf: Uint8Array, context: Context): any\n}\n\nconst decoders: Record<number, Decoder> = {\n 0x0: readSequence,\n 0x1: readSequence,\n 0x2: readInteger,\n 0x3: readBitString,\n 0x4: readOctetString,\n 0x5: readNull,\n 0x6: readObjectIdentifier,\n 0x10: readSequence,\n 0x16: readSequence,\n 0x30: readSequence\n}\n\nexport function decodeDer (buf: Uint8Array, context: Context = { offset: 0 }): any {\n const tag = buf[context.offset] & TAG_MASK\n context.offset++\n\n if (decoders[tag] != null) {\n return decoders[tag](buf, context)\n }\n\n throw new Error('No decoder for tag 0x' + tag.toString(16).padStart(2, '0'))\n}\n\nfunction readLength (buf: Uint8Array, context: Context): number {\n let length = 0\n\n if ((buf[context.offset] & LONG_LENGTH_MASK) === LONG_LENGTH_MASK) {\n // long length\n const count = buf[context.offset] & LONG_LENGTH_BYTES_MASK\n let str = '0x'\n context.offset++\n\n for (let i = 0; i < count; i++, context.offset++) {\n str += buf[context.offset].toString(16).padStart(2, '0')\n }\n\n length = parseInt(str, 16)\n } else {\n length = buf[context.offset]\n context.offset++\n }\n\n return length\n}\n\nfunction readSequence (buf: Uint8Array, context: Context): any[] {\n readLength(buf, context)\n const entries: any[] = []\n\n while (true) {\n if (context.offset >= buf.byteLength) {\n break\n }\n\n const result = decodeDer(buf, context)\n\n if (result === null) {\n break\n }\n\n entries.push(result)\n }\n\n return entries\n}\n\nfunction readInteger (buf: Uint8Array, context: Context): Uint8Array {\n const length = readLength(buf, context)\n const start = context.offset\n const end = context.offset + length\n\n const vals: number[] = []\n\n for (let i = start; i < end; i++) {\n if (i === start && buf[i] === 0) {\n continue\n }\n\n vals.push(buf[i])\n }\n\n context.offset += length\n\n return Uint8Array.from(vals)\n}\n\nfunction readObjectIdentifier (buf: Uint8Array, context: Context): string {\n const count = readLength(buf, context)\n const finalOffset = context.offset + count\n\n const byte = buf[context.offset]\n context.offset++\n\n let val1 = 0\n let val2 = 0\n\n if (byte < 40) {\n val1 = 0\n val2 = byte\n } else if (byte < 80) {\n val1 = 1\n val2 = byte - 40\n } else {\n val1 = 2\n val2 = byte - 80\n }\n\n let oid = `${val1}.${val2}`\n let num: number[] = []\n\n while (context.offset < finalOffset) {\n const byte = buf[context.offset]\n context.offset++\n\n // remove msb\n num.push(byte & 0b01111111)\n\n if (byte < 128) {\n num.reverse()\n\n // reached the end of the encoding\n let val = 0\n\n for (let i = 0; i < num.length; i++) {\n val += num[i] << (i * 7)\n }\n\n oid += `.${val}`\n num = []\n }\n }\n\n return oid\n}\n\nfunction readNull (buf: Uint8Array, context: Context): null {\n context.offset++\n\n return null\n}\n\nfunction readBitString (buf: Uint8Array, context: Context): any {\n const length = readLength(buf, context)\n const unusedBits = buf[context.offset]\n context.offset++\n const bytes = buf.subarray(context.offset, context.offset + length - 1)\n context.offset += length\n\n if (unusedBits !== 0) {\n // need to shift all bytes along by this many bits\n throw new Error('Unused bits in bit string is unimplemented')\n }\n\n return bytes\n}\n\nfunction readOctetString (buf: Uint8Array, context: Context): any {\n const length = readLength(buf, context)\n const bytes = buf.subarray(context.offset, context.offset + length)\n context.offset += length\n\n return bytes\n}\n\nfunction encodeNumber (value: number): Uint8ArrayList<ArrayBuffer> {\n let number = value.toString(16)\n\n if (number.length % 2 === 1) {\n number = '0' + number\n }\n\n const array = new Uint8ArrayList<ArrayBuffer>()\n\n for (let i = 0; i < number.length; i += 2) {\n array.append(Uint8Array.from([parseInt(`${number[i]}${number[i + 1]}`, 16)]))\n }\n\n return array\n}\n\nfunction encodeLength (bytes: { byteLength: number }): Uint8Array<ArrayBuffer> | Uint8ArrayList<ArrayBuffer> {\n if (bytes.byteLength < 128) {\n return Uint8Array.from([bytes.byteLength])\n }\n\n // long length\n const length = encodeNumber(bytes.byteLength)\n\n return new Uint8ArrayList(\n Uint8Array.from([\n length.byteLength | LONG_LENGTH_MASK\n ]),\n length\n )\n}\n\nexport function encodeInteger (value: Uint8Array | Uint8ArrayList): Uint8ArrayList {\n const contents = new Uint8ArrayList()\n\n const mask = 0b10000000\n const positive = (value.subarray()[0] & mask) === mask\n\n if (positive) {\n contents.append(Uint8Array.from([0]))\n }\n\n contents.append(value)\n\n return new Uint8ArrayList(\n Uint8Array.from([0x02]),\n encodeLength(contents),\n contents\n )\n}\n\nexport function encodeBitString (value: Uint8Array | Uint8ArrayList): Uint8ArrayList {\n // unused bits is always 0 with full-byte-only values\n const unusedBits = Uint8Array.from([0])\n\n const contents = new Uint8ArrayList(\n unusedBits,\n value\n )\n\n return new Uint8ArrayList(\n Uint8Array.from([0x03]),\n encodeLength(contents),\n contents\n )\n}\n\nexport function encodeOctetString (value: Uint8Array | Uint8ArrayList): Uint8ArrayList {\n return new Uint8ArrayList(\n Uint8Array.from([0x04]),\n encodeLength(value),\n value\n )\n}\n\nexport function encodeSequence (values: Array<Uint8Array | Uint8ArrayList>, tag = 0x30): Uint8ArrayList<ArrayBuffer> {\n const output = new Uint8ArrayList<ArrayBuffer>()\n\n for (const buf of values) {\n output.append(\n withArrayBuffer(buf.subarray())\n )\n }\n\n return new Uint8ArrayList(\n Uint8Array.from([tag]),\n encodeLength(output),\n output\n )\n}\n", "export class InvalidParametersError extends Error {\n static name = 'InvalidParametersError'\n name = 'InvalidParametersError'\n}\n", "import { CID } from 'multiformats'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base64url } from 'multiformats/bases/base64'\nimport { identity } from 'multiformats/hashes/identity'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { withArrayBuffer as uint8ArrayWithArrayBuffer } from 'uint8arrays/with-array-buffer'\nimport { decodeDer, encodeBitString, encodeInteger, encodeOctetString, encodeSequence } from './der.ts'\nimport { InvalidParametersError } from './errors.ts'\nimport { PrivateKeyMessage, PublicKeyMessage } from './pb.ts'\nimport type { Crypto, PrivateKey, PublicKey } from './index.ts'\nimport type { AbortOptions } from 'abort-error'\nimport type { MultihashDigest } from 'multiformats'\n\n// 1.2.840.10045.3.1.7 prime256v1 (ANSI X9.62 named elliptic curve)\nconst OID_256 = Uint8Array.from([0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07])\n// 1.3.132.0.34 secp384r1 (SECG (Certicom) named elliptic curve)\nconst OID_384 = Uint8Array.from([0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22])\n// 1.3.132.0.35 secp521r1 (SECG (Certicom) named elliptic curve)\nconst OID_521 = Uint8Array.from([0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23])\n\nconst P_256_KEY_JWK = {\n ext: true,\n kty: 'EC',\n crv: 'P-256'\n}\n\nconst P_384_KEY_JWK = {\n ext: true,\n kty: 'EC',\n crv: 'P-384'\n}\n\nconst P_521_KEY_JWK = {\n ext: true,\n kty: 'EC',\n crv: 'P-521'\n}\n\nconst P_256_KEY_LENGTH = 32\nconst P_384_KEY_LENGTH = 48\nconst P_521_KEY_LENGTH = 66\n\nclass ECDSAPublicKey implements PublicKey {\n public type = 'ECDSA'\n public code = 3\n public jwk: JsonWebKey\n\n constructor (jwk: JsonWebKey) {\n this.jwk = jwk\n }\n\n toMultihash (): MultihashDigest<0x00> {\n return identity.digest(this.toProtobuf())\n }\n\n toCID (): CID<unknown, 0x72, 0x00, 1> {\n return CID.createV1(0x72, this.toMultihash())\n }\n\n toString (): string {\n return base58btc.encode(this.toMultihash().bytes).substring(1)\n }\n\n toJWK (): JsonWebKey {\n return JSON.parse(JSON.stringify(this.jwk))\n }\n\n toProtobuf (): Uint8Array<ArrayBuffer> {\n return PublicKeyMessage.encode({\n Type: this.code,\n Data: publicKeyToPKIMessage(this.jwk)\n })\n }\n\n async verify (message: Uint8Array, signature: Uint8Array, options?: AbortOptions): Promise<boolean> {\n const key = await crypto.subtle.importKey('jwk', this.jwk, {\n name: 'ECDSA',\n namedCurve: this.jwk.crv ?? 'P-256'\n }, false, ['verify'])\n const isValid = await crypto.subtle.verify({\n name: 'ECDSA',\n hash: {\n name: 'SHA-256'\n }\n }, key, uint8ArrayWithArrayBuffer(signature), uint8ArrayWithArrayBuffer(message))\n options?.signal?.throwIfAborted()\n\n return isValid\n }\n}\n\nclass ECDSAPrivateKey implements PrivateKey {\n public type = 'ECDSA'\n public code = 3\n public jwk: JsonWebKey\n public publicKey: ECDSAPublicKey\n\n constructor (jwk: JsonWebKey, publicKey: ECDSAPublicKey) {\n this.jwk = jwk\n this.publicKey = publicKey\n }\n\n toProtobuf (): Uint8Array<ArrayBuffer> {\n return PrivateKeyMessage.encode({\n Type: this.code,\n Data: privateKeyToPKIMessage(this.jwk)\n })\n }\n\n toJWK (): JsonWebKey {\n return JSON.parse(JSON.stringify(this.jwk))\n }\n\n async sign (message: Uint8Array, options?: AbortOptions): Promise<Uint8Array<ArrayBuffer>> {\n const key = await crypto.subtle.importKey('jwk', this.jwk, {\n name: 'ECDSA',\n namedCurve: this.jwk.crv ?? 'P-256'\n }, true, ['sign'])\n const sig = await crypto.subtle.sign({\n name: 'ECDSA',\n hash: {\n name: 'SHA-256'\n }\n }, key, uint8ArrayWithArrayBuffer(message))\n options?.signal?.throwIfAborted()\n\n return new Uint8Array(sig, 0, sig.byteLength)\n }\n}\n\nexport interface CreateECDSAPrivateKeyOptions extends AbortOptions, Record<string, any> {\n /**\n * @default 'P-256'\n */\n curve?: 'P-256' | 'P-384' | 'P-521'\n}\n\nclass ECDSACrypto implements Crypto {\n type = 'ECDSA'\n code = 3\n\n async generatePrivateKey (options?: CreateECDSAPrivateKeyOptions): Promise<PrivateKey> {\n const curve = options?.curve ?? 'P-256'\n const keyPair = await crypto.subtle.generateKey({\n name: 'ECDSA',\n namedCurve: curve\n }, true, ['sign', 'verify'])\n\n const privateKeyJwk = await crypto.subtle.exportKey('jwk', keyPair.privateKey)\n const publicKeyJwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey)\n\n options?.signal?.throwIfAborted()\n\n return new ECDSAPrivateKey(privateKeyJwk, new ECDSAPublicKey(publicKeyJwk))\n }\n\n async publicKeyFromProtobuf (buf: Uint8Array, options?: AbortOptions): Promise<PublicKey> {\n const message = PublicKeyMessage.decode(buf)\n\n if (message.Data == null) {\n throw new InvalidParametersError('Data field was missing from protobuf')\n }\n\n if (message.Type !== this.code) {\n throw new InvalidParametersError('Incorrect Type field in protobuf')\n }\n\n options?.signal?.throwIfAborted()\n\n const publicKeyJwk = pkiToPublicJWK(message.Data)\n\n return new ECDSAPublicKey(publicKeyJwk)\n }\n\n async privateKeyFromProtobuf (buf: Uint8Array, options?: AbortOptions): Promise<PrivateKey> {\n const message = PrivateKeyMessage.decode(buf)\n\n if (message.Data == null) {\n throw new InvalidParametersError('Data field was missing from protobuf')\n }\n\n if (message.Type !== this.code) {\n throw new InvalidParametersError('Incorrect Type field in protobuf')\n }\n\n const privateKeyJwk = pkiMessageToPrivateJWK(message.Data)\n const publicKeyJwk = privateJWKToPublicJWK(privateKeyJwk)\n\n options?.signal?.throwIfAborted()\n\n return new ECDSAPrivateKey(privateKeyJwk, new ECDSAPublicKey(publicKeyJwk))\n }\n}\n\nexport function ecdsaCrypto (): Crypto {\n return new ECDSACrypto()\n}\n\nfunction privateJWKToPublicJWK (jwk: JsonWebKey): JsonWebKey {\n return {\n crv: jwk.crv,\n ext: true,\n key_ops: ['verify'],\n kty: 'EC',\n x: jwk.x,\n y: jwk.y\n }\n}\n\nfunction pkiMessageToPrivateJWK (buf: Uint8Array): JsonWebKey {\n const message = decodeDer(buf)\n const privateKey = message[1]\n const d = base64url.baseEncode(privateKey)\n const coordinates: Uint8Array = message[2][1][0]\n const offset = 1\n let x: string\n let y: string\n\n if (privateKey.byteLength === P_256_KEY_LENGTH) {\n x = base64url.baseEncode(coordinates.subarray(offset, offset + P_256_KEY_LENGTH))\n y = base64url.baseEncode(coordinates.subarray(offset + P_256_KEY_LENGTH))\n\n return {\n ...P_256_KEY_JWK,\n key_ops: ['sign'],\n d,\n x,\n y\n }\n }\n\n if (privateKey.byteLength === P_384_KEY_LENGTH) {\n x = base64url.baseEncode(coordinates.subarray(offset, offset + P_384_KEY_LENGTH))\n y = base64url.baseEncode(coordinates.subarray(offset + P_384_KEY_LENGTH))\n\n return {\n ...P_384_KEY_JWK,\n key_ops: ['sign'],\n d,\n x,\n y\n }\n }\n\n if (privateKey.byteLength === P_521_KEY_LENGTH) {\n x = base64url.baseEncode(coordinates.subarray(offset, offset + P_521_KEY_LENGTH))\n y = base64url.baseEncode(coordinates.subarray(offset + P_521_KEY_LENGTH))\n\n return {\n ...P_521_KEY_JWK,\n key_ops: ['sign'],\n d,\n x,\n y\n }\n }\n\n throw new InvalidParametersError(`Private key length was wrong length, got ${privateKey.byteLength}, expected 32, 48 or 66`)\n}\n\nfunction pkiToPublicJWK (buf: Uint8Array): JsonWebKey {\n const message = decodeDer(buf)\n\n const coordinates = message[1][1][0]\n const offset = 1\n let x: string\n let y: string\n\n if (coordinates.byteLength === ((P_256_KEY_LENGTH * 2) + 1)) {\n x = base64url.baseEncode(coordinates.subarray(offset, offset + P_256_KEY_LENGTH))\n y = base64url.baseEncode(coordinates.subarray(offset + P_256_KEY_LENGTH))\n\n return {\n ...P_256_KEY_JWK,\n key_ops: ['verify'],\n x,\n y\n }\n }\n\n if (coordinates.byteLength === ((P_384_KEY_LENGTH * 2) + 1)) {\n x = base64url.baseEncode(coordinates.subarray(offset, offset + P_384_KEY_LENGTH))\n y = base64url.baseEncode(coordinates.subarray(offset + P_384_KEY_LENGTH))\n\n return {\n ...P_384_KEY_JWK,\n key_ops: ['verify'],\n x,\n y\n }\n }\n\n if (coordinates.byteLength === ((P_521_KEY_LENGTH * 2) + 1)) {\n x = base64url.baseEncode(coordinates.subarray(offset, offset + P_521_KEY_LENGTH))\n y = base64url.baseEncode(coordinates.subarray(offset + P_521_KEY_LENGTH))\n\n return {\n ...P_521_KEY_JWK,\n key_ops: ['verify'],\n x,\n y\n }\n }\n\n throw new InvalidParametersError(`coordinates were wrong length, got ${coordinates.byteLength}, expected 65, 97 or 133`)\n}\n\nfunction publicKeyToPKIMessage (publicKey: JsonWebKey): Uint8Array {\n return encodeSequence([\n encodeInteger(Uint8Array.from([1])), // header\n encodeSequence([ // PKIProtection\n getOID(publicKey.crv)\n ], 0xA0),\n encodeSequence([ // extraCerts\n encodeBitString(\n new Uint8ArrayList(\n Uint8Array.from([0x04]),\n base64url.baseDecode(publicKey.x ?? ''),\n base64url.baseDecode(publicKey.y ?? '')\n )\n )\n ], 0xA1)\n ]).subarray()\n}\n\nfunction privateKeyToPKIMessage (privateKey: JsonWebKey): Uint8Array<ArrayBuffer> {\n return encodeSequence([\n encodeInteger(Uint8Array.from([1])), // header\n encodeOctetString(base64url.baseDecode(privateKey.d ?? '')), // body\n encodeSequence([ // PKIProtection\n getOID(privateKey.crv)\n ], 0xA0),\n encodeSequence([ // extraCerts\n encodeBitString(\n new Uint8ArrayList(\n Uint8Array.from([0x04]),\n base64url.baseDecode(privateKey.x ?? ''),\n base64url.baseDecode(privateKey.y ?? '')\n )\n )\n ], 0xA1)\n ]).subarray()\n}\n\nfunction getOID (curve?: string): Uint8Array<ArrayBuffer> {\n if (curve === 'P-256') {\n return OID_256\n }\n\n if (curve === 'P-384') {\n return OID_384\n }\n\n if (curve === 'P-521') {\n return OID_521\n }\n\n throw new InvalidParametersError(`Invalid curve ${curve}`)\n}\n", "import { CID } from 'multiformats'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base64url } from 'multiformats/bases/base64'\nimport { identity } from 'multiformats/hashes/identity'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { withArrayBuffer as uint8ArrayWithArrayBuffer } from 'uint8arrays/with-array-buffer'\nimport { InvalidParametersError } from './errors.ts'\nimport { PrivateKeyMessage, PublicKeyMessage } from './pb.ts'\nimport type { Crypto, PrivateKey, PublicKey } from './index.ts'\nimport type { AbortOptions } from 'abort-error'\nimport type { MultihashDigest } from 'multiformats'\n\nconst PRIVATE_KEY_LENGTH = 32\n\nclass Ed25519PublicKey implements PublicKey {\n public type = 'Ed25519'\n public code = 1\n public jwk: JsonWebKey\n\n constructor (jwk: JsonWebKey) {\n this.jwk = jwk\n }\n\n toMultihash (): MultihashDigest<0x00> {\n return identity.digest(this.toProtobuf())\n }\n\n toCID (): CID<unknown, 0x72, 0x00, 1> {\n return CID.createV1(0x72, this.toMultihash())\n }\n\n toString (): string {\n return base58btc.encode(this.toMultihash().bytes).substring(1)\n }\n\n toJWK (): JsonWebKey {\n return JSON.parse(JSON.stringify(this.jwk))\n }\n\n toProtobuf (): Uint8Array<ArrayBuffer> {\n return PublicKeyMessage.encode({\n Type: this.code,\n Data: base64url.baseDecode(this.jwk.x ?? '')\n })\n }\n\n async verify (message: Uint8Array, signature: Uint8Array, options?: AbortOptions): Promise<boolean> {\n const key = await crypto.subtle.importKey('jwk', this.jwk, {\n name: 'Ed25519'\n }, false, ['verify'])\n const isValid = await crypto.subtle.verify({\n name: 'Ed25519'\n }, key, uint8ArrayWithArrayBuffer(signature), uint8ArrayWithArrayBuffer(message))\n options?.signal?.throwIfAborted()\n\n return isValid\n }\n}\n\nclass Ed25519PrivateKey implements PrivateKey {\n public type = 'Ed25519'\n public code = 1\n public jwk: JsonWebKey\n public publicKey: Ed25519PublicKey\n\n constructor (jwk: JsonWebKey, publicKey: Ed25519PublicKey) {\n this.jwk = jwk\n this.publicKey = publicKey\n }\n\n toProtobuf (): Uint8Array<ArrayBuffer> {\n return PrivateKeyMessage.encode({\n Type: this.code,\n Data: uint8ArrayConcat([\n base64url.baseDecode(this.jwk.d ?? ''),\n base64url.baseDecode(this.jwk.x ?? '')\n ], 64)\n })\n }\n\n toJWK (): JsonWebKey {\n return JSON.parse(JSON.stringify(this.jwk))\n }\n\n async sign (message: Uint8Array, options?: AbortOptions): Promise<Uint8Array<ArrayBuffer>> {\n const key = await crypto.subtle.importKey('jwk', this.jwk, {\n name: 'Ed25519'\n }, true, ['sign'])\n const sig = await crypto.subtle.sign({\n name: 'Ed25519'\n }, key, uint8ArrayWithArrayBuffer(message))\n options?.signal?.throwIfAborted()\n\n return new Uint8Array(sig, 0, sig.byteLength)\n }\n}\n\nclass Ed25519Crypto implements Crypto {\n type = 'Ed25519'\n code = 1\n\n async generatePrivateKey (options?: AbortOptions & Record<string, any>): Promise<PrivateKey> {\n const keyPair = await crypto.subtle.generateKey('Ed25519', true, ['sign', 'verify'])\n const privateKeyJwk = await crypto.subtle.exportKey('jwk', keyPair.privateKey)\n const publicKeyJwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey)\n\n options?.signal?.throwIfAborted()\n\n return new Ed25519PrivateKey(privateKeyJwk, new Ed25519PublicKey(publicKeyJwk))\n }\n\n async publicKeyFromProtobuf (buf: Uint8Array, options?: AbortOptions): Promise<PublicKey> {\n const message = PublicKeyMessage.decode(buf)\n\n if (message.Data == null) {\n throw new InvalidParametersError('Data field was missing from protobuf')\n }\n\n if (message.Type !== this.code) {\n throw new InvalidParametersError('Incorrect Type field in protobuf')\n }\n\n options?.signal?.throwIfAborted()\n\n const publicKeyJwk = x5519ToPublicJWK(message.Data)\n\n return new Ed25519PublicKey(publicKeyJwk)\n }\n\n async privateKeyFromProtobuf (buf: Uint8Array, options?: AbortOptions): Promise<PrivateKey> {\n const message = PrivateKeyMessage.decode(buf)\n\n if (message.Data == null) {\n throw new InvalidParametersError('Data field was missing from protobuf')\n }\n\n if (message.Type !== this.code) {\n throw new InvalidParametersError('Incorrect Type field in protobuf')\n }\n\n const privateKeyJwk = await derivePrivateJWK(message.Data, options)\n const publicKeyJwk = privateJWKToPublicJWK(privateKeyJwk)\n\n return new Ed25519PrivateKey(privateKeyJwk, new Ed25519PublicKey(publicKeyJwk))\n }\n}\n\nexport function ed25519Crypto (): Crypto {\n return new Ed25519Crypto()\n}\n\nasync function derivePrivateJWK (raw: Uint8Array, options?: AbortOptions): Promise<JsonWebKey> {\n const privateKey = raw.subarray(0, PRIVATE_KEY_LENGTH)\n const pkcs8 = convertRawX25519KeyToPKCS(privateKey)\n const key = await crypto.subtle.importKey('pkcs8', pkcs8, {\n name: 'Ed25519'\n }, true, ['sign'])\n\n const jwk = await crypto.subtle.exportKey('jwk', key)\n\n options?.signal?.throwIfAborted()\n\n return jwk\n}\n\nconst PKCS8_HEADER = Uint8Array.from([\n 48, 46, 2, 1, 0, 48, 5, 6, 3, 43, 101, 112, 4, 34, 4\n])\n\nfunction convertRawX25519KeyToPKCS (privateKey: Uint8Array): Uint8Array<ArrayBuffer> {\n return uint8ArrayConcat([\n PKCS8_HEADER,\n Uint8Array.from([privateKey.byteLength]),\n privateKey\n ], PKCS8_HEADER.byteLength + 1 + privateKey.byteLength)\n}\n\nfunction privateJWKToPublicJWK (jwk: JsonWebKey): JsonWebKey {\n return {\n alg: 'Ed25519',\n crv: 'Ed25519',\n ext: true,\n key_ops: ['verify'],\n kty: 'OKP',\n x: jwk.x\n }\n}\n\nfunction x5519ToPublicJWK (buf: Uint8Array): JsonWebKey {\n return {\n alg: 'Ed25519',\n crv: 'Ed25519',\n ext: true,\n key_ops: ['verify'],\n kty: 'OKP',\n x: base64url.baseEncode(buf)\n }\n}\n", "import { CID } from 'multiformats'\nimport { base36 } from 'multiformats/bases/base36'\nimport { base64url } from 'multiformats/bases/base64'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { withArrayBuffer as uint8ArrayWithArrayBuffer } from 'uint8arrays/with-array-buffer'\nimport { decodeDer, encodeBitString, encodeInteger, encodeSequence } from './der.ts'\nimport { InvalidParametersError } from './errors.ts'\nimport { PrivateKeyMessage, PublicKeyMessage } from './pb.ts'\nimport type { Crypto, PrivateKey, PublicKey } from './index.ts'\nimport type { AbortOptions } from 'abort-error'\nimport type { MultihashDigest } from 'multiformats'\n\nexport const MAX_RSA_KEY_SIZE = 8192\n\nclass RSAPublicKey implements PublicKey {\n public type = 'RSA'\n public code = 0\n public _raw?: Uint8Array<ArrayBuffer>\n private digest: MultihashDigest<0x012>\n private jwk: JsonWebKey\n\n constructor (jwk: JsonWebKey, digest: MultihashDigest<0x012>) {\n if (rsaKeySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new InvalidParametersError('Key size is too large')\n }\n\n this.jwk = jwk\n this.digest = digest\n }\n\n toMultihash (): MultihashDigest<0x012> {\n return this.digest\n }\n\n toCID (): CID<unknown, 0x72, 0x12, 1> {\n return CID.createV1(0x72, this.toMultihash())\n }\n\n toString (): string {\n return this.toCID().toString(base36)\n }\n\n toProtobuf (): Uint8Array<ArrayBuffer> {\n return publicKeyToProtobuf(this.code, this.jwk)\n }\n\n toJWK (): JsonWebKey {\n return JSON.parse(JSON.stringify(this.jwk))\n }\n\n async verify (message: Uint8Array, signature: Uint8Array, options?: AbortOptions): Promise<boolean> {\n const key = await crypto.subtle.importKey('jwk', this.jwk, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: {\n name: 'SHA-256'\n }\n }, false, ['verify'])\n const result = await crypto.subtle.verify({\n name: 'RSASSA-PKCS1-v1_5'\n }, key, uint8ArrayWithArrayBuffer(signature), uint8ArrayWithArrayBuffer(message))\n options?.signal?.throwIfAborted()\n\n return result\n }\n}\n\nclass RSAPrivateKey implements PrivateKey {\n public type = 'RSA'\n public code = 0\n public publicKey: PublicKey\n private readonly jwk: JsonWebKey\n\n constructor (jwk: JsonWebKey, publicKey: PublicKey) {\n if (rsaKeySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new InvalidParametersError('Key size is too large')\n }\n\n this.jwk = jwk\n this.publicKey = publicKey\n }\n\n toProtobuf (): Uint8Array<ArrayBuffer> {\n return privateKeyToProtobuf(this.code, this.jwk)\n }\n\n toJWK (): JsonWebKey {\n return JSON.parse(JSON.stringify(this.jwk))\n }\n\n async sign (message: Uint8Array, options?: AbortOptions): Promise<Uint8Array<ArrayBuffer>> {\n const key = await crypto.subtle.importKey('jwk', this.jwk, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: {\n name: 'SHA-256'\n }\n }, false, ['sign'])\n const sig = await crypto.subtle.sign({\n name: 'RSASSA-PKCS1-v1_5'\n }, key, uint8ArrayWithArrayBuffer(message))\n\n options?.signal?.throwIfAborted()\n\n return new Uint8Array(sig, 0, sig.byteLength)\n }\n}\n\nexport interface CreateRSAPrivateKeyOptions extends AbortOptions, Record<string, any> {\n /**\n * The key size\n *\n * @default 2048\n */\n bits?: number\n}\n\nclass RSACrypto implements Crypto {\n public type = 'RSA'\n public code = 0\n\n async generatePrivateKey (options?: CreateRSAPrivateKeyOptions): Promise<PrivateKey> {\n const modulusLength = options?.bits ?? 2048\n\n if (modulusLength > MAX_RSA_KEY_SIZE) {\n throw new InvalidParametersError('Key size is too large')\n }\n\n const keypair = await crypto.subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: {\n name: 'SHA-256'\n }\n }, true, ['sign', 'verify'])\n\n const jwkPrivateKey = await crypto.subtle.exportKey('jwk', keypair.privateKey)\n const jwkPublicKey = await crypto.subtle.exportKey('jwk', keypair.publicKey)\n const digest = await publicKeyId(jwkPrivateKey)\n\n options?.signal?.throwIfAborted()\n\n return new RSAPrivateKey(jwkPrivateKey, new RSAPublicKey(jwkPublicKey, digest))\n }\n\n async publicKeyFromProtobuf (buf: Uint8Array, options?: AbortOptions): Promise<PublicKey> {\n const message = PublicKeyMessage.decode(buf)\n\n if (message.Data == null) {\n throw new InvalidParametersError('Data field was missing from protobuf')\n }\n\n if (message.Type !== this.code) {\n throw new InvalidParametersError('Incorrect Type field in protobuf')\n }\n\n const publicKeyJwk = pkixMessageToJwk(message.Data)\n const digest = await publicKeyId(publicKeyJwk)\n\n options?.signal?.throwIfAborted()\n\n return new RSAPublicKey(publicKeyJwk, digest)\n }\n\n async privateKeyFromProtobuf (buf: Uint8Array, options?: AbortOptions): Promise<PrivateKey> {\n const message = PrivateKeyMessage.decode(buf)\n\n if (message.Data == null) {\n throw new InvalidParametersError('Data field was missing from protobuf')\n }\n\n if (message.Type !== this.code) {\n throw new InvalidParametersError('Incorrect Type field in protobuf')\n }\n\n const pkcs1 = decodeDer(message.Data)\n const privateKeyJwk = pkcs1MessageToJwk(pkcs1)\n const publicKeyJwk = privateJWKToPublicJWK(privateKeyJwk)\n const digest = await publicKeyId(publicKeyJwk)\n\n options?.signal?.throwIfAborted()\n\n return new RSAPrivateKey(privateKeyJwk, new RSAPublicKey(publicKeyJwk, digest))\n }\n}\n\nexport function rsaCrypto (): Crypto {\n return new RSACrypto()\n}\n\n/**\n * Convert private key PKCS#1 in ASN1 DER format to JWK\n */\nfunction pkcs1MessageToJwk (message: Uint8Array[]): JsonWebKey {\n return {\n alg: 'RS256',\n kty: 'RSA',\n n: base64url.baseEncode(message[1]),\n e: base64url.baseEncode(message[2]),\n ext: true,\n key_ops: [\n 'sign'\n ],\n d: base64url.baseEncode(message[3]),\n p: base64url.baseEncode(message[4]),\n q: base64url.baseEncode(message[5]),\n dp: base64url.baseEncode(message[6]),\n dq: base64url.baseEncode(message[7]),\n qi: base64url.baseEncode(message[8])\n }\n}\n\n/**\n * Convert a JWK private key into PKCS#1 in ASN1 DER format\n */\nfunction jwkToPkcs1 (jwk: JsonWebKey): Uint8Array<ArrayBuffer> {\n if (jwk.n == null || jwk.e == null || jwk.d == null || jwk.p == null || jwk.q == null || jwk.dp == null || jwk.dq == null || jwk.qi == null) {\n throw new InvalidParametersError('JWK was missing components')\n }\n\n return encodeSequence([\n encodeInteger(Uint8Array.from([0])),\n encodeInteger(base64url.baseDecode(jwk.n)),\n encodeInteger(base64url.baseDecode(jwk.e)),\n encodeInteger(base64url.baseDecode(jwk.d)),\n encodeInteger(base64url.baseDecode(jwk.p)),\n encodeInteger(base64url.baseDecode(jwk.q)),\n encodeInteger(base64url.baseDecode(jwk.dp)),\n encodeInteger(base64url.baseDecode(jwk.dq)),\n encodeInteger(base64url.baseDecode(jwk.qi))\n ]).subarray()\n}\n\nconst RSA_ALGORITHM_IDENTIFIER = Uint8Array.from([\n 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00\n])\n\nfunction jwkToPkix (jwk: JsonWebKey): Uint8Array<ArrayBuffer> {\n if (jwk.n == null || jwk.e == null) {\n throw new InvalidParametersError('JWK public key was missing components')\n }\n\n const subjectPublicKeyInfo = encodeSequence([\n RSA_ALGORITHM_IDENTIFIER,\n encodeBitString(\n encodeSequence([\n encodeInteger(base64url.baseDecode(jwk.n)),\n encodeInteger(base64url.baseDecode(jwk.e))\n ])\n )\n ])\n\n return subjectPublicKeyInfo.subarray()\n}\n\nfunction pkixMessageToJwk (message: Uint8Array): JsonWebKey {\n const cert = decodeDer(message)\n\n if (cert.length < 2 || cert[0]?.[0] !== '1.2.840.113549.1.1.1') {\n throw new Error('PKIX certificate was invalid')\n }\n\n const keys = decodeDer(cert[1])\n\n return {\n kty: 'RSA',\n n: base64url.baseEncode(keys[0]),\n e: base64url.baseEncode(keys[1])\n }\n}\n\nfunction privateJWKToPublicJWK (jwk: JsonWebKey): JsonWebKey {\n return {\n key_ops: ['verify'],\n ext: true,\n alg: 'RS256',\n kty: 'RSA',\n n: jwk.n,\n // cspell:ignore AQAB\n e: 'AQAB'\n }\n}\n\nfunction rsaKeySize (jwk: JsonWebKey): number {\n if (jwk.kty !== 'RSA') {\n throw new InvalidParametersError('Invalid key type')\n } else if (jwk.n == null) {\n throw new InvalidParametersError('Invalid key modulus')\n }\n\n const modulus = base64url.baseDecode(jwk.n)\n return modulus.length * 8\n}\n\nasync function publicKeyId (jwk: JsonWebKey): Promise<MultihashDigest<0x12>> {\n const data = PublicKeyMessage.encode({\n Type: 0,\n Data: jwkToPkix(jwk)\n })\n\n return sha256.digest(data)\n}\n\nfunction publicKeyToProtobuf (code: number, jwk: JsonWebKey): Uint8Array<ArrayBuffer> {\n return PublicKeyMessage.encode({\n Type: code,\n Data: jwkToPkix(jwk)\n })\n}\n\nfunction privateKeyToProtobuf (code: number, jwk: JsonWebKey): Uint8Array<ArrayBuffer> {\n return PrivateKeyMessage.encode({\n Type: code,\n Data: jwkToPkcs1(jwk)\n })\n}\n", "import { rsaCrypto } from '@ipshipyard/crypto'\nimport { decodeDer } from '@ipshipyard/crypto/der'\nimport { PrivateKeyMessage } from '@ipshipyard/crypto/pb'\nimport { base64 } from 'multiformats/bases/base64'\nimport type { PrivateKey } from '@ipshipyard/crypto'\nimport type { AbortOptions } from 'abort-error'\n\n/**\n * Decode legacy RSA key stored as encrypted PEM files\n */\nexport async function privateKeyFromPEM (pem: string, cipher: any, options?: AbortOptions): Promise<PrivateKey> {\n pem = pem.replaceAll('-----BEGIN ENCRYPTED PRIVATE KEY-----', '')\n pem = pem.replaceAll('-----END ENCRYPTED PRIVATE KEY-----', '')\n pem = pem.replaceAll('\\r', '')\n pem = pem.replaceAll('\\n', '')\n\n const decoded = base64.decode(`m${pem}`)\n const der = decodeDer(decoded)\n\n // this looks fragile but DER is a canonical format so we are safe to have\n // deep property chains like this\n const salt = der[0][1][0][1][0]\n const iterations = toNumber(der[0][1][0][1][1])\n const keyLength = toNumber(der[0][1][0][1][2])\n const iv = der[0][1][0][1][4][1]\n const keyData = der[0][1][0][1][4][2]\n\n const plainText = await cipher.decrypt(salt, iv, keyData, {\n iterations,\n keyLength: keyLength * 8,\n hash: 'SHA-512',\n algorithm: 'AES-CBC',\n signal: options?.signal\n })\n\n const keyWrapper = decodeDer(plainText)\n const pkcs1 = keyWrapper[2]\n\n const pb = PrivateKeyMessage.encode({\n Type: 0,\n Data: pkcs1\n })\n\n return rsaCrypto().privateKeyFromProtobuf(pb)\n}\n\nfunction toNumber (buf: Uint8Array): number {\n if (buf.length === 0) {\n return 0\n }\n\n const str = [...buf]\n .map(n => n.toString(16).padStart(2, '0'))\n .join('')\n\n return parseInt(str, 16)\n}\n", "/**\n * @packageDocumentation\n *\n * A WebCrypto-first keychain implementation for use with Helia and libp2p.\n *\n * ## Configuring additional implementations\n *\n * ECDSA, Ed25519 and RSA keys are supported out of the box but other schemes\n * are configurable by passing a `CryptoLoader` that can return `Crypto`\n * instances.\n */\nimport { Keychain as KeychainClass } from './keychain.ts'\nimport type { Crypto, PrivateKey, PublicKey } from '@ipshipyard/crypto'\nimport type { AbortOptions } from 'abort-error'\nimport type { Datastore } from 'interface-datastore'\n\nexport interface CryptoLoader {\n (codeOrName: number | string, options?: AbortOptions): Crypto | Promise<Crypto>\n}\n\nexport interface CipherOptions extends AbortOptions {\n iterations?: number\n hash?: string\n keyLength?: number\n algorithm?: string\n}\n\nexport interface EncryptionResult {\n salt: Uint8Array<ArrayBuffer>\n iv: Uint8Array<ArrayBuffer>\n cipherText: Uint8Array<ArrayBuffer>\n}\n\nexport interface Cipher {\n encrypt(data: Uint8Array, options?: AbortOptions): Promise<EncryptionResult>\n decrypt(salt: Uint8Array, iv: Uint8Array, cipherText: Uint8Array, options?: CipherOptions): Promise<Uint8Array<ArrayBuffer>>\n}\n\nexport interface KeyInfo {\n /**\n * The hash of the key\n */\n id: string\n\n /**\n * The key name\n */\n name: string\n}\n\nexport interface GenerateKeyOptions extends AbortOptions, Record<string, any> {\n /**\n * The type of key to generate\n *\n * @default 'Ed25519'\n */\n type?: 'ECDSA' | 'Ed25519' | 'RSA' | string\n}\n\nexport interface KeychainInit {\n /**\n * The password is used to derive a key which encrypts the keychain at rest\n */\n password?: string\n\n /**\n * Specify a non-default PBK2 function salt\n */\n salt?: string\n\n /**\n * How many iterations to use when deriving a key from the password\n *\n * @default 10_000\n */\n iterations?: number\n\n /**\n * The hash type\n *\n * @default SHA2-512\n */\n hash?: 'SHA-256' | 'SHA-384' | 'SHA-512'\n\n /**\n * The 'self' key is the private key of the node from which the peer id is\n * derived.\n *\n * It cannot be renamed or removed.\n *\n * By default it is stored under the 'self' key, to use a different name, pass\n * this option.\n *\n * @default 'self'\n */\n selfKey?: string\n}\n\nexport interface KeychainComponents {\n datastore: Datastore\n getCrypto: CryptoLoader\n}\n\nexport interface Keychain {\n /**\n * Create a key of the passed type and store it under the specified name. A\n * cryptography implementation must be configured for the key type (defaults\n * to Ed25519).\n */\n generateKey (name: string, options?: AbortOptions & Record<string, any>): Promise<PrivateKey>\n\n /**\n * Import a new private key.\n *\n * The `type` parameter must match a supported cryptography implementation.\n *\n * The default supported key types are `Ed25519` and `RSA`, others may be\n * added through configuration.\n *\n * @example\n *\n * ```TypeScript\n * const key = await crypto.subtle.generateKey('Ed25519', true, ['sign', 'verify'])\n * const raw = await crypto.subtle.exportKey('raw', key)\n * await helia.keychain.importKey('my-key', 'Ed25519', raw)\n * ```\n */\n importKey(name: string, key: PrivateKey, options?: AbortOptions): Promise<PrivateKey>\n\n /**\n * Export an existing private key.\n *\n * @example\n *\n * ```TypeScript\n * const raw = await helia.exportKey('my-key')\n * const key = await crypto.subtle.importKey('raw', raw, {\n * name: 'Ed25519'\n * }, true, ['sign', 'verify'])\n * ```\n */\n exportKey(name: string, options?: AbortOptions): Promise<PrivateKey>\n\n /**\n * Removes a key from the keychain.\n *\n * @example\n *\n * ```TypeScript\n * await helia.keychain.removeKey('keyTest')\n * ```\n */\n removeKey(name: string, options?: AbortOptions): Promise<void>\n\n /**\n * Rename a key in the keychain. This is done in a batch commit with rollback\n * so errors thrown during the operation will not cause key loss.\n *\n * @example\n *\n * ```TypeScript\n * await helia.keychain.renameKey('oldName', 'newName')\n * ```\n */\n renameKey(oldName: string, newName: string, options?: AbortOptions): Promise<void>\n\n /**\n * List all the keys.\n *\n * @example\n *\n * ```TypeScript\n * for await (const name of helia.keychain.listKeys()) {\n * // ...\n * }\n * ```\n */\n listKeys(options?: AbortOptions): AsyncGenerator<KeyInfo>\n\n /**\n * Re-encrypt all keys in the keychain using a crypto graphic key derived\n * from the password\n *\n * @example\n *\n * ```TypeScript\n * await helia.keychain.rotateKeychainPass('newPassword')\n * ```\n */\n rotateKeychainPass(password: string, options?: AbortOptions): Promise<void>\n\n /**\n * Attempts to load a public key from a serialized protobuf message conforming\n * to the `PublicKey` message.\n */\n loadPublicKeyFromProtobuf (buf: Uint8Array, options?: AbortOptions): Promise<PublicKey>\n}\n\nexport function keychain (init?: KeychainInit): (components: KeychainComponents) => Keychain {\n return (components) => new KeychainClass(components, init)\n}\n", "/**\n * When this error is thrown it means an operation was aborted,\n * usually in response to the `abort` event being emitted by an\n * AbortSignal.\n */\nexport class AbortError extends Error {\n static name = 'AbortError'\n\n constructor (message: string = 'The operation was aborted') {\n super(message)\n this.name = 'AbortError'\n }\n}\n\n/**\n * Thrown when a remote Peer ID does not match the expected one\n */\nexport class UnexpectedPeerError extends Error {\n static name = 'UnexpectedPeerError'\n\n constructor (message = 'Unexpected Peer') {\n super(message)\n this.name = 'UnexpectedPeerError'\n }\n}\n\n/**\n * Thrown when a crypto exchange fails\n */\nexport class InvalidCryptoExchangeError extends Error {\n static name = 'InvalidCryptoExchangeError'\n\n constructor (message = 'Invalid crypto exchange') {\n super(message)\n this.name = 'InvalidCryptoExchangeError'\n }\n}\n\n/**\n * Thrown when invalid parameters are passed to a function or method call\n */\nexport class InvalidParametersError extends Error {\n static name = 'InvalidParametersError'\n\n constructor (message = 'Invalid parameters') {\n super(message)\n this.name = 'InvalidParametersError'\n }\n}\n\n/**\n * Thrown when a public key is invalid\n */\nexport class InvalidPublicKeyError extends Error {\n static name = 'InvalidPublicKeyError'\n\n constructor (message = 'Invalid public key') {\n super(message)\n this.name = 'InvalidPublicKeyError'\n }\n}\n\n/**\n * Thrown when a private key is invalid\n */\nexport class InvalidPrivateKeyError extends Error {\n static name = 'InvalidPrivateKeyError'\n\n constructor (message = 'Invalid private key') {\n super(message)\n this.name = 'InvalidPrivateKeyError'\n }\n}\n\n/**\n * Thrown when a operation is unsupported\n */\nexport class UnsupportedOperationError extends Error {\n static name = 'UnsupportedOperationError'\n\n constructor (message = 'Unsupported operation') {\n super(message)\n this.name = 'UnsupportedOperationError'\n }\n}\n\n/**\n * Thrown when a connection is closing\n */\nexport class ConnectionClosingError extends Error {\n static name = 'ConnectionClosingError'\n\n constructor (message = 'The connection is closing') {\n super(message)\n this.name = 'ConnectionClosingError'\n }\n}\n\n/**\n * Thrown when a connection is closed\n */\nexport class ConnectionClosedError extends Error {\n static name = 'ConnectionClosedError'\n\n constructor (message = 'The connection is closed') {\n super(message)\n this.name = 'ConnectionClosedError'\n }\n}\n\n/**\n * Thrown when a connection fails\n */\nexport class ConnectionFailedError extends Error {\n static name = 'ConnectionFailedError'\n\n constructor (message = 'Connection failed') {\n super(message)\n this.name = 'ConnectionFailedError'\n }\n}\n\n/**\n * Thrown when the muxer is closed and an attempt to open a stream occurs\n */\nexport class MuxerClosedError extends Error {\n static name = 'MuxerClosedError'\n\n constructor (message = 'The muxer is closed') {\n super(message)\n this.name = 'MuxerClosedError'\n }\n}\n\n/**\n * Thrown when a protocol stream is reset by the remote muxer\n */\nexport class StreamResetError extends Error {\n static name = 'StreamResetError'\n\n constructor (message = 'The stream has been reset') {\n super(message)\n this.name = 'StreamResetError'\n }\n}\n\n/**\n * Thrown when a protocol stream is aborted locally\n */\nexport class StreamAbortedError extends Error {\n static name = 'StreamAbortedError'\n\n constructor (message = 'The stream has been aborted') {\n super(message)\n this.name = 'StreamAbortedError'\n }\n}\n\n/**\n * Thrown when a stream is in an invalid state\n */\nexport class StreamStateError extends Error {\n static name = 'StreamStateError'\n\n constructor (message = 'The stream is in an invalid state') {\n super(message)\n this.name = 'StreamStateError'\n }\n}\n\n/**\n * Thrown when a stream buffer is full\n */\nexport class StreamBufferError extends Error {\n static name = 'StreamBufferError'\n\n constructor (message = 'The stream buffer was full') {\n super(message)\n this.name = 'StreamBufferError'\n }\n}\n\n/**\n * Thrown when a value could not be found\n */\nexport class NotFoundError extends Error {\n static name = 'NotFoundError'\n\n constructor (message = 'Not found') {\n super(message)\n this.name = 'NotFoundError'\n }\n}\n\n/**\n * Thrown when an invalid peer ID is encountered\n */\nexport class InvalidPeerIdError extends Error {\n static name = 'InvalidPeerIdError'\n\n constructor (message = 'Invalid PeerID') {\n super(message)\n this.name = 'InvalidPeerIdError'\n }\n}\n\n/**\n * Thrown when an invalid multiaddr is encountered\n */\nexport class InvalidMultiaddrError extends Error {\n static name = 'InvalidMultiaddrError'\n\n constructor (message = 'Invalid multiaddr') {\n super(message)\n this.name = 'InvalidMultiaddrError'\n }\n}\n\n/**\n * Thrown when an invalid CID is encountered\n */\nexport class InvalidCIDError extends Error {\n static name = 'InvalidCIDError'\n\n constructor (message = 'Invalid CID') {\n super(message)\n this.name = 'InvalidCIDError'\n }\n}\n\n/**\n * Thrown when an invalid multihash is encountered\n */\nexport class InvalidMultihashError extends Error {\n static name = 'InvalidMultihashError'\n\n constructor (message = 'Invalid Multihash') {\n super(message)\n this.name = 'InvalidMultihashError'\n }\n}\n\n/**\n * Thrown when a protocol is not supported\n */\nexport class UnsupportedProtocolError extends Error {\n static name = 'UnsupportedProtocolError'\n\n constructor (message = 'Unsupported protocol error') {\n super(message)\n this.name = 'UnsupportedProtocolError'\n }\n}\n\n/**\n * An invalid or malformed message was encountered during a protocol exchange\n */\nexport class InvalidMessageError extends Error {\n static name = 'InvalidMessageError'\n\n constructor (message = 'Invalid message') {\n super(message)\n this.name = 'InvalidMessageError'\n }\n}\n\n/**\n * Thrown when a remote peer sends a structurally valid message that does not\n * comply with the protocol\n */\nexport class ProtocolError extends Error {\n static name = 'ProtocolError'\n\n constructor (message = 'Protocol error') {\n super(message)\n this.name = 'ProtocolError'\n }\n}\n\n/**\n * Throw when an operation times out\n */\nexport class TimeoutError extends Error {\n static name = 'TimeoutError'\n\n constructor (message = 'Timed out') {\n super(message)\n this.name = 'TimeoutError'\n }\n}\n\n/**\n * Thrown when a startable component is interacted with but it has not been\n * started yet\n */\nexport class NotStartedError extends Error {\n static name = 'NotStartedError'\n\n constructor (message = 'Not started') {\n super(message)\n this.name = 'NotStartedError'\n }\n}\n\n/**\n * Thrown when a component is started that has already been started\n */\nexport class AlreadyStartedError extends Error {\n static name = 'AlreadyStartedError'\n\n constructor (message = 'Already started') {\n super(message)\n this.name = 'AlreadyStartedError'\n }\n}\n\n/**\n * Thrown when dialing an address failed\n */\nexport class DialError extends Error {\n static name = 'DialError'\n\n constructor (message = 'Dial error') {\n super(message)\n this.name = 'DialError'\n }\n}\n\n/**\n * Thrown when listening on an address failed\n */\nexport class ListenError extends Error {\n static name = 'ListenError'\n\n constructor (message = 'Listen error') {\n super(message)\n this.name = 'ListenError'\n }\n}\n\n/**\n * This error is thrown when a limited connection is encountered, i.e. if the\n * user tried to open a stream on a connection for a protocol that is not\n * configured to run over limited connections.\n */\nexport class LimitedConnectionError extends Error {\n static name = 'LimitedConnectionError'\n\n constructor (message = 'Limited connection') {\n super(message)\n this.name = 'LimitedConnectionError'\n }\n}\n\n/**\n * This error is thrown where there are too many inbound protocols streams open\n */\nexport class TooManyInboundProtocolStreamsError extends Error {\n static name = 'TooManyInboundProtocolStreamsError'\n\n constructor (message = 'Too many inbound protocol streams') {\n super(message)\n this.name = 'TooManyInboundProtocolStreamsError'\n }\n}\n\n/**\n * This error is thrown where there are too many outbound protocols streams open\n */\nexport class TooManyOutboundProtocolStreamsError extends Error {\n static name = 'TooManyOutboundProtocolStreamsError'\n\n constructor (message = 'Too many outbound protocol streams') {\n super(message)\n this.name = 'TooManyOutboundProtocolStreamsError'\n }\n}\n\n/**\n * Thrown when an attempt to operate on an unsupported key was made\n */\nexport class UnsupportedKeyTypeError extends Error {\n static name = 'UnsupportedKeyTypeError'\n\n constructor (message = 'Unsupported key type') {\n super(message)\n this.name = 'UnsupportedKeyTypeError'\n }\n}\n\n/**\n * Thrown when an operation has not been implemented\n */\nexport class NotImplementedError extends Error {\n static name = 'NotImplementedError'\n\n constructor (message = 'Not implemented') {\n super(message)\n this.name = 'NotImplementedError'\n }\n}\n", "/**\n * Implemented by components that have a life cycle\n */\nexport interface Startable {\n /**\n * If implemented, this method will be invoked before the start method.\n *\n * It should not assume any other components have been started.\n */\n beforeStart?(): void | Promise<void>\n\n /**\n * This method will be invoked to start the component.\n *\n * It should not assume that any other components have been started.\n */\n start(): void | Promise<void>\n\n /**\n * If implemented, this method will be invoked after the start method.\n *\n * All other components will have had their start method invoked before this method is called.\n */\n afterStart?(): void | Promise<void>\n\n /**\n * If implemented, this method will be invoked before the stop method.\n *\n * Any other components will still be running when this method is called.\n */\n beforeStop?(): void | Promise<void>\n\n /**\n * This method will be invoked to stop the component.\n *\n * It should not assume any other components are running when it is called.\n */\n stop(): void | Promise<void>\n\n /**\n * If implemented, this method will be invoked after the stop method.\n *\n * All other components will have had their stop method invoked before this method is called.\n */\n afterStop?(): void | Promise<void>\n}\n\n/**\n * Returns `true` if the object has type overlap with `Startable`\n */\nexport function isStartable (obj?: any): obj is Startable {\n return obj != null && typeof obj.start === 'function' && typeof obj.stop === 'function'\n}\n\n/**\n * A function that can be used to start and objects passed to it. This checks\n * that an object is startable before invoking its lifecycle methods so it is\n * safe to pass non-`Startable`s in.\n *\n * @example\n *\n * ```TypeScript\n * import { start } from '@libp2p/interface'\n * import type { Startable } from '@libp2p/interface'\n *\n * const startable: Startable = {\n * start: () => {},\n * stop: () => {}\n * }\n *\n * const notStartable = 5\n *\n * await start(\n * startable,\n * notStartable\n * )\n * ```\n */\nexport async function start (...objs: any[]): Promise<void> {\n const startables: Startable[] = []\n\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj)\n }\n }\n\n await Promise.all(\n startables.map(async s => {\n if (s.beforeStart != null) {\n await s.beforeStart()\n }\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n await s.start()\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n if (s.afterStart != null) {\n await s.afterStart()\n }\n })\n )\n}\n\n/**\n * A function that can be used to stop and objects passed to it. This checks\n * that an object is startable before invoking its lifecycle methods so it is\n * safe to pass non-`Startable`s in.\n *\n * @example\n *\n * ```TypeScript\n * import { stop } from '@libp2p/interface'\n * import type { Startable } from '@libp2p/interface'\n *\n * const startable: Startable = {\n * start: () => {},\n * stop: () => {}\n * }\n *\n * const notStartable = 5\n *\n * await stop(\n * startable,\n * notStartable\n * )\n * ```\n */\nexport async function stop (...objs: any[]): Promise<void> {\n const startables: Startable[] = []\n\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj)\n }\n }\n\n await Promise.all(\n startables.map(async s => {\n if (s.beforeStop != null) {\n await s.beforeStop()\n }\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n await s.stop()\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n if (s.afterStop != null) {\n await s.afterStop()\n }\n })\n )\n}\n", "/**\n * @packageDocumentation\n *\n * Adds types to the EventTarget class.\n *\n * Hopefully this won't be necessary\n * forever:\n *\n * - https://github.com/microsoft/TypeScript/issues/28357\n * - https://github.com/microsoft/TypeScript/issues/43477\n * - https://github.com/microsoft/TypeScript/issues/299\n * - https://www.npmjs.com/package/typed-events\n * - https://www.npmjs.com/package/typed-event-emitter\n * - https://www.npmjs.com/package/typed-event-target\n * - etc\n *\n * In addition to types, a `safeDispatchEvent` method is available which\n * prevents dispatching events that aren't in the event map, and a\n * `listenerCount` method which reports the number of listeners that are\n * currently registered for a given event.\n *\n * @example\n *\n * ```ts\n * import { TypedEventEmitter } from 'main-event'\n * import type { TypedEventTarget } from 'main-event'\n *\n * interface EventTypes {\n * 'test': CustomEvent<string>\n * }\n *\n * const target = new TypedEventEmitter<EventTypes>()\n *\n * // it's a regular EventTarget\n * console.info(target instanceof EventTarget) // true\n *\n * // register listeners normally\n * target.addEventListener('test', (evt) => {\n * // evt is CustomEvent<string>\n * })\n *\n * // @ts-expect-error 'derp' is not in the event map\n * target.addEventListener('derp', () => {})\n *\n * // use normal dispatchEvent method\n * target.dispatchEvent(new CustomEvent('test', {\n * detail: 'hello'\n * }))\n *\n * // use type safe dispatch method\n * target.safeDispatchEvent('test', {\n * detail: 'world'\n * })\n *\n * // report listener count\n * console.info(target.listenerCount('test')) // 0\n *\n * // event emitters can be used purely as interfaces too\n * function acceptTarget (target: TypedEventTarget<EventTypes>) {\n * // ...\n * }\n * ```\n */\n\nimport { setMaxListeners } from './events.ts'\n\nexport interface EventCallback<EventType> { (evt: EventType): void }\nexport interface EventObject<EventType> { handleEvent: EventCallback<EventType> }\nexport type EventHandler<EventType> = EventCallback<EventType> | EventObject<EventType>\n\ninterface Listener {\n once: boolean\n callback: any\n}\n\n/**\n *\n */\nexport interface TypedEventTarget <EventMap extends Record<string, any>> extends EventTarget {\n addEventListener<K extends keyof EventMap>(type: K, listener: EventHandler<EventMap[K]> | null, options?: boolean | AddEventListenerOptions): void\n\n listenerCount (type: string): number\n\n removeEventListener<K extends keyof EventMap>(type: K, listener?: EventHandler<EventMap[K]> | null, options?: boolean | EventListenerOptions): void\n\n removeEventListener (type: string, listener?: EventHandler<Event>, options?: boolean | EventListenerOptions): void\n\n safeDispatchEvent<Detail>(type: keyof EventMap, detail?: CustomEventInit<Detail>): boolean\n}\n\nfunction isEventObject <EventType> (obj?: any): obj is EventObject<EventType> {\n return typeof obj?.handleEvent === 'function'\n}\n\nfunction isOnce (options?: boolean | AddEventListenerOptions): boolean {\n return (options !== true && options !== false && options?.once) ?? false\n}\n\n/**\n * An implementation of a typed event target\n */\nexport class TypedEventEmitter<EventMap extends Record<string, any>> extends EventTarget implements TypedEventTarget<EventMap> {\n readonly #listeners = new Map<any, Listener[]>()\n\n constructor () {\n super()\n\n // silence MaxListenersExceededWarning warning on Node.js, this is a red\n // herring almost all of the time\n setMaxListeners(Infinity, this)\n }\n\n listenerCount (type: string): number {\n const listeners = this.#listeners.get(type)\n\n if (listeners == null) {\n return 0\n }\n\n return listeners.length\n }\n\n addEventListener<K extends keyof EventMap>(type: K, listener: EventHandler<EventMap[K]> | null, options?: boolean | AddEventListenerOptions): void\n addEventListener (type: string, listener: EventHandler<Event>, options?: boolean | AddEventListenerOptions): void {\n const once = isOnce(options)\n\n super.addEventListener(type, (evt) => {\n if (once) {\n let list = this.#listeners.get(evt.type)\n\n if (list != null) {\n list = list.filter(({ callback }) => callback !== listener)\n this.#listeners.set(evt.type, list)\n }\n }\n\n if (isEventObject<Event>(listener)) {\n listener.handleEvent(evt)\n } else {\n listener(evt)\n }\n }, options)\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n list = []\n this.#listeners.set(type, list)\n }\n\n list.push({\n callback: listener,\n once\n })\n }\n\n removeEventListener<K extends keyof EventMap>(type: K, listener?: EventHandler<EventMap[K]> | null, options?: boolean | EventListenerOptions): void\n removeEventListener (type: string, listener?: EventHandler<Event>, options?: boolean | EventListenerOptions): void {\n super.removeEventListener(type.toString(), listener ?? null, options)\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n return\n }\n\n list = list.filter(({ callback }) => callback !== listener)\n this.#listeners.set(type, list)\n }\n\n safeDispatchEvent<Detail>(type: keyof EventMap, detail: CustomEventInit<Detail> = {}): boolean {\n return this.dispatchEvent(new CustomEvent<Detail>(type as string, detail))\n }\n}\n\nexport { setMaxListeners }\n", "/**\n * Progress events are emitted during long running operations\n */\nexport interface ProgressEvent<T extends string = any, D = unknown> {\n /**\n * The event type\n */\n type: T\n\n /**\n * Context-specific event information\n */\n detail: D\n}\n\n/**\n * A callback function that receives progress events\n */\nexport interface ProgressEventListener<E extends ProgressEvent = any> {\n (evt: E): void\n}\n\n/**\n * An implementation of the ProgressEvent interface, this is essentially\n * a typed `CustomEvent` with a `type` property that lets us disambiguate\n * events passed to `progress` callbacks.\n */\nexport class CustomProgressEvent<D = unknown, T extends string = any> extends Event implements ProgressEvent<T, D> {\n public type: T\n public detail: D\n\n constructor (type: T, detail?: D) {\n super(type)\n\n this.type = type\n // @ts-expect-error detail may be undefined\n this.detail = detail\n }\n}\n\n/**\n * Define an `onProgress` callback that can be invoked with `ProgressEvent`s\n *\n * @example\n *\n * ```typescript\n * type MyOperationProgressEvents =\n * ProgressEvent<'operation:start'> |\n * ProgressEvent<'operation:success', Result> |\n * ProgressEvent<'operation:error', Error>\n *\n * export interface MyOperationOptions extends ProgressOptions<MyOperationProgressEvents> {\n * // define options here\n * }\n * ```\n */\nexport interface ProgressOptions<Event extends ProgressEvent = any> {\n onProgress?: ProgressEventListener<Event>\n}\n", "export class DNSQueryFailedError extends AggregateError {\n static name = 'DNSQueryFailedError'\n name = 'DNSQueryFailedError'\n}\n", "import EventEmitter from './index.js'\n\nexport { EventEmitter }\nexport default EventEmitter\n", "export class TimeoutError extends Error {\n\tname = 'TimeoutError';\n\n\tconstructor(message, options) {\n\t\tsuper(message, options);\n\t\tError.captureStackTrace?.(this, TimeoutError);\n\t}\n}\n\nconst getAbortedReason = signal => signal.reason ?? new DOMException('This operation was aborted.', 'AbortError');\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\tsignal,\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 (signal?.aborted) {\n\t\t\treject(getAbortedReason(signal));\n\t\t\treturn;\n\t\t}\n\n\t\tif (signal) {\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\t// Use .then() instead of async IIFE to preserve stack traces\n\t\t// eslint-disable-next-line promise/prefer-await-to-then, promise/prefer-catch\n\t\tpromise.then(resolve, reject);\n\n\t\tif (milliseconds === Number.POSITIVE_INFINITY) {\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\t// `.call(undefined, ...)` is needed for custom timers to avoid context issues\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\t});\n\n\t// eslint-disable-next-line promise/prefer-await-to-then\n\tconst cancelablePromise = wrappedPromise.finally(() => {\n\t\tcancelablePromise.clear();\n\t\tif (abortHandler && signal) {\n\t\t\tsignal.removeEventListener('abort', abortHandler);\n\t\t}\n\t});\n\n\tcancelablePromise.clear = () => {\n\t\t// `.call(undefined, ...)` is needed for custom timers to avoid context issues\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';\nconst compactionThreshold = 100;\nexport default class PriorityQueue {\n #queue = [];\n // The queue is stored as a sorted array, but dequeued items are left before `#head` until compaction. Only items from `#head` onward are live, which keeps repeated dequeues amortized O(1).\n #head = 0;\n enqueue(run, options) {\n const { priority = 0, id, } = options ?? {};\n const { size } = this;\n const element = {\n priority,\n id,\n run,\n };\n if (size === 0) {\n // When the queue is logically empty, discard any consumed prefix before accepting new work.\n this.#queue.length = 0;\n this.#head = 0;\n this.#queue.push(element);\n return;\n }\n if (this.#queue.at(-1).priority >= priority) {\n // Same-priority and lower-priority items belong after the current tail. Appending preserves FIFO order for equal priorities.\n this.#queue.push(element);\n return;\n }\n // Binary insertion must run on the live sorted range only.\n this.#compact();\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 // A dequeued item with the same id is no longer part of the queue.\n const index = this.#queue.findIndex((element, index) => index >= this.#head && 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 remove(idOrRun) {\n const index = this.#queue.findIndex((element, index) => {\n // The consumed prefix may still contain references that should not be removable.\n if (index < this.#head) {\n return false;\n }\n if (typeof idOrRun === 'string') {\n return element.id === idOrRun;\n }\n return element.run === idOrRun;\n });\n if (index !== -1) {\n this.#queue.splice(index, 1);\n }\n }\n dequeue() {\n if (this.#head === this.#queue.length) {\n return undefined;\n }\n const item = this.#queue[this.#head];\n this.#head++;\n if (this.#head === this.#queue.length) {\n // Fully drained queues are reset immediately so the next enqueue starts from a clean array.\n this.#queue.length = 0;\n this.#head = 0;\n }\n else if (this.#head > compactionThreshold && this.#head > this.#queue.length / 2) {\n // Keep repeated dequeues cheap, but stop the consumed prefix from growing without bound.\n this.#compact();\n }\n return item?.run;\n }\n filter(options) {\n const result = [];\n for (let index = this.#head; index < this.#queue.length; index++) {\n const element = this.#queue[index];\n if (element.priority === options.priority) {\n result.push(element.run);\n }\n }\n return result;\n }\n get size() {\n return this.#queue.length - this.#head;\n }\n #compact() {\n // Compaction restores the invariant that the whole array is the live sorted range.\n if (this.#head === 0) {\n return;\n }\n this.#queue.splice(0, this.#head);\n this.#head = 0;\n }\n}\n", "import { EventEmitter } from 'eventemitter3';\nimport pTimeout from 'p-timeout';\nimport PriorityQueue from './priority-queue.js';\n/**\nPromise queue with concurrency control.\n*/\nexport default class PQueue extends EventEmitter {\n #carryoverIntervalCount;\n #isIntervalIgnored;\n #intervalCount = 0;\n #intervalCap;\n #rateLimitedInInterval = false;\n #rateLimitFlushScheduled = false;\n #interval;\n #intervalEnd = 0;\n #lastExecutionTime = 0;\n #intervalId;\n #timeoutId;\n #strict;\n // Circular buffer implementation for better performance\n #strictTicks = [];\n #strictTicksStartIndex = 0;\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 // Use to assign a unique identifier to a promise function, if not explicitly specified\n #idAssigner = 1n;\n // Track currently running tasks for debugging\n #runningTasks = new Map();\n #queueAbortListenerCleanupFunctions = new Set();\n /**\n Get or set the default timeout for all tasks. Can be changed at runtime.\n\n Operations will throw a `TimeoutError` if they don't complete within the specified time.\n\n The timeout begins when the operation is dequeued and starts execution, not while it's waiting in the queue.\n\n @example\n ```\n const queue = new PQueue({timeout: 5000});\n\n // Change timeout for all future tasks\n queue.timeout = 10000;\n ```\n */\n timeout;\n constructor(options) {\n super();\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n options = {\n carryoverIntervalCount: false,\n intervalCap: Number.POSITIVE_INFINITY,\n interval: 0,\n concurrency: Number.POSITIVE_INFINITY,\n autoStart: true,\n queueClass: PriorityQueue,\n strict: false,\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 if (options.strict && options.interval === 0) {\n throw new TypeError('The `strict` option requires a non-zero `interval`');\n }\n if (options.strict && options.intervalCap === Number.POSITIVE_INFINITY) {\n throw new TypeError('The `strict` option requires a finite `intervalCap`');\n }\n // TODO: Remove this fallback in the next major version\n // eslint-disable-next-line @typescript-eslint/no-deprecated\n this.#carryoverIntervalCount = options.carryoverIntervalCount ?? options.carryoverConcurrencyCount ?? false;\n this.#isIntervalIgnored = options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0;\n this.#intervalCap = options.intervalCap;\n this.#interval = options.interval;\n this.#strict = options.strict;\n this.#queue = new options.queueClass();\n this.#queueClass = options.queueClass;\n this.concurrency = options.concurrency;\n if (options.timeout !== undefined && !(Number.isFinite(options.timeout) && options.timeout > 0)) {\n throw new TypeError(`Expected \\`timeout\\` to be a positive finite number, got \\`${options.timeout}\\` (${typeof options.timeout})`);\n }\n this.timeout = options.timeout;\n this.#isPaused = options.autoStart === false;\n this.#setupRateLimitTracking();\n }\n #cleanupStrictTicks(now) {\n // Remove ticks outside the current interval window using circular buffer approach\n while (this.#strictTicksStartIndex < this.#strictTicks.length) {\n const oldestTick = this.#strictTicks[this.#strictTicksStartIndex];\n if (oldestTick !== undefined && now - oldestTick >= this.#interval) {\n this.#strictTicksStartIndex++;\n }\n else {\n break;\n }\n }\n // Compact the array when it becomes inefficient or fully consumed\n // Compact when: (start index is large AND more than half wasted) OR all ticks expired\n const shouldCompact = (this.#strictTicksStartIndex > 100 && this.#strictTicksStartIndex > this.#strictTicks.length / 2)\n || this.#strictTicksStartIndex === this.#strictTicks.length;\n if (shouldCompact) {\n this.#strictTicks = this.#strictTicks.slice(this.#strictTicksStartIndex);\n this.#strictTicksStartIndex = 0;\n }\n }\n // Helper methods for interval consumption\n #consumeIntervalSlot(now) {\n if (this.#strict) {\n this.#strictTicks.push(now);\n }\n else {\n this.#intervalCount++;\n }\n }\n #rollbackIntervalSlot() {\n if (this.#strict) {\n // Pop from the end of the actual data (not from start index)\n if (this.#strictTicks.length > this.#strictTicksStartIndex) {\n this.#strictTicks.pop();\n }\n }\n else if (this.#intervalCount > 0) {\n this.#intervalCount--;\n }\n }\n #getActiveTicksCount() {\n return this.#strictTicks.length - this.#strictTicksStartIndex;\n }\n get #doesIntervalAllowAnother() {\n if (this.#isIntervalIgnored) {\n return true;\n }\n if (this.#strict) {\n // Cleanup already done by #isIntervalPausedAt before this is called\n return this.#getActiveTicksCount() < this.#intervalCap;\n }\n return this.#intervalCount < this.#intervalCap;\n }\n get #doesConcurrentAllowAnother() {\n return this.#pending < this.#concurrency;\n }\n #next() {\n this.#pending--;\n if (this.#pending === 0) {\n this.emit('pendingZero');\n }\n this.#tryToStartAnother();\n this.emit('next');\n }\n #onResumeInterval() {\n // Clear timeout ID before processing to prevent race condition\n // Must clear before #onInterval to allow new timeouts to be scheduled\n this.#timeoutId = undefined;\n this.#onInterval();\n this.#initializeIntervalIfNeeded();\n }\n #isIntervalPausedAt(now) {\n // Strict mode: check if we need to wait for oldest tick to age out\n if (this.#strict) {\n this.#cleanupStrictTicks(now);\n // If at capacity, need to wait for oldest tick to age out\n const activeTicksCount = this.#getActiveTicksCount();\n if (activeTicksCount >= this.#intervalCap) {\n const oldestTick = this.#strictTicks[this.#strictTicksStartIndex];\n // After cleanup, remaining ticks are within interval, so delay is always > 0\n const delay = this.#interval - (now - oldestTick);\n this.#createIntervalTimeout(delay);\n return true;\n }\n return false;\n }\n // Fixed window mode (original logic)\n if (this.#intervalId === undefined) {\n const delay = this.#intervalEnd - now;\n if (delay < 0) {\n // If the interval has expired while idle, check if we should enforce the interval\n // from the last task execution. This ensures proper spacing between tasks even\n // when the queue becomes empty and then new tasks are added.\n if (this.#lastExecutionTime > 0) {\n const timeSinceLastExecution = now - this.#lastExecutionTime;\n if (timeSinceLastExecution < this.#interval) {\n // Not enough time has passed since the last task execution\n this.#createIntervalTimeout(this.#interval - timeSinceLastExecution);\n return true;\n }\n }\n // Enough time has passed or no previous execution, allow execution\n this.#intervalCount = (this.#carryoverIntervalCount) ? this.#pending : 0;\n }\n else {\n // Act as the interval is pending\n this.#createIntervalTimeout(delay);\n return true;\n }\n }\n return false;\n }\n #createIntervalTimeout(delay) {\n if (this.#timeoutId !== undefined) {\n return;\n }\n this.#timeoutId = setTimeout(() => {\n this.#onResumeInterval();\n }, delay);\n }\n #clearIntervalTimer() {\n if (this.#intervalId) {\n clearInterval(this.#intervalId);\n this.#intervalId = undefined;\n }\n }\n #clearTimeoutTimer() {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId);\n this.#timeoutId = undefined;\n }\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 this.#clearIntervalTimer();\n this.emit('empty');\n if (this.#pending === 0) {\n // Clear timeout as well when completely idle\n this.#clearTimeoutTimer();\n // Compact strict ticks when idle to free memory\n if (this.#strict && this.#strictTicksStartIndex > 0) {\n const now = Date.now();\n this.#cleanupStrictTicks(now);\n }\n this.emit('idle');\n }\n return false;\n }\n let taskStarted = false;\n if (!this.#isPaused) {\n const now = Date.now();\n const canInitializeInterval = !this.#isIntervalPausedAt(now);\n if (this.#doesIntervalAllowAnother && this.#doesConcurrentAllowAnother) {\n const job = this.#queue.dequeue();\n if (!this.#isIntervalIgnored) {\n this.#consumeIntervalSlot(now);\n this.#scheduleRateLimitUpdate();\n }\n this.emit('active');\n job();\n if (canInitializeInterval) {\n this.#initializeIntervalIfNeeded();\n }\n taskStarted = true;\n }\n }\n return taskStarted;\n }\n #initializeIntervalIfNeeded() {\n if (this.#isIntervalIgnored || this.#intervalId !== undefined) {\n return;\n }\n // Strict mode uses timeouts instead of interval timers\n if (this.#strict) {\n return;\n }\n this.#intervalId = setInterval(() => {\n this.#onInterval();\n }, this.#interval);\n this.#intervalEnd = Date.now() + this.#interval;\n }\n #onInterval() {\n // Non-strict mode uses interval timers and intervalCount\n if (!this.#strict) {\n if (this.#intervalCount === 0 && this.#pending === 0 && this.#intervalId) {\n this.#clearIntervalTimer();\n }\n this.#intervalCount = this.#carryoverIntervalCount ? this.#pending : 0;\n }\n this.#processQueue();\n this.#scheduleRateLimitUpdate();\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 /**\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 if (typeof priority !== 'number' || !Number.isFinite(priority)) {\n throw new TypeError(`Expected \\`priority\\` to be a finite number, got \\`${priority}\\` (${typeof priority})`);\n }\n this.#queue.setPriority(id, priority);\n }\n async add(function_, options = {}) {\n // Create a copy to avoid mutating the original options object\n options = {\n timeout: this.timeout,\n ...options,\n // Assign unique ID if not provided\n id: options.id ?? (this.#idAssigner++).toString(),\n };\n return new Promise((resolve, reject) => {\n // Create a unique symbol for tracking this task\n const taskSymbol = Symbol(`task-${options.id}`);\n let cleanupQueueAbortHandler = () => undefined;\n const run = async () => {\n // Task is now running \u2014 remove the queued-state abort listener\n cleanupQueueAbortHandler();\n this.#pending++;\n // Track this running task\n this.#runningTasks.set(taskSymbol, {\n id: options.id,\n priority: options.priority ?? 0, // Match priority-queue default\n startTime: Date.now(),\n timeout: options.timeout,\n });\n let eventListener;\n try {\n // Check abort signal - if aborted, need to decrement the counter\n // that was incremented in tryToStartAnother\n try {\n options.signal?.throwIfAborted();\n }\n catch (error) {\n this.#rollbackIntervalConsumption();\n // Clean up tracking before throwing\n this.#runningTasks.delete(taskSymbol);\n throw error;\n }\n this.#lastExecutionTime = Date.now();\n let operation = function_({ signal: options.signal });\n if (options.timeout) {\n operation = pTimeout(Promise.resolve(operation), {\n milliseconds: options.timeout,\n message: `Task timed out after ${options.timeout}ms (queue has ${this.#pending} running, ${this.#queue.size} waiting)`,\n });\n }\n if (options.signal) {\n const { signal } = options;\n operation = Promise.race([operation, new Promise((_resolve, reject) => {\n eventListener = () => {\n reject(signal.reason);\n };\n signal.addEventListener('abort', eventListener, { once: true });\n })]);\n }\n const result = await operation;\n resolve(result);\n this.emit('completed', result);\n }\n catch (error) {\n reject(error);\n this.emit('error', error);\n }\n finally {\n // Clean up abort event listener\n if (eventListener) {\n options.signal?.removeEventListener('abort', eventListener);\n }\n // Remove from running tasks\n this.#runningTasks.delete(taskSymbol);\n // Use queueMicrotask to prevent deep recursion while maintaining timing\n queueMicrotask(() => {\n this.#next();\n });\n }\n };\n this.#queue.enqueue(run, options);\n const removeQueuedTask = () => {\n if (this.#queue instanceof PriorityQueue) {\n this.#queue.remove(run);\n return;\n }\n this.#queue.remove?.(options.id); // Intentionally best-effort: queued abort removal is only supported for queue classes that implement `.remove()`.\n };\n // Handle abort while task is waiting in the queue\n if (options.signal) {\n const { signal } = options;\n const queueAbortHandler = () => {\n cleanupQueueAbortHandler();\n removeQueuedTask();\n reject(signal.reason);\n this.#tryToStartAnother();\n this.emit('next');\n };\n cleanupQueueAbortHandler = () => {\n signal.removeEventListener('abort', queueAbortHandler);\n this.#queueAbortListenerCleanupFunctions.delete(cleanupQueueAbortHandler);\n };\n if (signal.aborted) {\n queueAbortHandler();\n return;\n }\n signal.addEventListener('abort', queueAbortHandler, { once: true });\n this.#queueAbortListenerCleanupFunctions.add(cleanupQueueAbortHandler);\n }\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 for (const cleanupQueueAbortHandler of this.#queueAbortListenerCleanupFunctions) {\n cleanupQueueAbortHandler();\n }\n this.#queue = new this.#queueClass();\n // Clear interval timer since queue is now empty (consistent with #tryToStartAnother)\n this.#clearIntervalTimer();\n // Note: We preserve strict mode rate-limiting state (ticks and timeout)\n // because clear() only clears queued tasks, not rate limit history.\n // This ensures that rate limits are still enforced after clearing the queue.\n // Note: We don't clear #runningTasks as those tasks are still running\n // They will be removed when they complete in the finally block\n // Force synchronous update since clear() should have immediate effect\n this.#updateRateLimitState();\n // Emit events so waiters (onEmpty, onIdle, onSizeLessThan) can resolve\n this.emit('empty');\n if (this.#pending === 0) {\n this.#clearTimeoutTimer();\n this.emit('idle');\n }\n this.emit('next');\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 /**\n The difference with `.onIdle` is that `.onPendingZero` only waits for currently running tasks to finish, ignoring queued tasks.\n\n @returns A promise that settles when all currently running tasks have completed; `queue.pending === 0`.\n */\n async onPendingZero() {\n if (this.#pending === 0) {\n return;\n }\n await this.#onEvent('pendingZero');\n }\n /**\n @returns A promise that settles when the queue becomes rate-limited due to intervalCap.\n */\n async onRateLimit() {\n if (this.isRateLimited) {\n return;\n }\n await this.#onEvent('rateLimit');\n }\n /**\n @returns A promise that settles when the queue is no longer rate-limited.\n */\n async onRateLimitCleared() {\n if (!this.isRateLimited) {\n return;\n }\n await this.#onEvent('rateLimitCleared');\n }\n /**\n @returns A promise that rejects when any task in the queue errors.\n\n Use with `Promise.race([queue.onError(), queue.onIdle()])` to fail fast on the first error while still resolving normally when the queue goes idle.\n\n Important: The promise returned by `add()` still rejects. You must handle each `add()` promise (for example, `.catch(() => {})`) to avoid unhandled rejections.\n\n @example\n ```\n import PQueue from 'p-queue';\n\n const queue = new PQueue({concurrency: 2});\n\n queue.add(() => fetchData(1)).catch(() => {});\n queue.add(() => fetchData(2)).catch(() => {});\n queue.add(() => fetchData(3)).catch(() => {});\n\n // Stop processing on first error\n try {\n await Promise.race([\n queue.onError(),\n queue.onIdle()\n ]);\n } catch (error) {\n queue.pause(); // Stop processing remaining tasks\n console.error('Queue failed:', error);\n }\n ```\n */\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n onError() {\n return new Promise((_resolve, reject) => {\n const handleError = (error) => {\n this.off('error', handleError);\n reject(error);\n };\n this.on('error', handleError);\n });\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 #setupRateLimitTracking() {\n // Only schedule updates when rate limiting is enabled\n if (this.#isIntervalIgnored) {\n return;\n }\n // Wire up to lifecycle events that affect rate limit state\n // Only 'add' and 'next' can actually change rate limit state\n this.on('add', () => {\n if (this.#queue.size > 0) {\n this.#scheduleRateLimitUpdate();\n }\n });\n this.on('next', () => {\n this.#scheduleRateLimitUpdate();\n });\n }\n #scheduleRateLimitUpdate() {\n // Skip if rate limiting is not enabled or already scheduled\n if (this.#isIntervalIgnored || this.#rateLimitFlushScheduled) {\n return;\n }\n this.#rateLimitFlushScheduled = true;\n queueMicrotask(() => {\n this.#rateLimitFlushScheduled = false;\n this.#updateRateLimitState();\n });\n }\n #rollbackIntervalConsumption() {\n if (this.#isIntervalIgnored) {\n return;\n }\n this.#rollbackIntervalSlot();\n this.#scheduleRateLimitUpdate();\n }\n #updateRateLimitState() {\n const previous = this.#rateLimitedInInterval;\n // Early exit if rate limiting is disabled or queue is empty\n if (this.#isIntervalIgnored || this.#queue.size === 0) {\n if (previous) {\n this.#rateLimitedInInterval = false;\n this.emit('rateLimitCleared');\n }\n return;\n }\n // Get the current count based on mode\n let count;\n if (this.#strict) {\n const now = Date.now();\n this.#cleanupStrictTicks(now);\n count = this.#getActiveTicksCount();\n }\n else {\n count = this.#intervalCount;\n }\n const shouldBeRateLimited = count >= this.#intervalCap;\n if (shouldBeRateLimited !== previous) {\n this.#rateLimitedInInterval = shouldBeRateLimited;\n this.emit(shouldBeRateLimited ? 'rateLimit' : 'rateLimitCleared');\n }\n }\n /**\n Whether the queue is currently rate-limited due to intervalCap.\n */\n get isRateLimited() {\n return this.#rateLimitedInInterval;\n }\n /**\n Whether the queue is saturated. Returns `true` when:\n - All concurrency slots are occupied and tasks are waiting, OR\n - The queue is rate-limited and tasks are waiting\n\n Useful for detecting backpressure and potential hanging tasks.\n\n ```js\n import PQueue from 'p-queue';\n\n const queue = new PQueue({concurrency: 2});\n\n // Backpressure handling\n if (queue.isSaturated) {\n console.log('Queue is saturated, waiting for capacity...');\n await queue.onSizeLessThan(queue.concurrency);\n }\n\n // Monitoring for stuck tasks\n setInterval(() => {\n if (queue.isSaturated) {\n console.warn(`Queue saturated: ${queue.pending} running, ${queue.size} waiting`);\n }\n }, 60000);\n ```\n */\n get isSaturated() {\n return (this.#pending === this.#concurrency && this.#queue.size > 0)\n || (this.isRateLimited && this.#queue.size > 0);\n }\n /**\n The tasks currently being executed. Each task includes its `id`, `priority`, `startTime`, `timeout` (if set), and `timeoutRemaining` (milliseconds until the task times out, or `undefined` if no timeout is set).\n\n Returns an array of task info objects.\n\n ```js\n import PQueue from 'p-queue';\n\n const queue = new PQueue({concurrency: 2, timeout: 10000});\n\n // Add tasks with IDs for better debugging\n queue.add(() => fetchUser(123), {id: 'user-123'});\n queue.add(() => fetchPosts(456), {id: 'posts-456', priority: 1});\n\n // Check what's running\n console.log(queue.runningTasks);\n // => [{\n // id: 'user-123',\n // priority: 0,\n // startTime: 1759253001716,\n // timeout: 10000,\n // timeoutRemaining: 9700\n // }, {\n // id: 'posts-456',\n // priority: 1,\n // startTime: 1759253001916,\n // timeout: 10000,\n // timeoutRemaining: 9900\n // }]\n ```\n */\n get runningTasks() {\n // Return fresh array with fresh objects to prevent mutations\n return [...this.#runningTasks.values()].map(task => ({\n ...task,\n timeoutRemaining: task.timeout ? Math.max(0, task.startTime + task.timeout - Date.now()) : undefined,\n }));\n }\n}\nexport { default as PriorityQueue } from './priority-queue.js';\n/**\nError thrown when a task times out.\n\n@example\n```\nimport PQueue, {TimeoutError} from 'p-queue';\n\nconst queue = new PQueue({timeout: 1000});\n\ntry {\n await queue.add(() => someTask());\n} catch (error) {\n if (error instanceof TimeoutError) {\n console.log('Task timed out');\n }\n}\n```\n*/\nexport { TimeoutError } from 'p-timeout';\n", "import { RecordType } from '../index.js'\n\nexport function getTypes (types?: RecordType | RecordType[]): RecordType[] {\n const DEFAULT_TYPES = [\n RecordType.A\n ]\n\n if (types == null) {\n return DEFAULT_TYPES\n }\n\n if (Array.isArray(types)) {\n if (types.length === 0) {\n return DEFAULT_TYPES\n }\n\n return types\n }\n\n return [\n types\n ]\n}\n", "import { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { RecordType } from '../index.js'\nimport type { DNSResponse } from '../index.js'\n\n/**\n * This TTL will be used if the remote service does not return one\n */\nexport const DEFAULT_TTL = 60\n\nexport function toDNSResponse (obj: any): DNSResponse {\n return {\n Status: obj.Status ?? 0,\n TC: obj.TC ?? obj.flag_tc ?? false,\n RD: obj.RD ?? obj.flag_rd ?? false,\n RA: obj.RA ?? obj.flag_ra ?? false,\n AD: obj.AD ?? obj.flag_ad ?? false,\n CD: obj.CD ?? obj.flag_cd ?? false,\n Question: (obj.Question ?? obj.questions ?? []).map((question: any) => {\n return {\n name: question.name,\n type: RecordType[question.type]\n }\n }),\n Answer: (obj.Answer ?? obj.answers ?? []).map((answer: any) => {\n return {\n name: answer.name,\n type: RecordType[answer.type],\n TTL: (answer.TTL ?? answer.ttl ?? DEFAULT_TTL),\n data: answer.data instanceof Uint8Array ? uint8ArrayToString(answer.data) : answer.data\n }\n })\n }\n}\n", "import PQueue from 'p-queue'\nimport { CustomProgressEvent } from 'progress-events'\nimport { RecordType } from '../index.js'\nimport { getTypes } from '../utils/get-types.js'\nimport { toDNSResponse } from '../utils/to-dns-response.js'\nimport type { DNSResponse } from '../index.js'\nimport type { DNSResolver } from './index.js'\n\n/**\n * Browsers limit concurrent connections per host (~6), we don't want to exhaust\n * the limit so this value controls how many DNS queries can be in flight at\n * once.\n */\nexport const DEFAULT_QUERY_CONCURRENCY = 4\n\nexport interface DNSJSONOverHTTPSOptions {\n queryConcurrency?: number\n}\n\n/**\n * Uses the RFC 8427 'application/dns-json' content-type to resolve DNS queries.\n *\n * Supports and server that uses the same schema as Google's DNS over HTTPS\n * resolver.\n *\n * This resolver needs fewer dependencies than the regular DNS-over-HTTPS\n * resolver so can result in a smaller bundle size and consequently is preferred\n * for browser use.\n *\n * @see https://developers.cloudflare.com/1.1.1.1/encryption/dns-over-https/make-api-requests/dns-json/\n * @see https://github.com/curl/curl/wiki/DNS-over-HTTPS#publicly-available-servers\n * @see https://dnsprivacy.org/public_resolvers/\n * @see https://datatracker.ietf.org/doc/html/rfc8427\n */\nexport function dnsJsonOverHttps (url: string, init: DNSJSONOverHTTPSOptions = {}): DNSResolver {\n const httpQueue = new PQueue({\n concurrency: init.queryConcurrency ?? DEFAULT_QUERY_CONCURRENCY\n })\n\n return async (fqdn, options = {}) => {\n const log = options?.logger?.forComponent('dns:dns-json-over-https')\n const searchParams = new URLSearchParams()\n searchParams.set('name', fqdn)\n\n getTypes(options.types).forEach(type => {\n // We pass record type as a string to the server because cloudflare DNS bug. see https://github.com/ipfs/helia/issues/474\n searchParams.append('type', RecordType[type])\n })\n\n options.onProgress?.(new CustomProgressEvent<string>('dns:query', fqdn))\n\n log?.('GET %s', `${url}?${searchParams}`)\n\n // query DNS-JSON over HTTPS server\n const response = await httpQueue.add(async () => {\n const res = await fetch(`${url}?${searchParams}`, {\n headers: {\n accept: 'application/dns-json'\n },\n signal: options?.signal\n })\n\n log?.('GET %s %d', res.url, res.status)\n\n if (res.status !== 200) {\n throw new Error(`Unexpected HTTP status: ${res.status} - ${res.statusText}`)\n }\n\n const response = toDNSResponse(await res.json())\n\n options.onProgress?.(new CustomProgressEvent<DNSResponse>('dns:response', response))\n\n return response\n }, {\n signal: options.signal\n })\n\n if (response == null) {\n throw new Error('No DNS response received')\n }\n\n return response\n }\n}\n", "import { dnsJsonOverHttps } from './dns-json-over-https.js'\nimport type { DNSResolver } from './index.js'\n\nexport function defaultResolver (): DNSResolver[] {\n return [\n dnsJsonOverHttps('https://cloudflare-dns.com/dns-query'),\n dnsJsonOverHttps('https://dns.google/resolve')\n ]\n}\n", "import hashlru from 'hashlru'\nimport { RecordType } from '../index.js'\nimport { DEFAULT_TTL, toDNSResponse } from './to-dns-response.js'\nimport type { Answer, DNSResponse } from '../index.js'\n\ninterface CachedAnswer {\n expires: number\n value: Answer\n}\n\nexport interface AnswerCache {\n get (fqdn: string, types: RecordType[]): DNSResponse | undefined\n add (domain: string, answer: Answer): void\n remove (domain: string, type: ResponseType): void\n clear (): void\n}\n\n/**\n * Time Aware Least Recent Used Cache\n *\n * @see https://arxiv.org/pdf/1801.00390\n */\nclass CachedAnswers {\n private readonly lru: any\n\n constructor (maxSize: number) {\n // @ts-expect-error types are broken - https://github.com/dominictarr/hashlru/pull/24\n this.lru = hashlru(maxSize)\n }\n\n get (fqdn: string, types: RecordType[]): DNSResponse | undefined {\n let foundAllAnswers = true\n const answers: Answer[] = []\n\n for (const type of types) {\n const cached = this.getAnswers(fqdn, type)\n\n if (cached.length === 0) {\n foundAllAnswers = false\n break\n }\n\n answers.push(...cached)\n }\n\n if (foundAllAnswers) {\n return toDNSResponse({ answers })\n }\n }\n\n private getAnswers (domain: string, type: RecordType): Answer[] {\n const key = `${domain.toLowerCase()}-${type}`\n const answers: CachedAnswer[] = this.lru.get(key)\n\n if (answers != null) {\n const cachedAnswers = answers\n .filter((entry) => {\n return entry.expires > Date.now()\n })\n .map(({ expires, value }) => ({\n ...value,\n TTL: Math.round((expires - Date.now()) / 1000),\n type: RecordType[value.type]\n }))\n\n if (cachedAnswers.length === 0) {\n this.lru.remove(key)\n }\n\n // @ts-expect-error hashlru stringifies stored types which turns enums\n // into strings, we convert back into enums above but tsc doesn't know\n return cachedAnswers\n }\n\n return []\n }\n\n add (domain: string, answer: Answer): void {\n const key = `${domain.toLowerCase()}-${answer.type}`\n\n const answers: CachedAnswer[] = this.lru.get(key) ?? []\n answers.push({\n expires: Date.now() + ((answer.TTL ?? DEFAULT_TTL) * 1000),\n value: answer\n })\n\n this.lru.set(key, answers)\n }\n\n remove (domain: string, type: ResponseType): void {\n const key = `${domain.toLowerCase()}-${type}`\n\n this.lru.remove(key)\n }\n\n clear (): void {\n this.lru.clear()\n }\n}\n\n/**\n * Avoid sending multiple queries for the same hostname by caching results\n */\nexport function cache (size: number): AnswerCache {\n return new CachedAnswers(size)\n}\n", "import { CustomProgressEvent } from 'progress-events'\nimport { DNSQueryFailedError } from './errors.ts'\nimport { defaultResolver } from './resolvers/default.js'\nimport { cache } from './utils/cache.js'\nimport { getTypes } from './utils/get-types.js'\nimport type { DNS as DNSInterface, DNSInit, DNSResponse, QueryOptions } from './index.js'\nimport type { DNSResolver } from './resolvers/index.js'\nimport type { AnswerCache } from './utils/cache.js'\nimport type { ComponentLogger } from '@libp2p/interface'\n\nconst DEFAULT_ANSWER_CACHE_SIZE = 1000\n\nexport class DNS implements DNSInterface {\n private readonly resolvers: Record<string, DNSResolver[]>\n private readonly cache: AnswerCache\n private readonly logger?: ComponentLogger\n\n constructor (init: DNSInit) {\n this.resolvers = {}\n this.cache = cache(init.cacheSize ?? DEFAULT_ANSWER_CACHE_SIZE)\n this.logger = init.logger\n\n Object.entries(init.resolvers ?? {}).forEach(([tld, resolver]) => {\n if (!Array.isArray(resolver)) {\n resolver = [resolver]\n }\n\n // convert `com` -> `com.`\n if (!tld.endsWith('.')) {\n tld = `${tld}.`\n }\n\n this.resolvers[tld] = resolver\n })\n\n // configure default resolver if none specified\n if (this.resolvers['.'] == null) {\n this.resolvers['.'] = defaultResolver()\n }\n }\n\n /**\n * Queries DNS resolvers for the passed record types for the passed domain.\n *\n * If cached records exist for all desired types they will be returned\n * instead.\n *\n * Any new responses will be added to the cache for subsequent requests.\n */\n async query (domain: string, options: QueryOptions = {}): Promise<DNSResponse> {\n const types = getTypes(options.types)\n const cached = options.cached !== false ? this.cache.get(domain, types) : undefined\n\n if (cached != null) {\n options.onProgress?.(new CustomProgressEvent<DNSResponse>('dns:cache', cached))\n\n return cached\n }\n\n const tld = `${domain.split('.').pop()}.`\n const resolvers = (this.resolvers[tld] ?? this.resolvers['.']).sort(() => {\n return (Math.random() > 0.5) ? -1 : 1\n })\n\n const errors: Error[] = []\n\n for (const resolver of resolvers) {\n // skip further resolutions if the user aborted the signal\n if (options.signal?.aborted === true) {\n break\n }\n\n try {\n const result = await resolver(domain, {\n ...options,\n logger: this.logger,\n types\n })\n\n for (const answer of result.Answer) {\n this.cache.add(domain, answer)\n }\n\n return result\n } catch (err: any) {\n errors.push(err)\n options.onProgress?.(new CustomProgressEvent<Error>('dns:error', err))\n }\n }\n\n throw new DNSQueryFailedError(errors, `DNS lookup of ${domain} ${types} failed`)\n }\n}\n", "/**\n * @packageDocumentation\n *\n * Query DNS records using `node:dns`, DNS over HTTP and/or DNSJSON over HTTP.\n *\n * A list of publicly accessible servers can be found [here](https://github.com/curl/curl/wiki/DNS-over-HTTPS#publicly-available-servers).\n *\n * @example Using the default resolver\n *\n * ```TypeScript\n * import { dns } from '@multiformats/dns'\n *\n * const resolver = dns()\n *\n * // resolve A records with a 5s timeout\n * const result = await dns.query('google.com', {\n * signal: AbortSignal.timeout(5000)\n * })\n * ```\n *\n * @example Using per-TLD resolvers\n *\n * ```TypeScript\n * import { dns } from '@multiformats/dns'\n * import { dnsJsonOverHttps } from '@multiformats/dns/resolvers'\n *\n * const resolver = dns({\n * resolvers: {\n * // will only be used to resolve `.com` addresses\n * 'com.': dnsJsonOverHttps('https://cloudflare-dns.com/dns-query'),\n *\n * // this can also be an array, resolvers will be shuffled and tried in\n * // series\n * 'net.': [\n * dnsJsonOverHttps('https://dns.google/resolve'),\n * dnsJsonOverHttps('https://dns.pub/dns-query')\n * ],\n *\n * // will only be used to resolve all other addresses\n * '.': dnsJsonOverHttps('https://dnsforge.de/dns-query'),\n * }\n * })\n * ```\n *\n * @example Query for specific record types\n *\n * ```TypeScript\n * import { dns, RecordType } from '@multiformats/dns'\n *\n * const resolver = dns()\n *\n * // resolve only TXT records\n * const result = await dns.query('google.com', {\n * types: [\n * RecordType.TXT\n * ]\n * })\n * ```\n *\n * ## Caching\n *\n * Individual Aanswers are cached so. If you make a request, for which all\n * record types are cached, all values will be pulled from the cache.\n *\n * If any of the record types are not cached, a new request will be resolved as\n * if none of the records were cached, and the cache will be updated to include\n * the new results.\n *\n * @example Ignoring the cache\n *\n * ```TypeScript\n * import { dns, RecordType } from '@multiformats/dns'\n *\n * const resolver = dns()\n *\n * // do not used cached results, always resolve a new query\n * const result = await dns.query('google.com', {\n * cached: false\n * })\n * ```\n */\n\nimport { DNS as DNSClass } from './dns.js'\nimport type { DNSResolver } from './resolvers/index.js'\nimport type { ComponentLogger } from '@libp2p/interface'\nimport type { ProgressEvent, ProgressOptions } from 'progress-events'\n\n/**\n * A subset of DNS Record Types\n *\n * @see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4.\n */\nexport enum RecordType {\n A = 1,\n CNAME = 5,\n TXT = 16,\n AAAA = 28\n}\n\nexport interface Question {\n /**\n * The record name requested.\n */\n name: string\n\n /**\n * The type of DNS record requested.\n *\n * @see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4.\n */\n type: RecordType\n}\n\nexport interface Answer {\n /**\n * The record owner.\n */\n name: string\n\n /**\n * The type of DNS record.\n *\n * @see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4\n */\n type: RecordType\n\n /**\n * The number of seconds the answer can be stored in cache before it is\n * considered stale.\n */\n TTL: number\n\n /**\n * The value of the DNS record for the given name and type. The data will be\n * in text for standardized record types and in hex for unknown types.\n */\n data: string\n}\n\nexport interface DNSResponse {\n /**\n * The Response Code of the DNS Query.\n *\n * @see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-6\n */\n Status: number\n\n /**\n * If true, it means the truncated bit was set. This happens when the DNS\n * answer is larger than a single UDP or TCP packet.\n */\n TC: boolean\n\n /**\n * If true, it means the Recursive Desired bit was set.\n */\n RD: boolean\n\n /**\n * If true, it means the Recursion Available bit was set.\n */\n RA: boolean\n\n /**\n * If true, it means that every record in the answer was verified with DNSSEC.\n */\n AD: boolean\n\n /**\n * If true, the client asked to disable DNSSEC validation.\n */\n CD: boolean\n\n /**\n * The records that were requested.\n */\n Question: Question[]\n\n /**\n * Values for the records that were requested.\n */\n Answer: Answer[]\n}\n\n/**\n * The default maximum amount of recursion allowed during a query\n */\nexport const MAX_RECURSIVE_DEPTH = 32\n\nexport interface QueryOptions extends ProgressOptions<ResolveDnsProgressEvents> {\n signal?: AbortSignal\n\n /**\n * Do not use cached DNS entries\n *\n * @default false\n */\n cached?: boolean\n\n /**\n * The type or types of DNS records to resolve\n *\n * @default [RecordType.A, RecordType.AAAA]\n */\n types?: RecordType | RecordType[]\n\n /**\n * An optional logger\n */\n logger?: ComponentLogger\n}\n\nexport interface DNS {\n query(fqdn: string, options?: QueryOptions): Promise<DNSResponse>\n}\n\nexport type ResolveDnsProgressEvents =\n ProgressEvent<'dns:cache', string> |\n ProgressEvent<'dns:query', string> |\n ProgressEvent<'dns:response', DNSResponse> |\n ProgressEvent<'dns:error', Error>\n\nexport type DNSResolvers = Record<string, DNSResolver | DNSResolver[]>\n\nexport interface DNSInit {\n /**\n * A set of resolvers used to answer DNS queries\n *\n * String keys control which resolvers are used for which TLDs.\n *\n * @example\n *\n * ```TypeScript\n * import { dns } from '@multiformats/dns'\n * import { dnsOverHttps } from '@multiformats/dns'\n *\n * const resolver = dns({\n * resolvers: {\n * // only used for .com domains\n * 'com.': dnsOverHttps('https://example-1.com'),\n *\n * // only used for .net domains, can be an array\n * 'net.': [\n * dnsOverHttps('https://example-2.com'),\n * dnsOverHttps('https://example-3.com'),\n * ],\n *\n * // used for everything else (can be an array)\n * '.': dnsOverHttps('https://example-4.com')\n * }\n * })\n * ```\n */\n resolvers?: DNSResolvers\n\n /**\n * To avoid repeating DNS lookups, successful answers are cached according to\n * their TTL. To avoid exhausting memory, this option controls how many\n * answers to cache.\n *\n * @default 1000\n */\n cacheSize?: number\n\n /**\n * An optional logger\n */\n logger?: ComponentLogger\n}\n\nexport function dns (init: DNSInit = {}): DNS {\n return new DNSClass(init)\n}\n", "//#region src/index.ts\nconst s = 1e3;\nconst m = s * 60;\nconst h = m * 60;\nconst d = h * 24;\nconst w = d * 7;\nconst y = d * 365.25;\nconst mo = y / 12;\nfunction ms(value, options) {\n\tif (typeof value === \"string\") return parse(value);\n\telse if (typeof value === \"number\") return format(value, options);\n\tthrow new Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(value)}`);\n}\n/**\n* Parse the given string and return milliseconds.\n*\n* @param str - A string to parse to milliseconds\n* @returns The parsed value in milliseconds, or `NaN` if the string can't be\n* parsed\n*/\nfunction parse(str) {\n\tif (typeof str !== \"string\" || str.length === 0 || str.length > 100) throw new Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(str)}`);\n\tconst match = /^(?<value>-?\\d*\\.?\\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(str);\n\tif (!match?.groups) return NaN;\n\tconst { value, unit = \"ms\" } = match.groups;\n\tconst n = parseFloat(value);\n\tconst matchUnit = unit.toLowerCase();\n\t/* istanbul ignore next - istanbul doesn't understand, but thankfully the TypeScript the exhaustiveness check in the default case keeps us type safe here */\n\tswitch (matchUnit) {\n\t\tcase \"years\":\n\t\tcase \"year\":\n\t\tcase \"yrs\":\n\t\tcase \"yr\":\n\t\tcase \"y\": return n * y;\n\t\tcase \"months\":\n\t\tcase \"month\":\n\t\tcase \"mo\": return n * mo;\n\t\tcase \"weeks\":\n\t\tcase \"week\":\n\t\tcase \"w\": return n * w;\n\t\tcase \"days\":\n\t\tcase \"day\":\n\t\tcase \"d\": return n * d;\n\t\tcase \"hours\":\n\t\tcase \"hour\":\n\t\tcase \"hrs\":\n\t\tcase \"hr\":\n\t\tcase \"h\": return n * h;\n\t\tcase \"minutes\":\n\t\tcase \"minute\":\n\t\tcase \"mins\":\n\t\tcase \"min\":\n\t\tcase \"m\": return n * m;\n\t\tcase \"seconds\":\n\t\tcase \"second\":\n\t\tcase \"secs\":\n\t\tcase \"sec\":\n\t\tcase \"s\": return n * s;\n\t\tcase \"milliseconds\":\n\t\tcase \"millisecond\":\n\t\tcase \"msecs\":\n\t\tcase \"msec\":\n\t\tcase \"ms\": return n;\n\t\tdefault: throw new Error(`Unknown unit \"${matchUnit}\" provided to ms.parse(). value=${JSON.stringify(str)}`);\n\t}\n}\n/**\n* Parse the given StringValue and return milliseconds.\n*\n* @param value - A typesafe StringValue to parse to milliseconds\n* @returns The parsed value in milliseconds, or `NaN` if the string can't be\n* parsed\n*/\nfunction parseStrict(value) {\n\treturn parse(value);\n}\n/**\n* Short format for `ms`.\n*/\nfunction fmtShort(ms$1) {\n\tconst msAbs = Math.abs(ms$1);\n\tif (msAbs >= y) return `${Math.round(ms$1 / y)}y`;\n\tif (msAbs >= mo) return `${Math.round(ms$1 / mo)}mo`;\n\tif (msAbs >= w) return `${Math.round(ms$1 / w)}w`;\n\tif (msAbs >= d) return `${Math.round(ms$1 / d)}d`;\n\tif (msAbs >= h) return `${Math.round(ms$1 / h)}h`;\n\tif (msAbs >= m) return `${Math.round(ms$1 / m)}m`;\n\tif (msAbs >= s) return `${Math.round(ms$1 / s)}s`;\n\treturn `${ms$1}ms`;\n}\n/**\n* Long format for `ms`.\n*/\nfunction fmtLong(ms$1) {\n\tconst msAbs = Math.abs(ms$1);\n\tif (msAbs >= y) return plural(ms$1, msAbs, y, \"year\");\n\tif (msAbs >= mo) return plural(ms$1, msAbs, mo, \"month\");\n\tif (msAbs >= w) return plural(ms$1, msAbs, w, \"week\");\n\tif (msAbs >= d) return plural(ms$1, msAbs, d, \"day\");\n\tif (msAbs >= h) return plural(ms$1, msAbs, h, \"hour\");\n\tif (msAbs >= m) return plural(ms$1, msAbs, m, \"minute\");\n\tif (msAbs >= s) return plural(ms$1, msAbs, s, \"second\");\n\treturn `${ms$1} ms`;\n}\n/**\n* Format the given integer as a string.\n*\n* @param ms - milliseconds\n* @param options - Options for the conversion\n* @returns The formatted string\n*/\nfunction format(ms$1, options) {\n\tif (typeof ms$1 !== \"number\" || !Number.isFinite(ms$1)) throw new Error(\"Value provided to ms.format() must be of type number.\");\n\treturn options?.long ? fmtLong(ms$1) : fmtShort(ms$1);\n}\n/**\n* Pluralization helper.\n*/\nfunction plural(ms$1, msAbs, n, name) {\n\tconst isPlural = msAbs >= n * 1.5;\n\treturn `${Math.round(ms$1 / n)} ${name}${isPlural ? \"s\" : \"\"}`;\n}\n\n//#endregion\nexport { format, ms, parse, parseStrict };", "/* eslint-disable no-console */\n\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\nimport { ms as humanize } from 'ms'\nimport type { Debug, Debugger, Options } from './index.ts'\n\nexport default function setup (env: any): Debug {\n createDebug.debug = createDebug\n createDebug.default = createDebug\n createDebug.coerce = coerce\n createDebug.disable = disable\n createDebug.enable = enable\n createDebug.enabled = enabled\n createDebug.humanize = humanize\n createDebug.destroy = destroy\n\n Object.keys(env).forEach(key => {\n // @ts-expect-error cannot use string to index type\n createDebug[key] = env[key]\n })\n\n /**\n * The currently active debug mode names, and names to skip.\n */\n\n createDebug.names = [] as any[]\n createDebug.skips = [] as any[]\n\n /**\n * Map of special \"%n\" handling functions, for the debug \"format\" argument.\n *\n * Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n */\n createDebug.formatters = {} satisfies Record<string, any>\n\n /**\n * Selects a color for a debug namespace\n *\n * @param {string} namespace - The namespace string for the debug instance to be colored\n * @returns {number | string} An ANSI color code for the given namespace\n */\n function selectColor (namespace: string): number | string {\n let hash = 0\n\n for (let i = 0; i < namespace.length; i++) {\n hash = ((hash << 5) - hash) + namespace.charCodeAt(i)\n hash |= 0 // Convert to 32bit integer\n }\n\n // @ts-expect-error colors is not in the types\n return createDebug.colors[Math.abs(hash) % createDebug.colors.length]\n }\n createDebug.selectColor = selectColor\n\n /**\n * Create a debugger with the given `namespace`.\n *\n * @param {string} namespace\n * @returns {Function}\n */\n function createDebug (namespace: string, options?: Options): Debugger {\n let prevTime: any\n let enableOverride: any = null\n let namespacesCache: any\n let enabledCache: any\n\n function debug (...args: any[]): void {\n // Disabled?\n // @ts-expect-error enabled is not in the types\n if (!debug.enabled) {\n return\n }\n\n const self: any = debug\n\n // Set `diff` timestamp\n const curr = Number(new Date())\n const ms = curr - (prevTime || curr)\n self.diff = ms\n self.prev = prevTime\n self.curr = curr\n prevTime = curr\n\n args[0] = createDebug.coerce(args[0])\n\n if (typeof args[0] !== 'string') {\n // Anything else let's inspect with %O\n args.unshift('%O')\n }\n\n // Apply any `formatters` transformations\n let index = 0\n args[0] = args[0].replace(/%([a-zA-Z%])/g, (match: any, format: any): any => {\n // If we encounter an escaped % then don't increase the array index\n if (match === '%%') {\n return '%'\n }\n index++\n // @ts-expect-error formatters is not in the types\n const formatter = createDebug.formatters[format]\n if (typeof formatter === 'function') {\n const val = args[index]\n match = formatter.call(self, val)\n\n // Now we need to remove `args[index]` since it's inlined in the `format`\n args.splice(index, 1)\n index--\n }\n return match\n })\n\n // Apply env-specific formatting (colors, etc.)\n // @ts-expect-error formatArgs is not in the types\n createDebug.formatArgs.call(self, args)\n\n if (options?.onLog != null) {\n options.onLog(...args)\n }\n\n // @ts-expect-error log is not in the types\n const logFn = self.log || createDebug.log\n logFn.apply(self, args)\n }\n\n debug.namespace = namespace\n // @ts-expect-error useColors is not in the types\n debug.useColors = createDebug.useColors()\n debug.color = createDebug.selectColor(namespace)\n debug.extend = extend\n debug.destroy = createDebug.destroy // XXX Temporary. Will be removed in the next major release.\n\n Object.defineProperty(debug, 'enabled', {\n enumerable: true,\n configurable: false,\n get: () => {\n if (enableOverride !== null) {\n return enableOverride\n }\n // @ts-expect-error namespaces is not in the types\n if (namespacesCache !== createDebug.namespaces) {\n // @ts-expect-error namespaces is not in the types\n namespacesCache = createDebug.namespaces\n enabledCache = createDebug.enabled(namespace)\n }\n\n return enabledCache\n },\n set: v => {\n enableOverride = v\n }\n })\n\n // Env-specific initialization logic for debug instances\n // @ts-expect-error init is not in the types\n if (typeof createDebug.init === 'function') {\n // @ts-expect-error init is not in the types\n createDebug.init(debug)\n }\n\n // @ts-expect-error some properties are added dynamically\n return debug\n }\n\n function extend (this: any, namespace: string, delimiter: string): any {\n const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace)\n newDebug.log = this.log\n return newDebug\n }\n\n /**\n * Enables a debug mode by namespaces. This can include modes\n * separated by a colon and wildcards.\n *\n * @param {string} namespaces\n */\n function enable (namespaces: string): void {\n // @ts-expect-error save is not in the types\n createDebug.save(namespaces)\n // @ts-expect-error namespaces is not in the types\n createDebug.namespaces = namespaces\n\n createDebug.names = []\n createDebug.skips = []\n\n let i\n const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/)\n const len = split.length\n\n for (i = 0; i < len; i++) {\n if (!split[i]) {\n // ignore empty strings\n continue\n }\n\n namespaces = split[i].replace(/\\*/g, '.*?')\n\n if (namespaces[0] === '-') {\n createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'))\n } else {\n createDebug.names.push(new RegExp('^' + namespaces + '$'))\n }\n }\n }\n\n /**\n * Disable debug output.\n *\n * @returns {string} namespaces\n */\n function disable (): string {\n const namespaces = [\n ...createDebug.names.map(toNamespace),\n ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n ].join(',')\n createDebug.enable('')\n return namespaces\n }\n\n /**\n * Returns true if the given mode name is enabled, false otherwise.\n *\n * @param {string} name\n * @returns {boolean}\n */\n function enabled (name: string): boolean {\n if (name[name.length - 1] === '*') {\n return true\n }\n\n let i\n let len\n\n for (i = 0, len = createDebug.skips.length; i < len; i++) {\n if (createDebug.skips[i].test(name)) {\n return false\n }\n }\n\n for (i = 0, len = createDebug.names.length; i < len; i++) {\n if (createDebug.names[i].test(name)) {\n return true\n }\n }\n\n return false\n }\n\n /**\n * Convert regexp to namespace\n */\n function toNamespace (regexp: RegExp): string {\n return regexp.toString()\n .substring(2, regexp.toString().length - 2)\n .replace(/\\.\\*\\?$/, '*')\n }\n\n /**\n * Coerce `val`.\n */\n function coerce (val: any): any {\n if (val instanceof Error) {\n return val.stack ?? val.message\n }\n return val\n }\n\n /**\n * XXX DO NOT USE. This is a temporary stub function.\n * XXX It WILL be removed in the next major release.\n */\n function destroy (): void {\n console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.')\n }\n\n // @ts-expect-error setupFormatters is not in the types\n createDebug.setupFormatters(createDebug.formatters)\n\n // @ts-expect-error load is not in the types\n createDebug.enable(createDebug.load())\n\n // @ts-expect-error some properties are added dynamically\n return createDebug\n}\n", "/* eslint-disable no-console */\n\n/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\nimport { ms as humanize } from 'ms'\nimport setup from './common.ts'\n\nconst storage = localstorage()\n\n/**\n * Colors.\n */\nconst colors = [\n '#0000CC',\n '#0000FF',\n '#0033CC',\n '#0033FF',\n '#0066CC',\n '#0066FF',\n '#0099CC',\n '#0099FF',\n '#00CC00',\n '#00CC33',\n '#00CC66',\n '#00CC99',\n '#00CCCC',\n '#00CCFF',\n '#3300CC',\n '#3300FF',\n '#3333CC',\n '#3333FF',\n '#3366CC',\n '#3366FF',\n '#3399CC',\n '#3399FF',\n '#33CC00',\n '#33CC33',\n '#33CC66',\n '#33CC99',\n '#33CCCC',\n '#33CCFF',\n '#6600CC',\n '#6600FF',\n '#6633CC',\n '#6633FF',\n '#66CC00',\n '#66CC33',\n '#9900CC',\n '#9900FF',\n '#9933CC',\n '#9933FF',\n '#99CC00',\n '#99CC33',\n '#CC0000',\n '#CC0033',\n '#CC0066',\n '#CC0099',\n '#CC00CC',\n '#CC00FF',\n '#CC3300',\n '#CC3333',\n '#CC3366',\n '#CC3399',\n '#CC33CC',\n '#CC33FF',\n '#CC6600',\n '#CC6633',\n '#CC9900',\n '#CC9933',\n '#CCCC00',\n '#CCCC33',\n '#FF0000',\n '#FF0033',\n '#FF0066',\n '#FF0099',\n '#FF00CC',\n '#FF00FF',\n '#FF3300',\n '#FF3333',\n '#FF3366',\n '#FF3399',\n '#FF33CC',\n '#FF33FF',\n '#FF6600',\n '#FF6633',\n '#FF9900',\n '#FF9933',\n '#FFCC00',\n '#FFCC33'\n]\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors (): boolean {\n // NB: In an Electron preload script, document will be defined but not fully\n // initialized. Since we know we're in Chrome, we'll just detect this case\n // explicitly\n // @ts-expect-error window.process.type and window.process.__nwjs are not in the types\n if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n return true\n }\n\n // Internet Explorer and Edge do not support colors.\n if (typeof navigator !== 'undefined' && (navigator.userAgent?.toLowerCase().match(/(edge|trident)\\/(\\d+)/) != null)) {\n return false\n }\n\n // Is webkit? http://stackoverflow.com/a/16459606/376773\n // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n // @ts-expect-error document.documentElement.style.WebkitAppearance is not in the types\n return (typeof document !== 'undefined' && document.documentElement?.style?.WebkitAppearance) ||\n // Is firebug? http://stackoverflow.com/a/398120/376773\n // @ts-expect-error window.console.firebug and window.console.exception are not in the types\n (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n // Is firefox >= v31?\n // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n (typeof navigator !== 'undefined' && (navigator.userAgent?.toLowerCase().match(/firefox\\/(\\d+)/) != null) && parseInt(RegExp.$1, 10) >= 31) ||\n // Double check webkit in userAgent just in case we are in a worker\n (typeof navigator !== 'undefined' && navigator.userAgent?.toLowerCase().match(/applewebkit\\/(\\d+)/))\n}\n\n/**\n * Colorize log arguments if enabled.\n */\nfunction formatArgs (this: any, args: any[]): void {\n args[0] = (this.useColors ? '%c' : '') +\n this.namespace +\n (this.useColors ? ' %c' : ' ') +\n args[0] +\n (this.useColors ? '%c ' : ' ') +\n '+' + humanize(this.diff)\n\n if (!this.useColors) {\n return\n }\n\n const c = 'color: ' + this.color\n args.splice(1, 0, c, 'color: inherit')\n\n // The final \"%c\" is somewhat tricky, because there could be other\n // arguments passed either before or after the %c, so we need to\n // figure out the correct index to insert the CSS into\n let index = 0\n let lastC = 0\n args[0].replace(/%[a-zA-Z%]/g, (match: string) => {\n if (match === '%%') {\n return\n }\n index++\n if (match === '%c') {\n // We only are interested in the *last* %c\n // (the user may have provided their own)\n lastC = index\n }\n })\n\n args.splice(lastC, 0, c)\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n */\nconst log = console.debug ?? console.log ?? (() => { })\n\n/**\n * Save `namespaces`.\n *\n * @param {string} namespaces\n */\nfunction save (namespaces: string): void {\n try {\n if (namespaces) {\n storage?.setItem('debug', namespaces)\n } else {\n storage?.removeItem('debug')\n }\n } catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n}\n\n/**\n * Load `namespaces`.\n *\n * @returns {string} returns the previously persisted debug modes\n */\nfunction load (): string | null | undefined {\n let r\n try {\n r = storage?.getItem('debug')\n } catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n\n // If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n if (!r && typeof globalThis.process !== 'undefined' && 'env' in globalThis.process) {\n r = globalThis.process.env.DEBUG\n }\n\n return r\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n */\nfunction localstorage (): Storage | undefined {\n try {\n // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n // The Browser also has localStorage in the global context.\n return localStorage\n } catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n}\n\nfunction setupFormatters (formatters: any): void {\n /**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n formatters.j = function (v: any) {\n try {\n return JSON.stringify(v)\n } catch (error: any) {\n return '[UnexpectedJSONParseError]: ' + error.message\n }\n }\n}\n\nexport default setup({ formatArgs, save, load, useColors, setupFormatters, colors, storage, log })\n", "/**\n * @packageDocumentation\n *\n * This module is a fork of the [debug](https://www.npmjs.com/package/debug) module. It has been converted to TypeScript and the output is ESM.\n *\n * It is API compatible with no extra features or bug fixes, it should only be used if you want a 100% ESM application.\n *\n * ESM should be arriving in `debug@5.x.x` so this module can be retired after that.\n *\n * Please see [debug](https://www.npmjs.com/package/debug) for API details.\n */\n\n/**\n * Module dependencies.\n */\nimport weald from './node.ts'\nimport type { ms } from 'ms'\n\nexport interface Options {\n /**\n * Receives log lines. The default transport writes the log line to\n * `process.stderr`, `console.debug` or `console.log` depending on what is\n * available in the environment.\n *\n * The args are not formatted - they can be passed to `util.format` from\n * Node.js or to `format` exported from this module as `weald/format`.\n *\n * @example Receiving log lines\n *\n * ```ts\n * import debug from 'weald'\n * import { format } from 'weald/format'\n *\n * const logger = debug('my-namespace', {\n * onLog (...args: any[]) {\n * const line = format(...args)\n * // do something with `line`\n * }\n * })\n * ```\n */\n onLog?(...args: any[]): void\n}\n\nexport interface Debug {\n (namespace: string, options?: Options): Debugger\n coerce(val: any): any\n disable(...args: string[]): string\n enable(namespaces: string | boolean): void\n enabled(namespaces: string): boolean\n formatArgs(this: Debugger, args: any[]): void\n log(fmt: string, ...args: any[]): unknown\n selectColor(namespace: string): string | number\n humanize: typeof ms\n useColors(): boolean\n\n names: RegExp[]\n skips: RegExp[]\n\n formatters: Formatters\n\n inspectOpts?: {\n hideDate?: boolean | number | null\n colors?: boolean | number | null\n depth?: boolean | number | null\n showHidden?: boolean | number | null\n }\n}\n\nexport type Formatters = Record<string, (v: any) => string>\n\nexport interface Debugger {\n (formatter: any, ...args: any[]): void\n\n color: string\n diff: number\n enabled: boolean\n log(fmt: string, ...args: any[]): unknown\n namespace: string\n destroy(): boolean\n extend(namespace: string, delimiter?: string): Debugger\n useColors(): boolean\n}\n\nexport default weald\n", "/**\n * @packageDocumentation\n *\n * A logger based on [weald](https://www.npmjs.com/package/weald) that contains custom formatters binary data in common multibase formats - base58btc, base32, base36 and base64 - all other logged objects ([CID](https://docs.ipfs.tech/concepts/content-addressing/)s, [Multiaddrs](https://multiformats.io/multiaddr/), etc) should contain a suitable `toString()` method.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from 'birnam'\n *\n * const log = logger('helia:my:component:name')\n *\n * try {\n * // an operation\n * log('something happened: %s', 'it was ok')\n * } catch (err) {\n * log.error('something bad happened: %e', err)\n * }\n *\n * log('with this peer: %s', {\n * toString () {\n * return '12D3Foo'\n * }\n * })\n * log('and this base58btc: %z', Uint8Array.from([0, 1, 2, 3]))\n * log('and this base32: %b', Uint8Array.from([4, 5, 6, 7]))\n * ```\n *\n * ```console\n * $ DEBUG=helia:* node index.js\n * something happened: it was ok\n * something bad happened: <stack trace>\n * with this peer: 12D3Foo\n * with this base58btc: zQmfoo\n * with this base32: bafyfoo\n * ```\n *\n * ## What's in a name?\n *\n * Great Birnam Wood is referenced in Shakespeare's [Scottish play](https://en.wikipedia.org/wiki/The_Scottish_Play)\n * as part of the prophecy told by the three witches. The woods themselves have\n * largely been cut down since, and the trees (presumably) turned into logs.\n */\n\nimport { base32 } from 'multiformats/bases/base32'\nimport { base36 } from 'multiformats/bases/base36'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base64 } from 'multiformats/bases/base64'\nimport debug from 'weald'\nimport type { Options as LoggerOptions, Debugger } from 'weald'\n\n/**\n * Logger component for interplanetary applications\n */\nexport interface Logger {\n /**\n * Log a message\n */\n (formatter: any, ...args: any[]): void\n\n /**\n * Log an error message\n */\n error(formatter: any, ...args: any[]): void\n\n /**\n * Log a trace message\n */\n trace(formatter: any, ...args: any[]): void\n\n /**\n * `true` if this logger is enabled\n */\n enabled: boolean\n\n /**\n * Create a logger scoped below this one\n *\n * @example\n *\n * ```ts\n * import { defaultLogger } from 'birnam'\n *\n * const log = defaultLogger().forComponent('foo')\n *\n * log('hello')\n * // foo hello\n *\n * const subLog = log.newScope('bar')\n *\n * subLog('hello')\n * // foo:bar hello\n * ```\n */\n newScope(name: string): Logger\n}\n\n/**\n * Component based logger. This can be used to create loggers that are scoped to\n * individual system components or services.\n *\n * To see logs, run your app with `DEBUG` set as an env var or for browsers, in\n * `localStorage`:\n *\n * ```console\n * $ DEBUG=helia* node index.js\n * helia:my-service hello +0ms\n * ```\n */\nexport interface ComponentLogger {\n /**\n * Returns a logger for the specified component.\n *\n * @example\n *\n * ```TypeScript\n * import type { ComponentLogger, Logger } from 'birnam'\n *\n * interface MyServiceComponents {\n * logger: ComponentLogger\n * }\n *\n * class MyService {\n * private readonly log: Logger\n *\n * constructor (components) {\n * this.log = components.logger.forComponent('my-app:my-service')\n *\n * this.log('hello')\n * // logs:\n * // my-app:my-service hello +0ms\n * }\n * }\n * ```\n */\n forComponent(name: string): Logger\n}\n\nexport type { LoggerOptions }\n\n// Add a formatter for converting to a base58 string\ndebug.formatters.z = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base58btc.baseEncode(v)\n}\n\n// Add a formatter for converting to a base32 string\ndebug.formatters.b = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base32.baseEncode(v)\n}\n\n// Add a formatter for converting to a base36 string\ndebug.formatters.k = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base36.baseEncode(v)\n}\n\n// Add a formatter for converting to a base64 string\ndebug.formatters.m = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base64.baseEncode(v)\n}\n\n// Add a formatter for stringifying Errors\ndebug.formatters.e = (v?: Error): string => {\n if (v == null) {\n return 'undefined'\n }\n\n return printError(v)\n}\n\nfunction formatError (v: Error, indent = ''): string {\n const message = notEmpty(v.message)\n const stack = notEmpty(v.stack)\n\n // some browser errors (mostly from Firefox) have no message or no stack,\n // sometimes both, sometimes neither. Sometimes the message is in the stack,\n // sometimes is isn't so try to do *something* useful\n if (message != null && stack != null) {\n if (stack.includes(message)) {\n return `${stack.split('\\n').join(`\\n${indent}`)}`\n }\n\n return `${message}\\n${indent}${stack.split('\\n').join(`\\n${indent}`)}`\n }\n\n if (stack != null) {\n return `${stack.split('\\n').join(`\\n${indent}`)}`\n }\n\n if (message != null) {\n return `${message}`\n }\n\n return `${v.toString()}`\n}\n\nfunction isAggregateError (err?: any): err is AggregateError {\n return err instanceof AggregateError || (err?.name === 'AggregateError' && Array.isArray(err.errors))\n}\n\nfunction printError (err: Error, indent = ''): string {\n if (isAggregateError(err)) {\n let output = formatError(err, indent)\n\n if (err.errors.length > 0) {\n indent = `${indent} `\n\n output += `\\n${indent}${\n err.errors\n .map(err => `${printError(err, `${indent}`)}`)\n .join(`\\n${indent}`)\n }`\n } else {\n output += `\\n${indent}[Error list was empty]`\n }\n\n return output.trim()\n }\n\n return formatError(err, indent)\n}\n\nfunction createDisabledLogger (namespace: string): Debugger {\n const logger = (): void => {}\n logger.enabled = false\n logger.color = ''\n logger.diff = 0\n logger.log = (): void => {}\n logger.namespace = namespace\n logger.destroy = () => true\n logger.extend = () => logger\n logger.useColors = () => false\n\n return logger\n}\n\n/**\n * Create a component logger that will prefix any log messages with the passed\n * string.\n *\n * @example\n *\n * ```TypeScript\n * import { prefixLogger } from 'birnam'\n *\n * const logger = prefixLogger('my-node')\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-node:my-component hello world\"\n * ```\n */\nexport function prefixLogger (prefix: string, options?: LoggerOptions): ComponentLogger {\n return {\n forComponent (name: string) {\n return logger(`${prefix}:${name}`, options)\n }\n }\n}\n\n/**\n * Create a component logger\n *\n * @example\n *\n * ```TypeScript\n * import { defaultLogger } from 'birnam'\n *\n * const logger = defaultLogger()\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nexport function defaultLogger (options?: LoggerOptions): ComponentLogger {\n return {\n forComponent (name: string) {\n return logger(name, options)\n }\n }\n}\n\n/**\n * Creates a logger for the passed component name.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from 'birnam'\n *\n * const log = logger('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nexport function logger (name: string, options?: LoggerOptions): Logger {\n // trace logging is a no-op by default\n let trace = createDisabledLogger(`${name}:trace`)\n\n // look at all the debug names and see if trace logging has explicitly been enabled\n if (debug.enabled(`${name}:trace`) && debug.names.map((r: any) => r.toString()).find((n: string) => n.includes(':trace')) != null) {\n trace = debug(`${name}:trace`, options)\n }\n\n return Object.assign(debug(name, options), {\n error: debug(`${name}:error`, options),\n trace,\n newScope: (scope: string) => logger(`${name}:${scope}`, options)\n })\n}\n\nexport function disable (): void {\n debug.disable()\n}\n\nexport function enable (namespaces: string): void {\n debug.enable(namespaces)\n}\n\nexport function enabled (namespaces: string): boolean {\n return debug.enabled(namespaces)\n}\n\nfunction notEmpty (str?: string): string | undefined {\n if (str == null) {\n return\n }\n\n str = str.trim()\n\n if (str.length === 0) {\n return\n }\n\n return str\n}\n", "import type { AbortOptions } from 'abort-error'\nimport type { Blockstore, InputPair, Pair } from 'interface-blockstore'\nimport type { CID } from 'multiformats/cid'\n\nexport class BaseBlockstore implements Blockstore {\n has (key: CID, options?: AbortOptions): boolean | Promise<boolean> {\n return Promise.reject(new Error('.has is not implemented'))\n }\n\n put (key: CID, val: Uint8Array | Iterable<Uint8Array> | AsyncIterable<Uint8Array>, options?: AbortOptions): CID | Promise<CID> {\n return Promise.reject(new Error('.put is not implemented'))\n }\n\n async * putMany (source: Iterable<InputPair> | AsyncIterable<InputPair>, options?: AbortOptions): Generator<CID> | AsyncGenerator<CID> {\n for await (const { cid, bytes } of source) {\n await this.put(cid, bytes, options)\n yield cid\n }\n }\n\n get (key: CID, options?: AbortOptions): Generator<Uint8Array> | AsyncGenerator<Uint8Array> {\n throw new Error('.get is not implemented')\n }\n\n async * getMany (source: Iterable<CID> | AsyncIterable<CID>, options?: AbortOptions): Generator<Pair> | AsyncGenerator<Pair> {\n for await (const key of source) {\n yield {\n cid: key,\n bytes: this.get(key, options)\n }\n }\n }\n\n delete (key: CID, options?: AbortOptions): void | Promise<void> {\n return Promise.reject(new Error('.delete is not implemented'))\n }\n\n async * deleteMany (source: Iterable<CID> | AsyncIterable<CID>, options?: AbortOptions): Generator<CID> | AsyncGenerator<CID> {\n for await (const key of source) {\n await this.delete(key, options)\n yield key\n }\n }\n\n /**\n * Extending classes should override `query` or implement this method\n */\n async * getAll (options?: AbortOptions): Generator<Pair> | AsyncGenerator<Pair> { // eslint-disable-line require-yield\n throw new Error('.getAll is not implemented')\n }\n}\n", "export class OpenFailedError extends Error {\n static name = 'OpenFailedError'\n name = OpenFailedError.name\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n static code = 'ERR_OPEN_FAILED'\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n code = OpenFailedError.code\n\n constructor (message = 'Open failed') {\n super(message)\n }\n}\n\nexport class CloseFailedError extends Error {\n static name = 'CloseFailedError'\n name = CloseFailedError.name\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n static code = 'ERR_CLOSE_FAILED'\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n code = CloseFailedError.code\n\n constructor (message = 'Close failed') {\n super(message)\n }\n}\n\nexport class PutFailedError extends Error {\n static name = 'PutFailedError'\n name = PutFailedError.name\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n static code = 'ERR_PUT_FAILED'\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n code = PutFailedError.code\n\n constructor (message = 'Put failed') {\n super(message)\n }\n}\n\nexport class GetFailedError extends Error {\n static name = 'GetFailedError'\n name = GetFailedError.name\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n static code = 'ERR_GET_FAILED'\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n code = GetFailedError.code\n\n constructor (message = 'Get failed') {\n super(message)\n }\n}\n\nexport class DeleteFailedError extends Error {\n static name = 'DeleteFailedError'\n name = DeleteFailedError.name\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n static code = 'ERR_DELETE_FAILED'\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n code = DeleteFailedError.code\n\n constructor (message = 'Delete failed') {\n super(message)\n }\n}\n\nexport class HasFailedError extends Error {\n static name = 'HasFailedError'\n name = HasFailedError.name\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n static code = 'ERR_HAS_FAILED'\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n code = HasFailedError.code\n\n constructor (message = 'Has failed') {\n super(message)\n }\n}\n\nexport class NotFoundError extends Error {\n static name = 'NotFoundError'\n name = NotFoundError.name\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n static code = 'ERR_NOT_FOUND'\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n code = NotFoundError.code\n\n constructor (message = 'Not Found') {\n super(message)\n }\n}\n\n/**\n * @deprecated import from 'abort-error' module instead - this will be removed in a future release\n */\nexport class AbortError extends Error {\n static name = 'AbortError'\n name = AbortError.name\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n static code = 'ERR_ABORTED'\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n code = AbortError.code\n\n constructor (message = 'Aborted') {\n super(message)\n }\n}\n", "/**\n * @packageDocumentation\n *\n * For when you need a one-liner to collect iterable values.\n *\n * @example\n *\n * ```javascript\n * import all from 'it-all'\n *\n * // This can also be an iterator, etc\n * const values = function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const arr = all(values)\n *\n * console.info(arr) // 0, 1, 2, 3, 4\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const arr = await all(values())\n *\n * console.info(arr) // 0, 1, 2, 3, 4\n * ```\n */\n\nfunction isAsyncIterable <T> (thing: any): thing is AsyncIterable<T> {\n return thing[Symbol.asyncIterator] != null\n}\n\n/**\n * Collects all values from an (async) iterable and returns them as an array\n */\nfunction all <T> (source: Iterable<T>): T[]\nfunction all <T> (source: Iterable<T> | AsyncIterable<T>): Promise<T[]>\nfunction all <T> (source: Iterable<T> | AsyncIterable<T>): Promise<T[]> | T[] {\n if (isAsyncIterable(source)) {\n return (async () => {\n const arr = []\n\n for await (const entry of source) {\n arr.push(entry)\n }\n\n return arr\n })()\n }\n\n const arr = []\n\n for (const entry of source) {\n arr.push(entry)\n }\n\n return arr\n}\n\nexport default all\n", "import { NotFoundError } from 'interface-store'\nimport all from 'it-all'\nimport { base32 } from 'multiformats/bases/base32'\nimport { CID } from 'multiformats/cid'\nimport * as raw from 'multiformats/codecs/raw'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { BaseBlockstore } from './base.ts'\nimport type { AbortOptions } from 'abort-error'\nimport type { Pair } from 'interface-blockstore'\n\nfunction isPromise <T> (p?: any): p is Promise<T> {\n return typeof p?.then === 'function'\n}\n\nexport class MemoryBlockstore extends BaseBlockstore {\n private readonly data: Map<string, Uint8Array[]>\n\n constructor () {\n super()\n\n this.data = new Map()\n }\n\n put (key: CID, val: Uint8Array | Iterable<Uint8Array> | AsyncIterable<Uint8Array>, options?: AbortOptions): CID | Promise<CID> {\n options?.signal?.throwIfAborted()\n\n let buf: Uint8Array[]\n\n if (val instanceof Uint8Array) {\n buf = [val]\n } else {\n const result = all(val)\n\n if (isPromise<Uint8Array[]>(result)) {\n return result.then(val => {\n return this._put(key, val, options)\n })\n } else {\n buf = result\n }\n }\n\n return this._put(key, buf, options)\n }\n\n private _put (key: CID, val: Uint8Array[], options?: AbortOptions): CID | Promise<CID> {\n options?.signal?.throwIfAborted()\n\n this.data.set(base32.encode(key.multihash.bytes), val)\n\n return key\n }\n\n * get (key: CID, options?: AbortOptions): Generator<Uint8Array> | AsyncGenerator<Uint8Array> {\n options?.signal?.throwIfAborted()\n const buf = this.data.get(base32.encode(key.multihash.bytes))\n\n if (buf == null) {\n throw new NotFoundError()\n }\n\n yield * buf\n }\n\n has (key: CID, options?: AbortOptions): boolean | Promise<boolean> {\n options?.signal?.throwIfAborted()\n return this.data.has(base32.encode(key.multihash.bytes))\n }\n\n async delete (key: CID, options?: AbortOptions): Promise<void> {\n options?.signal?.throwIfAborted()\n this.data.delete(base32.encode(key.multihash.bytes))\n }\n\n * getAll (options?: AbortOptions): Generator<Pair> | AsyncGenerator<Pair> {\n options?.signal?.throwIfAborted()\n\n for (const [key, value] of this.data.entries()) {\n yield {\n cid: CID.createV1(raw.code, Digest.decode(base32.decode(key))),\n bytes: (async function * () {\n yield * value\n })()\n }\n options?.signal?.throwIfAborted()\n }\n }\n}\n", "/**\n * @packageDocumentation\n *\n * A logger for libp2p based on [weald](https://www.npmjs.com/package/weald), a TypeScript port of the venerable [debug](https://www.npmjs.com/package/debug) module.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('libp2p:my:component:name')\n *\n * try {\n * // an operation\n * log('something happened: %s', 'it was ok')\n * } catch (err) {\n * log.error('something bad happened: %e', err)\n * }\n *\n * log('with this peer: %p', {})\n * log('and this base58btc: %b', Uint8Array.from([0, 1, 2, 3]))\n * log('and this base32: %t', Uint8Array.from([4, 5, 6, 7]))\n * ```\n *\n * ```console\n * $ DEBUG=libp2p:* node index.js\n * something happened: it was ok\n * something bad happened: <stack trace>\n * with this peer: 12D3Foo\n * with this base58btc: Qmfoo\n * with this base32: bafyfoo\n * ```\n */\n\nimport { base32 } from 'multiformats/bases/base32'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base64 } from 'multiformats/bases/base64'\nimport debug from 'weald'\nimport { truncatePeerId } from './utils.ts'\nimport type { PeerId, Logger, ComponentLogger } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Key } from 'interface-datastore'\nimport type { CID } from 'multiformats/cid'\nimport type { Debugger, Options as LoggerOptions } from 'weald'\n\nexport type { LoggerOptions }\n\n// Add a formatter for converting to a base58 string\ndebug.formatters.b = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base58btc.baseEncode(v)\n}\n\n// Add a formatter for converting to a base32 string\ndebug.formatters.t = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base32.baseEncode(v)\n}\n\n// Add a formatter for converting to a base64 string\ndebug.formatters.m = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base64.baseEncode(v)\n}\n\n// Add a formatter for stringifying peer ids\ndebug.formatters.p = (v?: PeerId): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying CIDs\ndebug.formatters.c = (v?: CID): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Datastore keys\ndebug.formatters.k = (v: Key): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Multiaddrs\ndebug.formatters.a = (v?: Multiaddr): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\nfunction formatError (v: Error, indent = ''): string {\n const message = notEmpty(v.message)\n const stack = notEmpty(v.stack)\n\n // some browser errors (mostly from Firefox) have no message or no stack,\n // sometimes both, sometimes neither. Sometimes the message is in the stack,\n // sometimes is isn't so try to do *something* useful\n if (message != null && stack != null) {\n if (stack.includes(message)) {\n return `${stack.split('\\n').join(`\\n${indent}`)}`\n }\n\n return `${message}\\n${indent}${stack.split('\\n').join(`\\n${indent}`)}`\n }\n\n if (stack != null) {\n return `${stack.split('\\n').join(`\\n${indent}`)}`\n }\n\n if (message != null) {\n return `${message}`\n }\n\n return `${v.toString()}`\n}\n\nfunction isAggregateError (err?: any): err is AggregateError {\n return err instanceof AggregateError || (err?.name === 'AggregateError' && Array.isArray(err.errors))\n}\n\nfunction printError (err: Error, indent = ''): string {\n if (isAggregateError(err)) {\n let output = formatError(err, indent)\n\n if (err.errors.length > 0) {\n indent = `${indent} `\n\n output += `\\n${indent}${\n err.errors\n .map(err => `${printError(err, `${indent}`)}`)\n .join(`\\n${indent}`)\n }`\n } else {\n output += `\\n${indent}[Error list was empty]`\n }\n\n return output.trim()\n }\n\n return formatError(err, indent)\n}\n\n// Add a formatter for stringifying Errors\ndebug.formatters.e = (v?: Error): string => {\n if (v == null) {\n return 'undefined'\n }\n\n return printError(v)\n}\n\nexport type { Logger, ComponentLogger }\n\nfunction createDisabledLogger (namespace: string): Debugger {\n const logger = (): void => {}\n logger.enabled = false\n logger.color = ''\n logger.diff = 0\n logger.log = (): void => {}\n logger.namespace = namespace\n logger.destroy = () => true\n logger.extend = () => logger\n logger.useColors = () => false\n\n return logger\n}\n\nexport interface PeerLoggerOptions extends LoggerOptions {\n prefixLength?: number\n suffixLength?: number\n}\n\n/**\n * Create a component logger that will prefix any log messages with a truncated\n * peer id.\n *\n * @example\n *\n * ```TypeScript\n * import { peerLogger } from '@libp2p/logger'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const peerId = peerIdFromString('12D3FooBar')\n * const logger = peerLogger(peerId)\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"12\u2026oBar:my-component hello world\"\n * ```\n */\nexport function peerLogger (peerId: PeerId, options: PeerLoggerOptions = {}): ComponentLogger {\n return prefixLogger(truncatePeerId(peerId, options), options)\n}\n\n/**\n * Create a component logger that will prefix any log messages with the passed\n * string.\n *\n * @example\n *\n * ```TypeScript\n * import { prefixLogger } from '@libp2p/logger'\n *\n * const logger = prefixLogger('my-node')\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-node:my-component hello world\"\n * ```\n */\nexport function prefixLogger (prefix: string, options?: LoggerOptions): ComponentLogger {\n return {\n forComponent (name: string) {\n return logger(`${prefix}:${name}`, options)\n }\n }\n}\n\n/**\n * Create a component logger\n *\n * @example\n *\n * ```TypeScript\n * import { defaultLogger } from '@libp2p/logger'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const logger = defaultLogger()\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nexport function defaultLogger (options?: LoggerOptions): ComponentLogger {\n return {\n forComponent (name: string) {\n return logger(name, options)\n }\n }\n}\n\n/**\n * Creates a logger for the passed component name.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nexport function logger (name: string, options?: LoggerOptions): Logger {\n // trace logging is a no-op by default\n let trace: Debugger = createDisabledLogger(`${name}:trace`)\n\n // look at all the debug names and see if trace logging has explicitly been enabled\n if (debug.enabled(`${name}:trace`) && debug.names.map((r: any) => r.toString()).find((n: string) => n.includes(':trace')) != null) {\n trace = debug(`${name}:trace`, options)\n }\n\n return Object.assign(debug(name, options), {\n error: debug(`${name}:error`, options),\n trace,\n newScope: (scope: string) => logger(`${name}:${scope}`, options)\n })\n}\n\nexport function disable (): void {\n debug.disable()\n}\n\nexport function enable (namespaces: string): void {\n debug.enable(namespaces)\n}\n\nexport function enabled (namespaces: string): boolean {\n return debug.enabled(namespaces)\n}\n\nfunction notEmpty (str?: string): string | undefined {\n if (str == null) {\n return\n }\n\n str = str.trim()\n\n if (str.length === 0) {\n return\n }\n\n return str\n}\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 * Filter values out of an (async)iterable\n *\n * @example\n *\n * ```javascript\n * import all from 'it-all'\n * import filter from 'it-filter'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const fn = (val, index) => val > 2 // Return boolean to keep item\n *\n * const arr = all(filter(values, fn))\n *\n * console.info(arr) // 3, 4\n * ```\n *\n * Async sources and filter functions must be awaited:\n *\n * ```javascript\n * import all from 'it-all'\n * import filter from 'it-filter'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const fn = async val => (val, index) > 2 // Return boolean or promise of boolean to keep item\n *\n * const arr = await all(filter(values, fn))\n *\n * console.info(arr) // 3, 4\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 * Filters the passed (async) iterable by using the filter function\n */\nfunction filter <T> (source: Iterable<T>, fn: (val: T, index: number) => Promise<boolean>): AsyncGenerator<T, void, undefined>\nfunction filter <T> (source: Iterable<T>, fn: (val: T, index: number) => boolean): Generator<T, void, undefined>\nfunction filter <T> (source: Iterable<T> | AsyncIterable<T>, fn: (val: T, index: number) => boolean | Promise<boolean>): AsyncGenerator<T, void, undefined>\nfunction filter <T> (source: Iterable<T> | AsyncIterable<T>, fn: (val: T, index: number) => boolean | Promise<boolean>): Generator<T, void, undefined> | AsyncGenerator<T, void, undefined> {\n let index = 0\n\n if (isAsyncIterable(source)) {\n return (async function * () {\n for await (const entry of source) {\n if (await fn(entry, index++)) {\n yield entry\n }\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 = fn(value, index++)\n\n // @ts-expect-error .then is not present on O\n if (typeof res.then === 'function') {\n return (async function * () {\n if (await res) {\n yield value\n }\n\n for (const entry of peekable) {\n if (await fn(entry, index++)) {\n yield entry\n }\n }\n })()\n }\n\n const func = fn as (val: T, index: number) => boolean\n\n return (function * () {\n if (res === true) {\n yield value\n }\n\n for (const entry of peekable) {\n if (func(entry, index++)) {\n yield entry\n }\n }\n })()\n}\n\nexport default filter\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", "/**\n * @packageDocumentation\n *\n * Pass a promise and an abort signal and await the result.\n *\n * @example Basic usage\n *\n * ```ts\n * import { raceSignal } from 'race-signal'\n *\n * const controller = new AbortController()\n *\n * const promise = new Promise((resolve, reject) => {\n * setTimeout(() => {\n * resolve('a value')\n * }, 1000)\n * })\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * // throws an AbortError\n * const resolve = await raceSignal(promise, controller.signal)\n * ```\n *\n * @example Overriding errors\n *\n * By default the thrown error is the `.reason` property of the signal but it's\n * possible to override this behaviour with the `translateError` option:\n *\n * ```ts\n * import { raceSignal } from 'race-signal'\n *\n * const controller = new AbortController()\n *\n * const promise = new Promise((resolve, reject) => {\n * setTimeout(() => {\n * resolve('a value')\n * }, 1000)\n * })\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * // throws `Error('Oh no!')`\n * const resolve = await raceSignal(promise, controller.signal, {\n * translateError: (signal) => {\n * // use `signal`, or don't\n * return new Error('Oh no!')\n * }\n * })\n * ```\n */\n\nexport interface RaceSignalOptions {\n /**\n * By default the rejection reason will be taken from the `.reason` field of\n * the aborted signal.\n *\n * Passing a function here allows overriding the default error.\n */\n translateError?(signal: AbortSignal): Error\n}\n\nfunction defaultTranslate (signal: AbortSignal): Error {\n return signal.reason\n}\n\n/**\n * Race a promise against an abort signal\n */\nexport async function raceSignal <T> (promise: Promise<T>, signal?: AbortSignal, opts?: RaceSignalOptions): Promise<T> {\n if (signal == null) {\n return promise\n }\n\n const translateError = opts?.translateError ?? defaultTranslate\n\n if (signal.aborted) {\n // the passed promise may yet resolve or reject but the use has signalled\n // they are no longer interested so smother the error\n promise.catch(() => {})\n return Promise.reject(translateError(signal))\n }\n\n let listener\n\n try {\n return await Promise.race([\n promise,\n new Promise<T>((resolve, reject) => {\n listener = () => {\n reject(translateError(signal))\n }\n signal.addEventListener('abort', listener)\n })\n ])\n } finally {\n if (listener != null) {\n signal.removeEventListener('abort', listener)\n }\n }\n}\n", "/**\n * @packageDocumentation\n *\n * A pushable async generator that waits until the current value is consumed\n * before allowing a new value to be pushed.\n *\n * Useful for when you don't want to keep memory usage under control and/or\n * allow a downstream consumer to dictate how fast data flows through a pipe,\n * but you want to be able to apply a transform to that data.\n *\n * @example\n *\n * ```typescript\n * import { queuelessPushable } from 'it-queueless-pushable'\n *\n * const pushable = queuelessPushable<string>()\n *\n * // run asynchronously\n * Promise.resolve().then(async () => {\n * // push a value - the returned promise will not resolve until the value is\n * // read from the pushable\n * await pushable.push('hello')\n * })\n *\n * // read a value\n * const result = await pushable.next()\n * console.info(result) // { done: false, value: 'hello' }\n * ```\n */\n\nimport deferred from 'p-defer'\nimport { raceSignal } from 'race-signal'\nimport type { AbortOptions } from 'abort-error'\nimport type { RaceSignalOptions } from 'race-signal'\n\nexport interface Pushable<T> extends AsyncGenerator<T, void, unknown> {\n /**\n * End the iterable after all values in the buffer (if any) have been yielded. If an\n * error is passed the buffer is cleared immediately and the next iteration will\n * throw the passed error\n */\n end(err?: Error, options?: AbortOptions & RaceSignalOptions): Promise<void>\n\n /**\n * Push a value into the iterable. Values are yielded from the iterable in the order\n * they are pushed. Values not yet consumed from the iterable are buffered.\n */\n push(value: T, options?: AbortOptions & RaceSignalOptions): Promise<void>\n}\n\nclass QueuelessPushable <T> implements Pushable<T> {\n private readNext: PromiseWithResolvers<void>\n private haveNext: PromiseWithResolvers<void>\n private ended: boolean\n private nextResult: IteratorResult<T> | undefined\n private error?: Error\n\n constructor () {\n this.ended = false\n\n this.readNext = deferred()\n this.haveNext = deferred()\n }\n\n [Symbol.asyncIterator] (): AsyncGenerator<T, void, unknown> {\n return this\n }\n\n async next (): Promise<IteratorResult<T, void>> {\n if (this.nextResult == null) {\n // wait for the supplier to push a value\n await this.haveNext.promise\n }\n\n if (this.nextResult == null) {\n throw new Error('HaveNext promise resolved but nextResult was undefined')\n }\n\n const nextResult = this.nextResult\n this.nextResult = undefined\n\n // signal to the supplier that we read the value\n this.readNext.resolve()\n this.readNext = deferred()\n\n return nextResult\n }\n\n async throw (err?: Error): Promise<IteratorReturnResult<undefined>> {\n this.ended = true\n this.error = err\n\n if (err != null) {\n // this can cause unhandled promise rejections if nothing is awaiting the\n // next value so attach a dummy catch listener to the promise\n this.haveNext.promise.catch(() => {})\n this.haveNext.reject(err)\n }\n\n const result: IteratorReturnResult<undefined> = {\n done: true,\n value: undefined\n }\n\n return result\n }\n\n async return (): Promise<IteratorResult<T>> {\n const result: IteratorReturnResult<undefined> = {\n done: true,\n value: undefined\n }\n\n this.ended = true\n this.nextResult = result\n\n // let the consumer know we have a new value\n this.haveNext.resolve()\n\n return result\n }\n\n async push (value: T, options?: AbortOptions & RaceSignalOptions): Promise<void> {\n await this._push(value, options)\n }\n\n async end (err?: Error, options?: AbortOptions & RaceSignalOptions): Promise<void> {\n if (err != null) {\n await this.throw(err)\n } else {\n // abortable return\n await this._push(undefined, options)\n }\n }\n\n private async _push (value?: T, options?: AbortOptions & RaceSignalOptions): Promise<void> {\n if (value != null && this.ended) {\n throw this.error ?? new Error('Cannot push value onto an ended pushable')\n }\n\n // wait for all values to be read\n while (this.nextResult != null) {\n await this.readNext.promise\n }\n\n if (value != null) {\n this.nextResult = { done: false, value }\n } else {\n this.ended = true\n this.nextResult = { done: true, value: undefined }\n }\n\n // let the consumer know we have a new value\n this.haveNext.resolve()\n this.haveNext = deferred()\n\n // wait for the consumer to have finished processing the value and requested\n // the next one or for the passed signal to abort the waiting\n await raceSignal(\n this.readNext.promise,\n options?.signal,\n options\n )\n }\n}\n\nexport function queuelessPushable <T> (): Pushable<T> {\n return new QueuelessPushable<T>()\n}\n", "/**\n * @packageDocumentation\n *\n * Merge several (async)iterables into one, yield values as they arrive.\n *\n * Nb. sources are iterated over in parallel so the order of emitted items is not guaranteed.\n *\n * @example\n *\n * ```javascript\n * import merge from 'it-merge'\n * import all from 'it-all'\n *\n * // This can also be an iterator, generator, etc\n * const values1 = [0, 1, 2, 3, 4]\n * const values2 = [5, 6, 7, 8, 9]\n *\n * const arr = all(merge(values1, values2))\n *\n * console.info(arr) // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import merge from 'it-merge'\n * import all from 'it-all'\n *\n * // This can also be an iterator, async iterator, generator, etc\n * const values1 = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n * const values2 = async function * () {\n * yield * [5, 6, 7, 8, 9]\n * }\n *\n * const arr = await all(merge(values1(), values2()))\n *\n * console.info(arr) // 0, 1, 5, 6, 2, 3, 4, 7, 8, 9 <- nb. order is not guaranteed\n * ```\n */\n\nimport { queuelessPushable } from 'it-queueless-pushable'\nimport type { Pushable } from 'it-queueless-pushable'\n\nfunction isAsyncIterable <T> (thing: any): thing is AsyncIterable<T> {\n return thing[Symbol.asyncIterator] != null\n}\n\nasync function addAllToPushable <T> (sources: Array<AsyncIterable<T> | Iterable<T>>, output: Pushable<T>, signal: AbortSignal): Promise<void> {\n try {\n await Promise.all(\n sources.map(async (source) => {\n for await (const item of source) {\n await output.push(item, {\n signal\n })\n signal.throwIfAborted()\n }\n })\n )\n\n await output.end(undefined, {\n signal\n })\n } catch (err: any) {\n await output.end(err, {\n signal\n })\n .catch(() => {})\n }\n}\n\nasync function * mergeSources <T> (sources: Array<AsyncIterable<T> | Iterable<T>>): AsyncGenerator<T, void, undefined> {\n const controller = new AbortController()\n const output = queuelessPushable<T>()\n\n addAllToPushable(sources, output, controller.signal)\n .catch(() => {})\n\n try {\n yield * output\n } finally {\n controller.abort()\n }\n}\n\nfunction * mergeSyncSources <T> (syncSources: Array<Iterable<T>>): Generator<T, void, undefined> {\n for (const source of syncSources) {\n yield * source\n }\n}\n\n/**\n * Treat one or more iterables as a single iterable.\n *\n * Nb. sources are iterated over in parallel so the\n * order of emitted items is not guaranteed.\n */\nfunction merge <T> (...sources: Array<Iterable<T>>): Generator<T, void, undefined>\nfunction merge <T> (...sources: Array<AsyncIterable<T> | Iterable<T>>): AsyncGenerator<T, void, undefined>\nfunction merge <T> (...sources: Array<AsyncIterable<T> | Iterable<T>>): AsyncGenerator<T, void, undefined> | Generator<T, void, undefined> {\n const syncSources: Array<Iterable<T>> = []\n\n for (const source of sources) {\n if (!isAsyncIterable(source)) {\n syncSources.push(source)\n }\n }\n\n if (syncSources.length === sources.length) {\n // all sources are synchronous\n return mergeSyncSources(syncSources)\n }\n\n return mergeSources(sources)\n}\n\nexport default merge\n", "import { logger } from '@libp2p/logger'\nimport { NotFoundError } from 'interface-store'\nimport filter from 'it-filter'\nimport merge from 'it-merge'\nimport { BaseBlockstore } from './base.ts'\nimport type { AbortOptions } from 'abort-error'\nimport type { Blockstore, InputPair, Pair } from 'interface-blockstore'\nimport type { CID } from 'multiformats/cid'\n\nconst log = logger('blockstore:core:tiered')\n\n/**\n * A blockstore that can combine multiple stores. Puts and deletes\n * will write through to all blockstores. Has and get will\n * try each store sequentially. getAll will use every store but also\n * deduplicate any yielded pairs.\n */\nexport class TieredBlockstore extends BaseBlockstore {\n private readonly stores: Blockstore[]\n\n constructor (stores: Blockstore[]) {\n super()\n\n this.stores = stores.slice()\n }\n\n async put (key: CID, value: Uint8Array | Iterable<Uint8Array> | AsyncIterable<Uint8Array>, options?: AbortOptions): Promise<CID> {\n await Promise.all(\n this.stores.map(async store => {\n await store.put(key, value, options)\n })\n )\n\n return key\n }\n\n async * get (key: CID, options?: AbortOptions): Generator<Uint8Array> | AsyncGenerator<Uint8Array> {\n let error: Error | undefined\n\n for (const store of this.stores) {\n try {\n yield * store.get(key, options)\n return\n } catch (err: any) {\n error = err\n log.error(err)\n }\n }\n\n throw error ?? new NotFoundError()\n }\n\n async has (key: CID, options?: AbortOptions): Promise<boolean> {\n for (const s of this.stores) {\n if (await s.has(key, options)) {\n return true\n }\n }\n\n return false\n }\n\n async delete (key: CID, options?: AbortOptions): Promise<void> {\n await Promise.all(\n this.stores.map(async store => {\n await store.delete(key, options)\n })\n )\n }\n\n async * putMany (source: Iterable<InputPair> | AsyncIterable<InputPair>, options: AbortOptions = {}): Generator<CID> | AsyncGenerator<CID> {\n for await (const pair of source) {\n await this.put(pair.cid, pair.bytes, options)\n yield pair.cid\n }\n }\n\n async * deleteMany (source: Iterable<CID> | AsyncIterable<CID>, options: AbortOptions = {}): Generator<CID> | AsyncGenerator<CID> {\n for await (const cid of source) {\n await this.delete(cid, options)\n yield cid\n }\n }\n\n async * getAll (options?: AbortOptions): Generator<Pair> | AsyncGenerator<Pair> {\n // deduplicate yielded pairs\n const seen = new Set<string>()\n\n yield * filter(merge(...this.stores.map(s => s.getAll(options))), (pair) => {\n const cidStr = pair.cid.toString()\n\n if (seen.has(cidStr)) {\n return false\n }\n\n seen.add(cidStr)\n\n return true\n })\n }\n}\n", "import { Key } from 'interface-datastore/key'\nimport type { Shard } from './index.ts'\nimport type { Datastore } from 'interface-datastore'\n\nexport const PREFIX = '/repo/flatfs/shard/'\nexport const SHARDING_FN = 'SHARDING'\n\nexport class ShardBase implements Shard {\n public param: number\n public name: string\n public _padding: string\n\n constructor (param: number) {\n this.param = param\n this.name = 'base'\n this._padding = ''\n }\n\n fun (s: string): string {\n return 'implement me'\n }\n\n toString (): string {\n return `${PREFIX}v1/${this.name}/${this.param}`\n }\n}\n\nexport class Prefix extends ShardBase {\n constructor (prefixLen: number) {\n super(prefixLen)\n this._padding = ''.padStart(prefixLen, '_')\n this.name = 'prefix'\n }\n\n fun (noslash: string): string {\n return (noslash + this._padding).slice(0, this.param)\n }\n}\n\nexport class Suffix extends ShardBase {\n constructor (suffixLen: number) {\n super(suffixLen)\n\n this._padding = ''.padStart(suffixLen, '_')\n this.name = 'suffix'\n }\n\n fun (noslash: string): string {\n const s = this._padding + noslash\n return s.slice(s.length - this.param)\n }\n}\n\nexport class NextToLast extends ShardBase {\n constructor (suffixLen: number) {\n super(suffixLen)\n this._padding = ''.padStart(suffixLen + 1, '_')\n this.name = 'next-to-last'\n }\n\n fun (noslash: string): string {\n const s = this._padding + noslash\n const offset = s.length - this.param - 1\n return s.slice(offset, offset + this.param)\n }\n}\n\n/**\n * Convert a given string to the matching sharding function\n */\nexport function parseShardFun (str: string): Shard {\n str = str.trim()\n\n if (str.length === 0) {\n throw new Error('empty shard string')\n }\n\n if (!str.startsWith(PREFIX)) {\n throw new Error(`invalid or no path prefix: ${str}`)\n }\n\n const parts = str.slice(PREFIX.length).split('/')\n const version = parts[0]\n\n if (version !== 'v1') {\n throw new Error(`expect 'v1' version, got '${version}'`)\n }\n\n const name = parts[1]\n\n if (parts[2] == null || parts[2] === '') {\n throw new Error('missing param')\n }\n\n const param = parseInt(parts[2], 10)\n\n switch (name) {\n case 'prefix':\n return new Prefix(param)\n case 'suffix':\n return new Suffix(param)\n case 'next-to-last':\n return new NextToLast(param)\n default:\n throw new Error(`unkown sharding function: ${name}`)\n }\n}\n\nexport const readShardFun = async (path: string | Uint8Array, store: Datastore): Promise<Shard> => {\n const key = new Key(path).child(new Key(SHARDING_FN))\n // @ts-expect-error not all stores have this\n const get = typeof store.getRaw === 'function' ? store.getRaw.bind(store) : store.get.bind(store)\n const res = await get(key)\n return parseShardFun(new TextDecoder().decode(res ?? '').trim())\n}\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 * Consumes all values from an (async)iterable and returns them sorted by the passed sort function.\n *\n * @example\n *\n * ```javascript\n * import sort from 'it-sort'\n * import all from 'it-all'\n *\n * const sorter = (a, b) => {\n * return a.localeCompare(b)\n * }\n *\n * // This can also be an iterator, generator, etc\n * const values = ['foo', 'bar']\n *\n * const arr = all(sort(values, sorter))\n *\n * console.info(arr) // 'bar', 'foo'\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import sort from 'it-sort'\n * import all from 'it-all'\n *\n * const sorter = (a, b) => {\n * return a.localeCompare(b)\n * }\n *\n * const values = async function * () {\n * yield * ['foo', 'bar']\n * }\n *\n * const arr = await all(sort(values, sorter))\n *\n * console.info(arr) // 'bar', 'foo'\n * ```\n */\n\nimport all from 'it-all'\n\nfunction isAsyncIterable <T> (thing: any): thing is AsyncIterable<T> {\n return thing[Symbol.asyncIterator] != null\n}\n\nexport interface CompareFunction<T> {\n (a: T, b: T): number\n}\n\n/**\n * Collects all values from an async iterator, sorts them\n * using the passed function and yields them\n */\nfunction sort <T> (source: Iterable<T>, sorter: CompareFunction<T>): Generator<T, void, undefined>\nfunction sort <T> (source: Iterable<T> | AsyncIterable<T>, sorter: CompareFunction<T>): AsyncGenerator<T, void, undefined>\nfunction sort <T> (source: Iterable<T> | AsyncIterable<T>, sorter: CompareFunction<T>): AsyncGenerator<T, void, undefined> | Generator<T, void, undefined> {\n if (isAsyncIterable(source)) {\n return (async function * () {\n const arr = await all(source)\n\n yield * arr.sort(sorter)\n })()\n }\n\n return (function * () {\n const arr = all(source)\n\n yield * arr.sort(sorter)\n })()\n}\n\nexport default sort\n", "/**\n * @packageDocumentation\n *\n * For when you only want a few values out of an (async)iterable.\n *\n * @example\n *\n * ```javascript\n * import take from 'it-take'\n * import all from 'it-all'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const arr = all(take(values, 2))\n *\n * console.info(arr) // 0, 1\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import take from 'it-take'\n * import all from 'it-all'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const arr = await all(take(values(), 2))\n *\n * console.info(arr) // 0, 1\n * ```\n */\n\nfunction isAsyncIterable <T> (thing: any): thing is AsyncIterable<T> {\n return thing[Symbol.asyncIterator] != null\n}\n\n/**\n * Stop iteration after n items have been received\n */\nfunction take <T> (source: Iterable<T>, limit: number): Generator<T, void, undefined>\nfunction take <T> (source: Iterable<T> | AsyncIterable<T>, limit: number): AsyncGenerator<T, void, undefined>\nfunction take <T> (source: Iterable<T> | AsyncIterable<T>, limit: number): AsyncGenerator<T, void, undefined> | Generator<T, void, undefined> {\n if (isAsyncIterable(source)) {\n return (async function * () {\n let items = 0\n\n if (limit < 1) {\n return\n }\n\n for await (const entry of source) {\n yield entry\n\n items++\n\n if (items === limit) {\n return\n }\n }\n })()\n }\n\n return (function * () {\n let items = 0\n\n if (limit < 1) {\n return\n }\n\n for (const entry of source) {\n yield entry\n\n items++\n\n if (items === limit) {\n return\n }\n }\n })()\n}\n\nexport default take\n", "import drain from 'it-drain'\nimport filter from 'it-filter'\nimport sort from 'it-sort'\nimport take from 'it-take'\nimport type { AbortOptions } from 'abort-error'\nimport type { Batch, Datastore, Key, KeyQuery, Pair, Query } from 'interface-datastore'\n\nexport class BaseDatastore implements Datastore {\n put (key: Key, val: Uint8Array, options?: AbortOptions): Key | Promise<Key> {\n return Promise.reject(new Error('.put is not implemented'))\n }\n\n get (key: Key, options?: AbortOptions): Uint8Array | Promise<Uint8Array> {\n return Promise.reject(new Error('.get is not implemented'))\n }\n\n has (key: Key, options?: AbortOptions): boolean | Promise<boolean> {\n return Promise.reject(new Error('.has is not implemented'))\n }\n\n delete (key: Key, options?: AbortOptions): void | Promise<void> {\n return Promise.reject(new Error('.delete is not implemented'))\n }\n\n async * putMany (source: Iterable<Pair> | AsyncIterable<Pair>, options: AbortOptions = {}): Generator<Key> | AsyncGenerator<Key> {\n for await (const { key, value } of source) {\n await this.put(key, value, options)\n yield key\n }\n }\n\n async * getMany (source: Iterable<Key> | AsyncIterable<Key>, options: AbortOptions = {}): Generator<Pair> | AsyncGenerator<Pair> {\n for await (const key of source) {\n yield {\n key,\n value: await this.get(key, options)\n }\n }\n }\n\n async * deleteMany (source: Iterable<Key> | AsyncIterable<Key>, options: AbortOptions = {}): Generator<Key> | AsyncGenerator<Key> {\n for await (const key of source) {\n await this.delete(key, options)\n yield key\n }\n }\n\n batch (): Batch {\n let puts: Pair[] = []\n let dels: Key[] = []\n\n return {\n put (key, value) {\n puts.push({ key, value })\n },\n\n delete (key) {\n dels.push(key)\n },\n commit: async (options) => {\n await drain(this.putMany(puts, options))\n puts = []\n await drain(this.deleteMany(dels, options))\n dels = []\n }\n }\n }\n\n /**\n * Extending classes should override `query` or implement this method\n */\n // eslint-disable-next-line require-yield\n async * _all (q: Query, options?: AbortOptions): Generator<Pair> | AsyncGenerator<Pair> {\n throw new Error('._all is not implemented')\n }\n\n /**\n * Extending classes should override `queryKeys` or implement this method\n */\n // eslint-disable-next-line require-yield\n async * _allKeys (q: KeyQuery, options?: AbortOptions): Generator<Key> | AsyncGenerator<Key> {\n throw new Error('._allKeys is not implemented')\n }\n\n query (q: Query, options?: AbortOptions): Generator<Pair> | AsyncGenerator<Pair> {\n let it = this._all(q, options)\n\n if (q.prefix != null) {\n const prefix = q.prefix\n it = filter(it, (e) => e.key.toString().startsWith(prefix))\n }\n\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it)\n }\n\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sort(it, f), it)\n }\n\n if (q.offset != null) {\n let i = 0\n const offset = q.offset\n it = filter(it, () => i++ >= offset)\n }\n\n if (q.limit != null) {\n it = take(it, q.limit)\n }\n\n return it\n }\n\n queryKeys (q: KeyQuery, options?: AbortOptions): Generator<Key> | AsyncGenerator<Key> {\n let it = this._allKeys(q, options)\n\n if (q.prefix != null) {\n const prefix = q.prefix\n it = filter(it, (key) =>\n key.toString().startsWith(prefix)\n )\n }\n\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it)\n }\n\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sort(it, f), it)\n }\n\n if (q.offset != null) {\n const offset = q.offset\n let i = 0\n it = filter(it, () => i++ >= offset)\n }\n\n if (q.limit != null) {\n it = take(it, q.limit)\n }\n\n return it\n }\n}\n", "import { Key } from 'interface-datastore/key'\nimport { NotFoundError } from 'interface-store'\nimport { BaseDatastore } from './base.ts'\nimport type { AbortOptions } from 'abort-error'\nimport type { KeyQuery, Pair, Query } from 'interface-datastore'\n\nexport class MemoryDatastore extends BaseDatastore {\n private readonly data: Map<string, Uint8Array>\n\n constructor () {\n super()\n\n this.data = new Map()\n }\n\n put (key: Key, val: Uint8Array, options?: AbortOptions): Key | Promise<Key> {\n options?.signal?.throwIfAborted()\n\n this.data.set(key.toString(), val)\n\n return key\n }\n\n get (key: Key, options?: AbortOptions): Uint8Array | Promise<Uint8Array> {\n options?.signal?.throwIfAborted()\n\n const result = this.data.get(key.toString())\n\n if (result == null) {\n throw new NotFoundError()\n }\n\n return result\n }\n\n has (key: Key, options?: AbortOptions): boolean | Promise<boolean> {\n options?.signal?.throwIfAborted()\n return this.data.has(key.toString())\n }\n\n delete (key: Key, options?: AbortOptions): void | Promise<void> {\n options?.signal?.throwIfAborted()\n this.data.delete(key.toString())\n }\n\n * _all (q: Query, options?: AbortOptions): Generator<Pair> | AsyncGenerator<Pair> {\n options?.signal?.throwIfAborted()\n for (const [key, value] of this.data.entries()) {\n yield { key: new Key(key), value }\n options?.signal?.throwIfAborted()\n }\n }\n\n * _allKeys (q: KeyQuery, options?: AbortOptions): Generator<Key> | AsyncGenerator<Key> {\n options?.signal?.throwIfAborted()\n for (const key of this.data.keys()) {\n yield new Key(key)\n options?.signal?.throwIfAborted()\n }\n }\n}\n", "// ported from https://www.npmjs.com/package/fast-fifo\n\nexport interface Next<T> {\n done?: boolean\n error?: Error\n value?: T\n}\n\nclass FixedFIFO<T> {\n public buffer: Array<Next<T> | undefined>\n private readonly mask: number\n private top: number\n private btm: number\n public next: FixedFIFO<T> | null\n\n constructor (hwm: number) {\n if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) {\n throw new Error('Max size for a FixedFIFO should be a power of two')\n }\n\n this.buffer = new Array(hwm)\n this.mask = hwm - 1\n this.top = 0\n this.btm = 0\n this.next = null\n }\n\n push (data: Next<T>): boolean {\n if (this.buffer[this.top] !== undefined) {\n return false\n }\n\n this.buffer[this.top] = data\n this.top = (this.top + 1) & this.mask\n\n return true\n }\n\n shift (): Next<T> | undefined {\n const last = this.buffer[this.btm]\n\n if (last === undefined) {\n return undefined\n }\n\n this.buffer[this.btm] = undefined\n this.btm = (this.btm + 1) & this.mask\n return last\n }\n\n isEmpty (): boolean {\n return this.buffer[this.btm] === undefined\n }\n}\n\nexport interface FIFOOptions {\n /**\n * When the queue reaches this size, it will be split into head/tail parts\n */\n splitLimit?: number\n}\n\nexport class FIFO<T> {\n public size: number\n private readonly hwm: number\n private head: FixedFIFO<T>\n private tail: FixedFIFO<T>\n\n constructor (options: FIFOOptions = {}) {\n this.hwm = options.splitLimit ?? 16\n this.head = new FixedFIFO<T>(this.hwm)\n this.tail = this.head\n this.size = 0\n }\n\n calculateSize (obj: any): number {\n if (obj?.byteLength != null) {\n return obj.byteLength\n }\n\n return 1\n }\n\n push (val: Next<T>): void {\n if (val?.value != null) {\n this.size += this.calculateSize(val.value)\n }\n\n if (!this.head.push(val)) {\n const prev = this.head\n this.head = prev.next = new FixedFIFO<T>(2 * this.head.buffer.length)\n this.head.push(val)\n }\n }\n\n shift (): Next<T> | undefined {\n let val = this.tail.shift()\n\n if (val === undefined && (this.tail.next != null)) {\n const next = this.tail.next\n this.tail.next = null\n this.tail = next\n val = this.tail.shift()\n }\n\n if (val?.value != null) {\n this.size -= this.calculateSize(val.value)\n }\n\n return val\n }\n\n isEmpty (): boolean {\n return this.head.isEmpty()\n }\n}\n", "/**\n * @packageDocumentation\n *\n * An iterable that you can push values into.\n *\n * @example\n *\n * ```js\n * import { pushable } from 'it-pushable'\n *\n * const source = pushable()\n *\n * setTimeout(() => source.push('hello'), 100)\n * setTimeout(() => source.push('world'), 200)\n * setTimeout(() => source.end(), 300)\n *\n * const start = Date.now()\n *\n * for await (const value of source) {\n * console.log(`got \"${value}\" after ${Date.now() - start}ms`)\n * }\n * console.log(`done after ${Date.now() - start}ms`)\n *\n * // Output:\n * // got \"hello\" after 105ms\n * // got \"world\" after 207ms\n * // done after 309ms\n * ```\n *\n * @example\n *\n * ```js\n * import { pushableV } from 'it-pushable'\n * import all from 'it-all'\n *\n * const source = pushableV()\n *\n * source.push(1)\n * source.push(2)\n * source.push(3)\n * source.end()\n *\n * console.info(await all(source))\n *\n * // Output:\n * // [ [1, 2, 3] ]\n * ```\n */\n\nimport deferred from 'p-defer'\nimport { FIFO } from './fifo.ts'\nimport type { Next } from './fifo.ts'\n\nexport class AbortError extends Error {\n type: string\n code: string\n\n constructor (message?: string, code?: string) {\n super(message ?? 'The operation was aborted')\n this.type = 'aborted'\n this.code = code ?? 'ABORT_ERR'\n }\n}\n\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\ninterface BasePushable<T> {\n /**\n * End the iterable after all values in the buffer (if any) have been yielded. If an\n * error is passed the buffer is cleared immediately and the next iteration will\n * throw the passed error\n */\n end(err?: Error): this\n\n /**\n * Push a value into the iterable. Values are yielded from the iterable in the order\n * they are pushed. Values not yet consumed from the iterable are buffered.\n */\n push(value: T): this\n\n /**\n * Returns a promise that resolves when the underlying queue becomes empty (e.g.\n * this.readableLength === 0).\n *\n * If an AbortSignal is passed as an option and that signal aborts, it only\n * causes the returned promise to reject - it does not end the pushable.\n */\n onEmpty(options?: AbortOptions): Promise<void>\n\n /**\n * This property contains the number of bytes (or objects) in the queue ready to be read.\n *\n * If `objectMode` is true, this is the number of objects in the queue, if false it's the\n * total number of bytes in the queue.\n */\n readableLength: number\n}\n\n/**\n * An iterable that you can push values into.\n */\nexport interface Pushable<T, R = void, N = unknown> extends AsyncGenerator<T, R, N>, BasePushable<T> {}\n\n/**\n * Similar to `pushable`, except it yields multiple buffered chunks at a time. All values yielded from the iterable will be arrays.\n */\nexport interface PushableV<T, R = void, N = unknown> extends AsyncGenerator<T[], R, N>, BasePushable<T> {}\n\nexport interface Options {\n /**\n * A boolean value that means non-`Uint8Array`s will be passed to `.push`, default: `false`\n */\n objectMode?: boolean\n\n /**\n * A function called after *all* values have been yielded from the iterator (including\n * buffered values). In the case when the iterator is ended with an error it will be\n * passed the error as a parameter.\n */\n onEnd?(err?: Error): void\n}\n\nexport interface DoneResult { done: true }\nexport interface ValueResult<T> { done: false, value: T }\nexport type NextResult<T> = ValueResult<T> | DoneResult\n\ninterface getNext<T, V = T> { (buffer: FIFO<T>): NextResult<V> }\n\nexport interface ObjectPushableOptions extends Options {\n objectMode: true\n}\n\nexport interface BytePushableOptions extends Options {\n objectMode?: false\n}\n\n/**\n * Create a new async iterable. The values yielded from calls to `.next()`\n * or when used in a `for await of`loop are \"pushed\" into the iterable.\n * Returns an async iterable object with additional methods.\n */\nexport function pushable<T extends { byteLength: number } = Uint8Array> (options?: BytePushableOptions): Pushable<T>\nexport function pushable<T> (options: ObjectPushableOptions): Pushable<T>\nexport function pushable<T> (options: Options = {}): Pushable<T> {\n const getNext = (buffer: FIFO<T>): NextResult<T> => {\n const next: Next<T> | undefined = buffer.shift()\n\n if (next == null) {\n return { done: true }\n }\n\n if (next.error != null) {\n throw next.error\n }\n\n return {\n done: next.done === true,\n // @ts-expect-error if done is false, value will be present\n value: next.value\n }\n }\n\n return _pushable<T, T, Pushable<T>>(getNext, options)\n}\n\nexport function pushableV<T extends { byteLength: number } = Uint8Array> (options?: BytePushableOptions): PushableV<T>\nexport function pushableV<T> (options: ObjectPushableOptions): PushableV<T>\nexport function pushableV<T> (options: Options = {}): PushableV<T> {\n const getNext = (buffer: FIFO<T>): NextResult<T[]> => {\n let next: Next<T> | undefined\n const values: T[] = []\n\n while (!buffer.isEmpty()) {\n next = buffer.shift()\n\n if (next == null) {\n break\n }\n\n if (next.error != null) {\n throw next.error\n }\n\n if (next.done === false) {\n // @ts-expect-error if done is false value should be pushed\n values.push(next.value)\n }\n }\n\n if (next == null) {\n return { done: true }\n }\n\n return {\n done: next.done === true,\n value: values\n }\n }\n\n return _pushable<T, T[], PushableV<T>>(getNext, options)\n}\n\nfunction _pushable<PushType, ValueType, ReturnType> (getNext: getNext<PushType, ValueType>, options?: Options): ReturnType {\n options = options ?? {}\n let onEnd = options.onEnd\n let buffer = new FIFO<PushType>()\n let pushable: any\n let onNext: ((next: Next<PushType>) => ReturnType) | null\n let ended: boolean\n let drain = deferred()\n\n const waitNext = async (): Promise<NextResult<ValueType>> => {\n try {\n if (!buffer.isEmpty()) {\n return getNext(buffer)\n }\n\n if (ended) {\n return { done: true }\n }\n\n return await new Promise<NextResult<ValueType>>((resolve, reject) => {\n onNext = (next: Next<PushType>) => {\n onNext = null\n buffer.push(next)\n\n try {\n resolve(getNext(buffer))\n } catch (err) {\n reject(err)\n }\n\n return pushable\n }\n })\n } finally {\n if (buffer.isEmpty()) {\n // settle promise in the microtask queue to give consumers a chance to\n // await after calling .push\n queueMicrotask(() => {\n drain.resolve()\n drain = deferred()\n })\n }\n }\n }\n\n const bufferNext = (next: Next<PushType>): ReturnType => {\n if (onNext != null) {\n return onNext(next)\n }\n\n buffer.push(next)\n return pushable\n }\n\n const bufferError = (err: Error): ReturnType => {\n buffer = new FIFO()\n\n if (onNext != null) {\n return onNext({ error: err })\n }\n\n buffer.push({ error: err })\n return pushable\n }\n\n const push = (value: PushType): ReturnType => {\n if (ended) {\n return pushable\n }\n\n // @ts-expect-error `byteLength` is not declared on PushType\n if (options?.objectMode !== true && value?.byteLength == null) {\n throw new Error('objectMode was not true but tried to push non-Uint8Array value')\n }\n\n return bufferNext({ done: false, value })\n }\n const end = (err?: Error): ReturnType => {\n if (ended) { return pushable }\n ended = true\n\n return (err != null) ? bufferError(err) : bufferNext({ done: true })\n }\n const _return = (): DoneResult => {\n buffer = new FIFO()\n end()\n\n return { done: true }\n }\n const _throw = (err: Error): DoneResult => {\n end(err)\n\n return { done: true }\n }\n\n pushable = {\n [Symbol.asyncIterator] () { return this },\n next: waitNext,\n return: _return,\n throw: _throw,\n push,\n end,\n get readableLength (): number {\n return buffer.size\n },\n onEmpty: async (options?: AbortOptions) => {\n const signal = options?.signal\n signal?.throwIfAborted()\n\n if (buffer.isEmpty()) {\n return\n }\n\n let cancel: Promise<void> | undefined\n let listener: (() => void) | undefined\n\n if (signal != null) {\n cancel = new Promise((resolve, reject) => {\n listener = () => {\n reject(new AbortError())\n }\n\n signal.addEventListener('abort', listener)\n })\n }\n\n try {\n await Promise.race([\n drain.promise,\n cancel\n ])\n } finally {\n if (listener != null && signal != null) {\n signal?.removeEventListener('abort', listener)\n }\n }\n }\n }\n\n if (onEnd == null) {\n return pushable\n }\n\n const _pushable = pushable\n\n pushable = {\n [Symbol.asyncIterator] () { return this },\n next () {\n return _pushable.next()\n },\n throw (err: Error) {\n _pushable.throw(err)\n\n if (onEnd != null) {\n onEnd(err)\n onEnd = undefined\n }\n\n return { done: true }\n },\n return () {\n _pushable.return()\n\n if (onEnd != null) {\n onEnd()\n onEnd = undefined\n }\n\n return { done: true }\n },\n push,\n end (err: Error) {\n _pushable.end(err)\n\n if (onEnd != null) {\n onEnd(err)\n onEnd = undefined\n }\n\n return pushable\n },\n get readableLength () {\n return _pushable.readableLength\n },\n onEmpty: (opts?: AbortOptions) => {\n return _pushable.onEmpty(opts)\n }\n }\n\n return pushable\n}\n", "import { Key } from 'interface-datastore'\nimport { OpenFailedError } from 'interface-store'\nimport { BaseDatastore } from './base.ts'\nimport { KeyTransformDatastore } from './keytransform.ts'\nimport {\n readShardFun,\n SHARDING_FN\n} from './shard.ts'\nimport type { Shard } from './index.ts'\nimport type { AbortOptions } from 'abort-error'\nimport type { Batch, KeyQuery, KeyQueryFilter, Pair, Query, QueryFilter, Datastore } from 'interface-datastore'\n\nconst shardKey = new Key(SHARDING_FN)\n\n/**\n * Backend independent abstraction of go-ds-flatfs.\n *\n * Wraps another datastore such that all values are stored\n * sharded according to the given sharding function.\n */\nexport class ShardingDatastore extends BaseDatastore {\n private readonly child: KeyTransformDatastore\n private shard: Shard\n\n constructor (store: Datastore, shard: Shard) {\n super()\n\n this.child = new KeyTransformDatastore(store, {\n convert: this._convertKey.bind(this),\n invert: this._invertKey.bind(this)\n })\n this.shard = shard\n }\n\n async open (): Promise<void> {\n this.shard = await ShardingDatastore.create(this.child, this.shard)\n }\n\n _convertKey (key: Key): Key {\n const s = key.toString()\n if (s === shardKey.toString()) {\n return key\n }\n\n const parent = new Key(this.shard.fun(s))\n return parent.child(key)\n }\n\n _invertKey (key: Key): Key {\n const s = key.toString()\n if (s === shardKey.toString()) {\n return key\n }\n return Key.withNamespaces(key.list().slice(1))\n }\n\n static async create (store: Datastore, shard?: Shard): Promise<Shard> {\n const hasShard = await store.has(shardKey)\n\n if (!hasShard) {\n if (shard == null) {\n throw new OpenFailedError('Shard is required when datastore doesn\\'t have a shard key already')\n }\n\n await store.put(shardKey, new TextEncoder().encode(shard.toString() + '\\n'))\n }\n\n if (shard == null) {\n shard = await readShardFun('/', store)\n }\n\n // test shards\n const diskShard = await readShardFun('/', store)\n const a = diskShard.toString()\n const b = shard.toString()\n\n if (a !== b) {\n throw new Error(`specified fun ${b} does not match repo shard fun ${a}`)\n }\n\n return diskShard\n }\n\n async put (key: Key, val: Uint8Array, options?: AbortOptions): Promise<Key> {\n await this.child.put(key, val, options)\n\n return key\n }\n\n async get (key: Key, options?: AbortOptions): Promise<Uint8Array> {\n return this.child.get(key, options)\n }\n\n async has (key: Key, options?: AbortOptions): Promise<boolean> {\n return this.child.has(key, options)\n }\n\n async delete (key: Key, options?: AbortOptions): Promise<void> {\n await this.child.delete(key, options)\n }\n\n async * putMany (source: Iterable<Pair> | AsyncIterable<Pair>, options: AbortOptions = {}): Generator<Key> | AsyncGenerator<Key> {\n yield * this.child.putMany(source, options)\n }\n\n async * getMany (source: Iterable<Key> | AsyncIterable<Key>, options: AbortOptions = {}): Generator<Pair> | AsyncGenerator<Pair> {\n yield * this.child.getMany(source, options)\n }\n\n async * deleteMany (source: Iterable<Key> | AsyncIterable<Key>, options: AbortOptions = {}): Generator<Key> | AsyncGenerator<Key> {\n yield * this.child.deleteMany(source, options)\n }\n\n batch (): Batch {\n return this.child.batch()\n }\n\n query (q: Query, options?: AbortOptions): Generator<Pair> | AsyncGenerator<Pair> {\n const omitShard: QueryFilter = ({ key }) => key.toString() !== shardKey.toString()\n\n const tq: Query = {\n ...q,\n filters: [\n omitShard\n ].concat(q.filters ?? [])\n }\n\n return this.child.query(tq, options)\n }\n\n queryKeys (q: KeyQuery, options?: AbortOptions): Generator<Key> | AsyncGenerator<Key> {\n const omitShard: KeyQueryFilter = (key) => key.toString() !== shardKey.toString()\n\n const tq: KeyQuery = {\n ...q,\n filters: [\n omitShard\n ].concat(q.filters ?? [])\n }\n\n return this.child.queryKeys(tq, options)\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport { NotFoundError } from 'interface-store'\nimport { BaseDatastore } from './base.ts'\nimport type { AbortOptions } from 'abort-error'\nimport type { Batch, Datastore, Key, KeyQuery, Pair, Query } from 'interface-datastore'\n\nconst log = logger('datastore:core:tiered')\n\n/**\n * A datastore that can combine multiple stores. Puts and deletes\n * will write through to all datastores. Has and get will\n * try each store sequentially. Query will always try the\n * last one first.\n *\n */\nexport class TieredDatastore extends BaseDatastore {\n private readonly stores: Datastore[]\n\n constructor (stores: Datastore[]) {\n super()\n\n this.stores = stores.slice()\n }\n\n async put (key: Key, value: Uint8Array, options?: AbortOptions): Promise<Key> {\n await Promise.all(\n this.stores.map(async store => {\n await store.put(key, value, options)\n })\n )\n\n return key\n }\n\n async get (key: Key, options?: AbortOptions): Promise<Uint8Array> {\n let error: Error | undefined\n\n for (const store of this.stores) {\n try {\n const res = await store.get(key, options)\n\n if (res != null) {\n return res\n }\n } catch (err: any) {\n error = err\n log.error(err)\n }\n }\n\n throw error ?? new NotFoundError()\n }\n\n async has (key: Key, options?: AbortOptions): Promise<boolean> {\n for (const s of this.stores) {\n if (await s.has(key, options)) {\n return true\n }\n }\n\n return false\n }\n\n async delete (key: Key, options?: AbortOptions): Promise<void> {\n await Promise.all(\n this.stores.map(async store => {\n await store.delete(key, options)\n })\n )\n }\n\n async * putMany (source: Iterable<Pair> | AsyncIterable<Pair>, options: AbortOptions = {}): Generator<Key> | AsyncGenerator<Key> {\n for await (const pair of source) {\n await this.put(pair.key, pair.value, options)\n yield pair.key\n }\n }\n\n async * deleteMany (source: Iterable<Key> | AsyncIterable<Key>, options: AbortOptions = {}): Generator<Key> | AsyncGenerator<Key> {\n for await (const key of source) {\n await this.delete(key, options)\n yield key\n }\n }\n\n batch (): Batch {\n const batches = this.stores.map(store => store.batch())\n\n return {\n put: (key, value) => {\n batches.forEach(b => { b.put(key, value) })\n },\n delete: (key) => {\n batches.forEach(b => { b.delete(key) })\n },\n commit: async (options) => {\n for (const batch of batches) {\n await batch.commit(options)\n }\n }\n }\n }\n\n query (q: Query, options?: AbortOptions): Generator<Pair> | AsyncGenerator<Pair> {\n return this.stores[this.stores.length - 1].query(q, options)\n }\n\n queryKeys (q: KeyQuery, options?: AbortOptions): Generator<Key> | AsyncGenerator<Key> {\n return this.stores[this.stores.length - 1].queryKeys(q, options)\n }\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\n// Types that reach getObjectType() - excludes types with fast-paths above:\n// primitives (typeof), Array (isArray), Uint8Array (instanceof), plain Object (constructor)\nconst objectTypeNames = [\n 'Object', // for Object.create(null) and other non-plain objects\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 'Uint8ClampedArray',\n 'Int16Array',\n 'Uint16Array',\n 'Int32Array',\n 'Uint32Array',\n 'Float32Array',\n 'Float64Array',\n 'BigInt64Array',\n 'BigUint64Array',\n 'Tagged'\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 (typeOf === 'string' || typeOf === 'number' || typeOf === 'bigint' || typeOf === 'symbol') {\n return typeOf\n }\n /* c8 ignore next 3 */\n if (typeOf === 'function') {\n return 'Function'\n }\n if (Array.isArray(value)) {\n return 'Array'\n }\n // Also catches Node.js Buffer which extends Uint8Array\n if (value instanceof Uint8Array) {\n return 'Uint8Array'\n }\n // Fast path for plain objects (most common case after primitives/arrays/bytes)\n if (value.constructor === Object) {\n return 'Object'\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 {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 * Check equality between two Type instances. Safe to use across different\n * copies of the Type class (e.g., when bundlers duplicate the module).\n * (major, name) uniquely identifies a Type; terminal is implied by these.\n * @param {Type} a\n * @param {Type} b\n * @returns {boolean}\n */\n static equals (a, b) {\n return a === b || (a.major === b.major && a.name === b.name)\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 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\n// Threshold for manual UTF-8 encoding vs native methods.\n// Node.js Buffer.from: crossover ~24 chars\n// Browser TextEncoder: crossover ~200 chars\nconst FROM_STRING_THRESHOLD_BUFFER = 24\nconst FROM_STRING_THRESHOLD_TEXTENCODER = 200\n\nexport const fromString = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {string} string\n */\n (string) => {\n return string.length >= FROM_STRING_THRESHOLD_BUFFER\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 >= FROM_STRING_THRESHOLD_TEXTENCODER ? 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 // Buffer.slice() returns a view, not a copy, so we need special handling\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 if ((c >= 0xD800) && (c <= 0xDFFF)) {\n c = 0xFFFD // Unpaired Surrogate\n }\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// 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\n/**\n * U8Bl is a buffer list that writes directly to a user-provided Uint8Array.\n * It provides the same interface as Bl but writes to a fixed destination.\n */\nexport class U8Bl {\n /**\n * @param {Uint8Array} dest\n */\n constructor (dest) {\n this.dest = dest\n /** @type {number} */\n this.cursor = 0\n // chunks is for interface compatibility with Bl - encode.js checks chunks.length\n // as a sanity check for pre-calculated sizes. For U8Bl this is always [dest].\n /** @type {Uint8Array[]} */\n this.chunks = [dest]\n }\n\n reset () {\n this.cursor = 0\n }\n\n /**\n * @param {Uint8Array|number[]} bytes\n */\n push (bytes) {\n if (this.cursor + bytes.length > this.dest.length) {\n throw new Error('write out of bounds, destination buffer is too small')\n }\n this.dest.set(bytes, this.cursor)\n this.cursor += bytes.length\n }\n\n /**\n * @param {boolean} [reset]\n * @returns {Uint8Array}\n */\n toBytes (reset = false) {\n const byts = this.dest.subarray(0, this.cursor)\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('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').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 {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeUint (writer, token) {\n return encodeUintValue(writer, 0, token.value)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {number} major\n * @param {number|bigint} uint\n */\nexport function encodeUintValue (writer, major, uint) {\n if (uint < uintBoundaries[0]) {\n const nuint = Number(uint)\n // pack into one byte, minor=0, additional=value\n writer.push([major | nuint])\n } else if (uint < uintBoundaries[1]) {\n const nuint = Number(uint)\n // pack into two byte, minor=0, additional=24\n writer.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 writer.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 writer.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 writer.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('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').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 {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeNegint (writer, token) {\n const negint = token.value\n const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))\n uint.encodeUintValue(writer, 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 } from './byte-utils.js'\n\n/**\n * @typedef {import('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').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 = data.slice(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 = Type.equals(token.type, Type.string) ? fromString(token.value) : token.value\n }\n // @ts-ignore c'mon\n return token.encodedBytes\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeBytes (writer, token) {\n const bytes = tokenBytes(token)\n uint.encodeUintValue(writer, token.type.majorEncoded, bytes.length)\n writer.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'\n\nconst textDecoder = new TextDecoder()\n\n// Threshold for ASCII fast-path vs TextDecoder. Short ASCII strings (common for\n// map keys) are faster to decode with a simple loop than TextDecoder overhead.\nconst ASCII_THRESHOLD = 32\n\n/**\n * @typedef {import('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').DecodeOptions} DecodeOptions\n */\n\n/**\n * Decode UTF-8 bytes to string. For short ASCII strings (common case for map keys),\n * a simple loop is faster than TextDecoder.\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n * @returns {string}\n */\nfunction toStr (bytes, start, end) {\n const len = end - start\n if (len < ASCII_THRESHOLD) {\n let str = ''\n for (let i = start; i < end; i++) {\n const c = bytes[i]\n if (c & 0x80) { // non-ASCII, fall back to TextDecoder\n return textDecoder.decode(bytes.subarray(start, end))\n }\n str += String.fromCharCode(c)\n }\n return str\n }\n return textDecoder.decode(bytes.subarray(start, end))\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, toStr(data, pos + prefix, pos + totLength), totLength)\n if (options.retainStringBytes === true) {\n tok.byteValue = data.slice(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('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').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 {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeArray (writer, token) {\n uint.encodeUintValue(writer, 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('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').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 {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeMap (writer, token) {\n uint.encodeUintValue(writer, 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('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').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 {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeTag (writer, token) {\n uint.encodeUintValue(writer, 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('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').DecodeOptions} DecodeOptions\n * @typedef {import('../interface.js').EncodeOptions} EncodeOptions\n */\n\nexport const MINOR_FALSE = 20\nexport const MINOR_TRUE = 21\nexport const MINOR_NULL = 22\nexport const 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 {ByteWriter} writer\n * @param {Token} token\n * @param {EncodeOptions} options\n */\nexport function encodeFloat (writer, token, options) {\n const float = token.value\n\n if (float === false) {\n writer.push([Type.float.majorEncoded | MINOR_FALSE])\n } else if (float === true) {\n writer.push([Type.float.majorEncoded | MINOR_TRUE])\n } else if (float === null) {\n writer.push([Type.float.majorEncoded | MINOR_NULL])\n } else if (float === undefined) {\n writer.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 writer.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 writer.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 writer.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 // Use valu32 for sign bit since bitwise ops on floats lose -0 sign\n dataView.setUint16(0, ((valu32 & 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.js').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, U8Bl } from './bl.js'\nimport { encodeErrPrefix } from './common.js'\nimport { quickEncodeToken } from './jump.js'\nimport { asU8A, compare, fromString } from './byte-utils.js'\n\nimport { encodeUint, encodeUintValue } 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, MINOR_FALSE, MINOR_TRUE, MINOR_NULL, MINOR_UNDEFINED } from './7float.js'\n\n/**\n * @typedef {import('../interface.js').EncodeOptions} EncodeOptions\n * @typedef {import('../interface.js').OptionalTypeEncoder} OptionalTypeEncoder\n * @typedef {import('../interface.js').Reference} Reference\n * @typedef {import('../interface.js').StrictTypeEncoder} StrictTypeEncoder\n * @typedef {import('../interface.js').TokenTypeEncoder} TokenTypeEncoder\n * @typedef {import('../interface.js').TokenOrNestedTokens} TokenOrNestedTokens\n * @typedef {import('../interface.js').ByteWriter} ByteWriter\n */\n\n/** @type {EncodeOptions} */\nconst defaultEncodeOptions = {\n float64: false,\n mapSorter,\n quickEncodeToken\n}\n\n/** @type {EncodeOptions} */\nexport const rfc8949EncodeOptions = Object.freeze({\n float64: true,\n mapSorter: rfc8949MapSorter,\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 defaultWriter = 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 maxLength = isMap ? obj.size : keys.length\n\n /** @type {undefined | [TokenOrNestedTokens, TokenOrNestedTokens][]} */\n let entries\n\n if (maxLength) {\n // Pre-allocate the array with the expected size\n entries = new Array(maxLength)\n refStack = Ref.createCheck(refStack, obj)\n const skipUndefined = !isMap && options.ignoreUndefinedProperties\n\n let i = 0\n for (const key of keys) {\n const value = isMap ? obj.get(key) : obj[key]\n if (skipUndefined && value === undefined) {\n continue\n }\n entries[i++] = [\n objectToTokens(key, options, refStack),\n objectToTokens(value, options, refStack)\n ]\n }\n\n // Truncate only if properties were skipped\n if (i < maxLength) {\n entries.length = i\n }\n }\n\n if (!entries?.length) {\n if (options.addBreakTokens === true) {\n return [simpleTokens.emptyMap, new Token(Type.break)]\n }\n return simpleTokens.emptyMap\n }\n\n sortMapEntries(entries, options)\n if (options.addBreakTokens) {\n return [new Token(Type.map, entries.length), entries, new Token(Type.break)]\n }\n return [new Token(Type.map, entries.length), entries]\n },\n\n /**\n * Encode a `Tagged` wrapper as a CBOR tag header followed by the encoded\n * form of the wrapped value. The value is recursively tokenised through\n * `objectToTokens()` so any registered `typeEncoders` apply to it.\n *\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} options\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\n Tagged (obj, _typ, options, refStack) {\n return [\n new Token(Type.tag, obj.tag),\n objectToTokens(obj.value, options, refStack)\n ]\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 * @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 * @typedef {Token & { _keyBytes?: Uint8Array }} TokenEx\n *\n * @param {(Token|Token[])[]} e1\n * @param {(Token|Token[])[]} e2\n * @returns {number}\n */\nfunction rfc8949MapSorter (e1, e2) {\n if (e1[0] instanceof Token && e2[0] instanceof Token) {\n const t1 = /** @type {TokenEx} */ (e1[0])\n const t2 = /** @type {TokenEx} */ (e2[0])\n\n if (!t1._keyBytes) {\n t1._keyBytes = encodeRfc8949(t1.value)\n }\n\n if (!t2._keyBytes) {\n t2._keyBytes = encodeRfc8949(t2.value)\n }\n\n return compare(t1._keyBytes, t2._keyBytes)\n }\n\n throw new Error('rfc8949MapSorter: complex key types are not supported yet')\n}\n\n/**\n * @param {any} data\n * @returns {Uint8Array}\n */\nfunction encodeRfc8949 (data) {\n return encodeCustom(data, cborEncoders, rfc8949EncodeOptions)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {TokenOrNestedTokens} tokens\n * @param {TokenTypeEncoder[]} encoders\n * @param {EncodeOptions} options\n */\nfunction tokensToEncoded (writer, tokens, encoders, options) {\n if (Array.isArray(tokens)) {\n for (const token of tokens) {\n tokensToEncoded(writer, token, encoders, options)\n }\n } else {\n encoders[tokens.type.major](writer, tokens, options)\n }\n}\n\n// CBOR major type prefixes, cached from Type for hot path performance\nconst MAJOR_UINT = Type.uint.majorEncoded\nconst MAJOR_NEGINT = Type.negint.majorEncoded\nconst MAJOR_BYTES = Type.bytes.majorEncoded\nconst MAJOR_STRING = Type.string.majorEncoded\nconst MAJOR_ARRAY = Type.array.majorEncoded\n\n// Simple value bytes (CBOR major type 7 + minor value)\nconst SIMPLE_FALSE = Type.float.majorEncoded | MINOR_FALSE\nconst SIMPLE_TRUE = Type.float.majorEncoded | MINOR_TRUE\nconst SIMPLE_NULL = Type.float.majorEncoded | MINOR_NULL\nconst SIMPLE_UNDEFINED = Type.float.majorEncoded | MINOR_UNDEFINED\n\nconst neg1b = BigInt(-1)\nconst pos1b = BigInt(1)\n\n/**\n * Check if direct encoding can be used for the given options.\n * Direct encoding bypasses token creation for most values.\n * @param {EncodeOptions} options\n * @returns {boolean}\n */\nfunction canDirectEncode (options) {\n // Cannot use direct encode with addBreakTokens (needs special break token handling).\n // Direct encode checks typeEncoders per-value, falling back to tokens as needed.\n // Maps fall back to token-based encoding for efficient key sorting.\n return options.addBreakTokens !== true\n}\n\n/**\n * Direct encode a value to the writer, bypassing token creation for most types.\n * Falls back to token-based encoding for custom type encoders.\n * @param {ByteWriter} writer\n * @param {any} data\n * @param {EncodeOptions} options\n * @param {Reference|undefined} refStack\n */\nfunction directEncode (writer, data, options, refStack) {\n const typ = is(data)\n\n // Check for custom encoder for THIS specific type\n const customEncoder = options.typeEncoders && options.typeEncoders[typ]\n if (customEncoder) {\n const tokens = customEncoder(data, typ, options, refStack)\n if (tokens != null) {\n // Custom encoder returned tokens, serialize immediately\n tokensToEncoded(writer, tokens, cborEncoders, options)\n return\n }\n // Custom encoder returned null, fall through to default handling\n }\n\n // Direct encode based on type\n switch (typ) {\n case 'null':\n writer.push([SIMPLE_NULL])\n return\n\n case 'undefined':\n writer.push([SIMPLE_UNDEFINED])\n return\n\n case 'boolean':\n writer.push([data ? SIMPLE_TRUE : SIMPLE_FALSE])\n return\n\n case 'number':\n if (!Number.isInteger(data) || !Number.isSafeInteger(data)) {\n // Float, use token encoder for complex float encoding\n encodeFloat(writer, new Token(Type.float, data), options)\n } else if (data >= 0) {\n encodeUintValue(writer, MAJOR_UINT, data)\n } else {\n // Negative integer\n encodeUintValue(writer, MAJOR_NEGINT, data * -1 - 1)\n }\n return\n\n case 'bigint':\n if (data >= BigInt(0)) {\n encodeUintValue(writer, MAJOR_UINT, data)\n } else {\n encodeUintValue(writer, MAJOR_NEGINT, data * neg1b - pos1b)\n }\n return\n\n case 'string': {\n const bytes = fromString(data)\n encodeUintValue(writer, MAJOR_STRING, bytes.length)\n writer.push(bytes)\n return\n }\n\n case 'Uint8Array':\n encodeUintValue(writer, MAJOR_BYTES, data.length)\n writer.push(data)\n return\n\n case 'Array':\n if (!data.length) {\n writer.push([MAJOR_ARRAY]) // Empty array: 0x80\n return\n }\n refStack = Ref.createCheck(refStack, data)\n encodeUintValue(writer, MAJOR_ARRAY, data.length)\n for (const elem of data) {\n directEncode(writer, elem, options, refStack)\n }\n return\n\n case 'Object':\n case 'Map':\n // Maps require key sorting, use token-based encoding for efficiency\n // (pre-encoding all keys for sorting is expensive)\n {\n const tokens = typeEncoders.Object(data, typ, options, refStack)\n tokensToEncoded(writer, tokens, cborEncoders, options)\n }\n return\n\n default:\n // Fall back to token-based encoding for other types (DataView, TypedArrays, etc.)\n {\n const typeEncoder = typeEncoders[typ]\n if (!typeEncoder) {\n throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)\n }\n const tokens = typeEncoder(data, typ, options, refStack)\n tokensToEncoded(writer, tokens, cborEncoders, options)\n }\n }\n}\n\n/**\n * @param {any} data\n * @param {TokenTypeEncoder[]} encoders\n * @param {EncodeOptions} options\n * @param {Uint8Array} [destination]\n * @returns {Uint8Array}\n */\nfunction encodeCustom (data, encoders, options, destination) {\n // arg ordering is different to encodeInto for backward compatibility\n const hasDest = destination instanceof Uint8Array\n let writeTo = hasDest ? new U8Bl(destination) : defaultWriter\n\n const tokens = objectToTokens(data, options)\n if (!Array.isArray(tokens) && options.quickEncodeToken) {\n const quickBytes = options.quickEncodeToken(tokens)\n if (quickBytes) {\n if (hasDest) {\n // Copy quick bytes into destination buffer\n writeTo.push(quickBytes)\n return writeTo.toBytes()\n }\n return quickBytes\n }\n const encoder = encoders[tokens.type.major]\n if (encoder.encodedSize) {\n const size = encoder.encodedSize(tokens, options)\n if (!hasDest) {\n writeTo = new Bl(size)\n }\n encoder(writeTo, tokens, options)\n /* c8 ignore next 4 */\n // this would be a problem with encodedSize() functions\n if (writeTo.chunks.length !== 1) {\n throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)\n }\n return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0])\n }\n }\n writeTo.reset()\n tokensToEncoded(writeTo, tokens, encoders, options)\n return writeTo.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\n // Use direct encode path when possible\n if (canDirectEncode(options)) {\n defaultWriter.reset()\n directEncode(defaultWriter, data, options, undefined)\n return defaultWriter.toBytes(true)\n }\n\n return encodeCustom(data, cborEncoders, options)\n}\n\n/**\n * @param {any} data\n * @param {Uint8Array} destination\n * @param {EncodeOptions} [options]\n * @returns {{ written: number }}\n */\nfunction encodeInto (data, destination, options) {\n options = Object.assign({}, defaultEncodeOptions, options)\n\n // Use direct encode path when possible\n if (canDirectEncode(options)) {\n const writer = new U8Bl(destination)\n directEncode(writer, data, options, undefined)\n return { written: writer.toBytes().length }\n }\n\n const result = encodeCustom(data, cborEncoders, options, destination)\n return { written: result.length }\n}\n\nexport { objectToTokens, encode, encodeCustom, encodeInto, Ref }\n", "import { decodeErrPrefix } from './common.js'\nimport { Type } from './token.js'\nimport { jump, quick } from './jump.js'\nimport { asU8A } from './byte-utils.js'\n\n/**\n * @typedef {import('./token.js').Token} Token\n * @typedef {import('../interface.js').DecodeOptions} DecodeOptions\n * @typedef {import('../interface.js').DecodeTokenizer} DecodeTokenizer\n * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl\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 rejectDuplicateMapKeys = options.rejectDuplicateMapKeys === 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 && typeof key !== 'string') {\n throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)\n }\n if (rejectDuplicateMapKeys) {\n // @ts-ignore\n if ((useMaps && m.has(key)) || (!useMaps && Object.hasOwn(obj, key))) {\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 * Generator that yields [key, value] entries from a CBOR map token.\n * Used by tag decoders that need to preserve key types (e.g., Tag 259 Map).\n * @param {Token} token - The map token\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {Generator<[any, any], void, unknown>}\n */\nfunction * tokenToMapEntries (token, tokeniser, options) {\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 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 yield [key, value]\n }\n}\n\n/**\n * Creates a TagDecodeControl object for tag decoders.\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {TagDecodeControl}\n */\nfunction createTagDecodeControl (tokeniser, options) {\n let called = false\n\n /**\n * @type {TagDecodeControl}\n */\n const decode = function () {\n if (called) {\n throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)\n }\n called = true\n const value = tokensToObject(tokeniser, options)\n if (value === DONE) {\n throw new Error(`${decodeErrPrefix} tag content missing`)\n }\n if (value === BREAK) {\n throw new Error(`${decodeErrPrefix} got unexpected break in tag content`)\n }\n return value\n }\n\n decode.entries = function () {\n if (called) {\n throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)\n }\n called = true\n\n // Get the next token and ensure it's a map\n const token = tokeniser.next()\n if (!Type.equals(token.type, Type.map)) {\n throw new Error(`${decodeErrPrefix} entries() requires map content, got ${token.type.name}`)\n }\n\n // Collect all entries into an array (ensures full content consumption)\n const entries = []\n for (const entry of tokenToMapEntries(token, tokeniser, options)) {\n entries.push(entry)\n }\n return entries\n }\n\n // For internal tracking\n Object.defineProperty(decode, '_called', {\n get () { return called },\n enumerable: false\n })\n\n return decode\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 (Type.equals(token.type, Type.break)) {\n return BREAK\n }\n\n if (token.type.terminal) {\n return token.value\n }\n\n if (Type.equals(token.type, Type.array)) {\n return tokenToArray(token, tokeniser, options)\n }\n\n if (Type.equals(token.type, Type.map)) {\n return tokenToMap(token, tokeniser, options)\n }\n\n if (Type.equals(token.type, Type.tag)) {\n if (options.tags && typeof options.tags[token.value] === 'function') {\n const decodeControl = createTagDecodeControl(tokeniser, options)\n const result = options.tags[token.value](decodeControl)\n if (!decodeControl._called) {\n throw new Error(`${decodeErrPrefix} tag decoder must call decode() or entries()`)\n }\n return result\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 // Convert Buffer to plain Uint8Array for faster slicing in decode path\n const u8aData = asU8A(data)\n const tokeniser = options.tokenizer || new Tokeniser(u8aData, 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", "/**\n * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl\n * @typedef {(decode: TagDecodeControl) => Tagged} TaggedTagDecoder\n */\n\n/**\n * A wrapper class for representing a CBOR tag with an arbitrary nested value.\n *\n * `Tagged` is a symmetric primitive: it can be passed to `encode()` to emit\n * a CBOR tag header followed by the encoded form of `value`, and it can be\n * returned from a tag decoder (via `Tagged.decoder(tag)` or `Tagged.preserve()`)\n * to round-trip a tag through decode without losing the tag number.\n *\n * Use `Tagged` for one-off tag handling where defining a dedicated\n * `typeEncoders` entry and tag decoder pair would be heavyweight, e.g. when\n * wrapping a structure in a single application-specific tag (COSE, dCBOR\n * envelopes, etc.).\n *\n * For systematic mapping of a JS type to a tag (e.g. CID -> tag 42), prefer\n * a dedicated `typeEncoders` entry instead.\n */\nexport class Tagged {\n /**\n * @param {number} tag - CBOR tag number, a non-negative integer\n * @param {any} value - The value to be tagged; encoded recursively\n */\n constructor (tag, value) {\n if (typeof tag !== 'number' || !Number.isInteger(tag) || tag < 0) {\n throw new TypeError('Tagged: tag must be a non-negative integer')\n }\n this.tag = tag\n this.value = value\n }\n\n /**\n * Build a tag decoder for use in `decode()`'s `tags` option that returns the\n * decoded content wrapped in a `Tagged` instance, preserving the tag number\n * for the caller to inspect.\n *\n * @param {number} tag - The CBOR tag number this decoder will be registered for\n * @returns {TaggedTagDecoder}\n *\n * @example\n * import { decode, Tagged } from 'cborg'\n * const value = decode(bytes, { tags: { 16: Tagged.decoder(16) } })\n * // value instanceof Tagged; value.tag === 16\n */\n static decoder (tag) {\n return (decode) => new Tagged(tag, decode())\n }\n\n /**\n * Build a `tags` option for `decode()` that wraps each listed tag number in\n * a `Tagged` instance, preserving those tags through decode without\n * registering a dedicated decoder per tag.\n *\n * @param {...number} tagNumbers - One or more CBOR tag numbers to preserve\n * @returns {{[tagNumber: number]: TaggedTagDecoder}}\n *\n * @example\n * import { decode, Tagged } from 'cborg'\n * const value = decode(bytes, { tags: Tagged.preserve(16, 96) })\n */\n static preserve (...tagNumbers) {\n /** @type {{[tagNumber: number]: TaggedTagDecoder}} */\n const tags = {}\n for (const tag of tagNumbers) {\n tags[tag] = Tagged.decoder(tag)\n }\n return tags\n }\n}\n\n// Symbol.toStringTag so the internal `is()` type detection returns 'Tagged'\n// for instances, allowing the default Tagged typeEncoder to match.\nObject.defineProperty(Tagged.prototype, Symbol.toStringTag, {\n value: 'Tagged'\n})\n", "export class AlreadyPinnedError extends Error {\n static name = 'AlreadyPinnedError'\n name = 'AlreadyPinnedError'\n}\n\nexport class BlockPinnedError extends Error {\n static name = 'BlockPinnedError'\n name = 'BlockPinnedError'\n}\n\nexport class InvalidDatastoreVersionError extends Error {\n static name = 'InvalidDatastoreVersionError'\n name = 'InvalidDatastoreVersionError'\n}\n\nexport class InvalidConfigurationError extends Error {\n static name = 'InvalidConfigurationError'\n name = 'InvalidConfigurationError'\n}\n\nexport class GetFailedError extends AggregateError {\n static name = 'GetFailedError'\n name = 'GetFailedError'\n}\n\nexport class LoadBlockFailedError extends AggregateError {\n static name = 'LoadBlockFailedError'\n name = 'LoadBlockFailedError'\n}\n\nexport class BlockNotFoundWhileOfflineError extends Error {\n static name = 'BlockNotFoundWhileOfflineError'\n name = 'BlockNotFoundWhileOfflineError'\n}\n\nexport class DecryptionFailedError extends Error {\n static name = 'DecryptionFailedError'\n name = 'DecryptionFailedError'\n}\n", "// FNV_PRIMES and FNV_OFFSETS from\n// http://www.isthe.com/chongo/tech/comp/fnv/index.html#FNV-param\n\nconst FNV_PRIMES = {\n\t32: 16_777_619n,\n\t64: 1_099_511_628_211n,\n\t128: 309_485_009_821_345_068_724_781_371n,\n\t256: 374_144_419_156_711_147_060_143_317_175_368_453_031_918_731_002_211n,\n\t512: 35_835_915_874_844_867_368_919_076_489_095_108_449_946_327_955_754_392_558_399_825_615_420_669_938_882_575_126_094_039_892_345_713_852_759n,\n\t1024: 5_016_456_510_113_118_655_434_598_811_035_278_955_030_765_345_404_790_744_303_017_523_831_112_055_108_147_451_509_157_692_220_295_382_716_162_651_878_526_895_249_385_292_291_816_524_375_083_746_691_371_804_094_271_873_160_484_737_966_720_260_389_217_684_476_157_468_082_573n,\n};\n\nconst FNV_OFFSETS = {\n\t32: 2_166_136_261n,\n\t64: 14_695_981_039_346_656_037n,\n\t128: 144_066_263_297_769_815_596_495_629_667_062_367_629n,\n\t256: 100_029_257_958_052_580_907_070_968_620_625_704_837_092_796_014_241_193_945_225_284_501_741_471_925_557n,\n\t512: 9_659_303_129_496_669_498_009_435_400_716_310_466_090_418_745_672_637_896_108_374_329_434_462_657_994_582_932_197_716_438_449_813_051_892_206_539_805_784_495_328_239_340_083_876_191_928_701_583_869_517_785n,\n\t1024: 14_197_795_064_947_621_068_722_070_641_403_218_320_880_622_795_441_933_960_878_474_914_617_582_723_252_296_732_303_717_722_150_864_096_521_202_355_549_365_628_174_669_108_571_814_760_471_015_076_148_029_755_969_804_077_320_157_692_458_563_003_215_304_957_150_157_403_644_460_363_550_505_412_711_285_966_361_610_267_868_082_893_823_963_790_439_336_411_086_884_584_107_735_010_676_915n,\n};\n\nconst cachedEncoder = new globalThis.TextEncoder();\n\nfunction fnv1aUint8Array(uint8Array, size) {\n\tconst fnvPrime = FNV_PRIMES[size];\n\tlet hash = FNV_OFFSETS[size];\n\n\t// eslint-disable-next-line unicorn/no-for-loop -- This is a performance-sensitive loop\n\tfor (let index = 0; index < uint8Array.length; index++) {\n\t\thash ^= BigInt(uint8Array[index]);\n\t\thash = BigInt.asUintN(size, hash * fnvPrime);\n\t}\n\n\treturn hash;\n}\n\nfunction fnv1aEncodeInto(string, size, utf8Buffer) {\n\tif (utf8Buffer.length === 0) {\n\t\tthrow new Error('The `utf8Buffer` option must have a length greater than zero');\n\t}\n\n\tconst fnvPrime = FNV_PRIMES[size];\n\tlet hash = FNV_OFFSETS[size];\n\tlet remaining = string;\n\n\twhile (remaining.length > 0) {\n\t\tconst result = cachedEncoder.encodeInto(remaining, utf8Buffer);\n\t\tremaining = remaining.slice(result.read);\n\t\tfor (let index = 0; index < result.written; index++) {\n\t\t\thash ^= BigInt(utf8Buffer[index]);\n\t\t\thash = BigInt.asUintN(size, hash * fnvPrime);\n\t\t}\n\t}\n\n\treturn hash;\n}\n\nexport default function fnv1a(value, {size = 32, utf8Buffer} = {}) {\n\tif (!FNV_PRIMES[size]) {\n\t\tthrow new Error('The `size` option must be one of 32, 64, 128, 256, 512, or 1024');\n\t}\n\n\tif (typeof value === 'string') {\n\t\tif (utf8Buffer) {\n\t\t\treturn fnv1aEncodeInto(value, size, utf8Buffer);\n\t\t}\n\n\t\tvalue = cachedEncoder.encode(value);\n\t}\n\n\treturn fnv1aUint8Array(value, size);\n}\n", "import fnv1aHash from '@sindresorhus/fnv1a'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\nexport interface Hash {\n hash(input: Uint8Array, seed: number): number\n hashV(input: Uint8Array, seed: number): Uint8Array\n}\n\nexport const fnv1a: Hash = {\n hash: (input) => {\n return Number(fnv1aHash(input, {\n size: 32\n }))\n },\n hashV: (input, seed) => {\n return numberToBuffer(fnv1a.hash(input, seed))\n }\n}\n\nexport function numberToBuffer (num: bigint | number): Uint8Array {\n let hex = num.toString(16)\n\n if (hex.length % 2 === 1) {\n hex = `0${hex}`\n }\n\n return uint8ArrayFromString(hex, 'base16')\n}\n", "import { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport type { Hash } from './hashes.ts'\n\nexport const MAX_FINGERPRINT_SIZE = 64\n\nexport class Fingerprint {\n private readonly fp: Uint8Array\n private readonly h: Hash\n private readonly seed: number\n\n constructor (buf: Uint8Array, hash: Hash, seed: number, fingerprintSize: number = 2) {\n if (fingerprintSize > MAX_FINGERPRINT_SIZE) {\n throw new TypeError('Invalid Fingerprint Size')\n }\n\n const fnv = hash.hashV(buf, seed)\n const fp = uint8ArrayAlloc(fingerprintSize)\n\n for (let i = 0; i < fp.length; i++) {\n fp[i] = fnv[i]\n }\n\n if (fp.length === 0) {\n fp[0] = 7\n }\n\n this.fp = fp\n this.h = hash\n this.seed = seed\n }\n\n hash (): number {\n return this.h.hash(this.fp, this.seed)\n }\n\n equals (other?: any): boolean {\n if (!(other?.fp instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.fp, other.fp)\n }\n}\n", "export function getRandomInt (min: number, max: number): number {\n return Math.floor(Math.random() * (max - min)) + min\n}\n", "import { Fingerprint } from './fingerprint.ts'\nimport { getRandomInt } from './utils.ts'\n\nexport class Bucket {\n private readonly contents: Array<Fingerprint | null>\n\n constructor (size: number) {\n this.contents = new Array(size).fill(null)\n }\n\n has (fingerprint: Fingerprint): boolean {\n if (!(fingerprint instanceof Fingerprint)) {\n throw new TypeError('Invalid Fingerprint')\n }\n\n return this.contents.some((fp) => {\n return fingerprint.equals(fp)\n })\n }\n\n add (fingerprint: Fingerprint): boolean {\n if (!(fingerprint instanceof Fingerprint)) {\n throw new TypeError('Invalid Fingerprint')\n }\n\n for (let i = 0; i < this.contents.length; i++) {\n if (this.contents[i] == null) {\n this.contents[i] = fingerprint\n return true\n }\n }\n\n return true\n }\n\n swap (fingerprint: Fingerprint): Fingerprint | null {\n if (!(fingerprint instanceof Fingerprint)) {\n throw new TypeError('Invalid Fingerprint')\n }\n\n const i = getRandomInt(0, this.contents.length - 1)\n const current = this.contents[i]\n this.contents[i] = fingerprint\n\n return current\n }\n\n remove (fingerprint: Fingerprint): boolean {\n if (!(fingerprint instanceof Fingerprint)) {\n throw new TypeError('Invalid Fingerprint')\n }\n\n const found = this.contents.findIndex((fp) => {\n return fingerprint.equals(fp)\n })\n\n if (found > -1) {\n this.contents[found] = null\n return true\n } else {\n return false\n }\n }\n}\n", "import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { Bucket } from './bucket.ts'\nimport { Fingerprint, MAX_FINGERPRINT_SIZE } from './fingerprint.ts'\nimport { fnv1a } from './hashes.ts'\nimport { getRandomInt } from './utils.ts'\nimport type { Hash } from './hashes.ts'\nimport type { Filter } from './index.ts'\n\nconst maxCuckooCount = 500\n\nexport interface CuckooFilterInit {\n /**\n * How many items the filter is expected to contain\n */\n filterSize: number\n\n /**\n * How many items to put in each bucket\n */\n bucketSize?: number\n\n /**\n * How many bytes the fingerprint is expected to be\n */\n fingerprintSize?: number\n\n /**\n * A non-cryptographic hash implementation\n */\n hash?: Hash\n\n /**\n * A number used to seed the hash\n */\n seed?: number\n}\n\nexport class CuckooFilter implements Filter {\n private readonly bucketSize: number\n private readonly filterSize: number\n private readonly fingerprintSize: number\n private readonly buckets: Bucket[]\n public count: number\n private readonly hash: Hash\n private readonly seed: number\n\n constructor (init: CuckooFilterInit) {\n this.filterSize = init.filterSize\n this.bucketSize = init.bucketSize ?? 4\n this.fingerprintSize = init.fingerprintSize ?? 2\n this.count = 0\n this.buckets = []\n this.hash = init.hash ?? fnv1a\n this.seed = init.seed ?? getRandomInt(0, Math.pow(2, 10))\n }\n\n add (item: Uint8Array | string): boolean {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item)\n }\n\n const fingerprint = new Fingerprint(item, this.hash, this.seed, this.fingerprintSize)\n const j = this.hash.hash(item, this.seed) % this.filterSize\n const k = (j ^ fingerprint.hash()) % this.filterSize\n\n if (this.buckets[j] == null) {\n this.buckets[j] = new Bucket(this.bucketSize)\n }\n\n if (this.buckets[k] == null) {\n this.buckets[k] = new Bucket(this.bucketSize)\n }\n\n if (this.buckets[j].add(fingerprint) || this.buckets[k].add(fingerprint)) {\n this.count++\n return true\n }\n\n const rand = [j, k]\n let i = rand[getRandomInt(0, rand.length - 1)]\n\n if (this.buckets[i] == null) {\n this.buckets[i] = new Bucket(this.bucketSize)\n }\n\n for (let n = 0; n < maxCuckooCount; n++) {\n const swapped = this.buckets[i].swap(fingerprint)\n\n if (swapped == null) {\n continue\n }\n\n i = (i ^ swapped.hash()) % this.filterSize\n\n if (this.buckets[i] == null) {\n this.buckets[i] = new Bucket(this.bucketSize)\n }\n\n if (this.buckets[i].add(swapped)) {\n this.count++\n\n return true\n } else {\n continue\n }\n }\n\n return false\n }\n\n has (item: Uint8Array | string): boolean {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item)\n }\n\n const fingerprint = new Fingerprint(item, this.hash, this.seed, this.fingerprintSize)\n const j = this.hash.hash(item, this.seed) % this.filterSize\n const inJ = this.buckets[j]?.has(fingerprint) ?? false\n\n if (inJ) {\n return inJ\n }\n\n const k = (j ^ fingerprint.hash()) % this.filterSize\n\n return this.buckets[k]?.has(fingerprint) ?? false\n }\n\n remove (item: Uint8Array | string): boolean {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item)\n }\n\n const fingerprint = new Fingerprint(item, this.hash, this.seed, this.fingerprintSize)\n const j = this.hash.hash(item, this.seed) % this.filterSize\n const inJ = this.buckets[j]?.remove(fingerprint) ?? false\n\n if (inJ) {\n this.count--\n return inJ\n }\n\n const k = (j ^ fingerprint.hash()) % this.filterSize\n const inK = this.buckets[k]?.remove(fingerprint) ?? false\n\n if (inK) {\n this.count--\n }\n\n return inK\n }\n\n get reliable (): boolean {\n return Math.floor(100 * (this.count / this.filterSize)) <= 90\n }\n}\n\n// max load constants, defined in the cuckoo paper\nconst MAX_LOAD = {\n 1: 0.5,\n 2: 0.84,\n 4: 0.95,\n 8: 0.98\n}\n\nfunction calculateBucketSize (errorRate: number = 0.001): 2 | 4 | 8 {\n if (errorRate > 0.002) {\n return 2\n }\n\n if (errorRate > 0.00001) {\n return 4\n }\n\n return 8\n}\n\nexport function optimize (maxItems: number, errorRate: number = 0.001): CuckooFilterInit {\n // https://www.eecs.harvard.edu/~michaelm/postscripts/cuckoo-conext2014.pdf\n // Section 5.1 Optimal Bucket Size\n const bucketSize = calculateBucketSize(errorRate)\n const load = MAX_LOAD[bucketSize]\n\n // https://stackoverflow.com/questions/57555236/how-to-size-a-cuckoo-filter/57617208#57617208\n const filterSize = Math.round(maxItems / load)\n const fingerprintSize = Math.min(Math.ceil(Math.log2(1 / errorRate) + Math.log2(2 * bucketSize)), MAX_FINGERPRINT_SIZE)\n\n return {\n filterSize,\n bucketSize,\n fingerprintSize\n }\n}\n\nexport function createCuckooFilter (maxItems: number, errorRate: number = 0.005): Filter {\n const opts = optimize(maxItems, errorRate)\n return new CuckooFilter(opts)\n}\n", "import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { CuckooFilter, optimize } from './cuckoo-filter.ts'\nimport { fnv1a } from './hashes.ts'\nimport { getRandomInt } from './utils.ts'\nimport type { CuckooFilterInit } from './cuckoo-filter.ts'\nimport type { Hash } from './hashes.ts'\nimport type { Filter } from './index.ts'\n\nexport interface ScalableCuckooFilterInit extends CuckooFilterInit {\n /**\n * A number to multiply maxItems by when adding new sub-filters\n */\n scale?: number\n}\n\nexport class ScalableCuckooFilter implements Filter {\n private readonly filterSize: number\n private readonly bucketSize: number\n private readonly fingerprintSize: number\n private readonly scale: number\n private readonly filterSeries: CuckooFilter[]\n private readonly hash: Hash\n private readonly seed: number\n\n constructor (init: ScalableCuckooFilterInit) {\n this.bucketSize = init.bucketSize ?? 4\n this.filterSize = init.filterSize ?? (1 << 18) / this.bucketSize\n this.fingerprintSize = init.fingerprintSize ?? 2\n this.scale = init.scale ?? 2\n this.hash = init.hash ?? fnv1a\n this.seed = init.seed ?? getRandomInt(0, Math.pow(2, 10))\n this.filterSeries = [\n new CuckooFilter({\n filterSize: this.filterSize,\n bucketSize: this.bucketSize,\n fingerprintSize: this.fingerprintSize,\n hash: this.hash,\n seed: this.seed\n })\n ]\n }\n\n add (item: Uint8Array | string): boolean {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item)\n }\n\n if (this.has(item)) {\n return true\n }\n\n let current = this.filterSeries.find((cuckoo) => {\n return cuckoo.reliable\n })\n\n if (current == null) {\n const curSize = this.filterSize * Math.pow(this.scale, this.filterSeries.length)\n\n current = new CuckooFilter({\n filterSize: curSize,\n bucketSize: this.bucketSize,\n fingerprintSize: this.fingerprintSize,\n hash: this.hash,\n seed: this.seed\n })\n\n this.filterSeries.push(current)\n }\n\n return current.add(item)\n }\n\n has (item: Uint8Array | string): boolean {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item)\n }\n\n for (let i = 0; i < this.filterSeries.length; i++) {\n if (this.filterSeries[i].has(item)) {\n return true\n }\n }\n\n return false\n }\n\n remove (item: Uint8Array | string): boolean {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item)\n }\n\n for (let i = 0; i < this.filterSeries.length; i++) {\n if (this.filterSeries[i].remove(item)) {\n return true\n }\n }\n\n return false\n }\n\n get count (): number {\n return this.filterSeries.reduce((acc, curr) => {\n return acc + curr.count\n }, 0)\n }\n}\n\nexport function createScalableCuckooFilter (maxItems: number, errorRate: number = 0.001, options?: Pick<ScalableCuckooFilterInit, 'hash' | 'seed' | 'scale'>): Filter {\n return new ScalableCuckooFilter({\n ...optimize(maxItems, errorRate),\n ...(options ?? {})\n })\n}\n", "import pTimeout from 'p-timeout';\n\nconst normalizeEmitter = emitter => {\n\tconst addListener = emitter.addEventListener || emitter.on || emitter.addListener;\n\tconst removeListener = emitter.removeEventListener || emitter.off || emitter.removeListener;\n\n\tif (!addListener || !removeListener) {\n\t\tthrow new TypeError('Emitter is not compatible');\n\t}\n\n\treturn {\n\t\taddListener: addListener.bind(emitter),\n\t\tremoveListener: removeListener.bind(emitter),\n\t};\n};\n\nexport function pEventMultiple(emitter, event, options) {\n\tlet cancel;\n\tconst returnValue = new Promise((resolve, reject) => {\n\t\toptions = {\n\t\t\trejectionEvents: ['error'],\n\t\t\tmultiArgs: false,\n\t\t\trejectionMultiArgs: false,\n\t\t\tresolveImmediately: false,\n\t\t\t...options,\n\t\t};\n\n\t\tif (!(options.count >= 0 && (options.count === Number.POSITIVE_INFINITY || Number.isInteger(options.count)))) {\n\t\t\tthrow new TypeError('The `count` option should be at least 0 or more');\n\t\t}\n\n\t\toptions.signal?.throwIfAborted();\n\n\t\t// Allow multiple events\n\t\tconst events = [event].flat();\n\n\t\tconst items = [];\n\t\tconst {addListener, removeListener} = normalizeEmitter(emitter);\n\n\t\tconst onItem = async (...arguments_) => {\n\t\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\t\tif (options.filter) {\n\t\t\t\ttry {\n\t\t\t\t\tif (!(await options.filter(value))) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tcancel();\n\t\t\t\t\treject(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\titems.push(value);\n\n\t\t\tif (options.count === items.length) {\n\t\t\t\tcancel();\n\t\t\t\tresolve(items);\n\t\t\t}\n\t\t};\n\n\t\tconst rejectHandler = (...arguments_) => {\n\t\t\tcancel();\n\t\t\treject(options.rejectionMultiArgs ? arguments_ : arguments_[0]);\n\t\t};\n\n\t\tcancel = () => {\n\t\t\tfor (const event of events) {\n\t\t\t\tremoveListener(event, onItem);\n\t\t\t}\n\n\t\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\t\t// Only remove rejection handler if we actually registered it\n\t\t\t\tif (!events.includes(rejectionEvent)) {\n\t\t\t\t\tremoveListener(rejectionEvent, rejectHandler);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tfor (const event of events) {\n\t\t\taddListener(event, onItem);\n\t\t}\n\n\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\t// Skip registering rejection handler if we're already listening to this event\n\t\t\t// as the main event takes priority (as documented)\n\t\t\tif (!events.includes(rejectionEvent)) {\n\t\t\t\taddListener(rejectionEvent, rejectHandler);\n\t\t\t}\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\toptions.signal.addEventListener('abort', () => {\n\t\t\t\trejectHandler(options.signal.reason);\n\t\t\t}, {once: true});\n\t\t}\n\n\t\tif (options.resolveImmediately) {\n\t\t\tresolve(items);\n\t\t}\n\t});\n\n\treturnValue.cancel = cancel;\n\n\tif (typeof options.timeout === 'number') {\n\t\tconst timeout = pTimeout(returnValue, {milliseconds: options.timeout});\n\t\t// When cancelling, also clear the timeout timer\n\t\ttimeout.cancel = () => {\n\t\t\tcancel();\n\t\t\ttimeout.clear();\n\t\t};\n\n\t\treturn timeout;\n\t}\n\n\treturn returnValue;\n}\n\nexport function pEvent(emitter, event, options) {\n\tif (typeof options === 'function') {\n\t\toptions = {filter: options};\n\t}\n\n\toptions = {\n\t\t...options,\n\t\tcount: 1,\n\t\tresolveImmediately: false,\n\t};\n\n\tconst arrayPromise = pEventMultiple(emitter, event, options);\n\tconst promise = arrayPromise.then(array => array[0]); // eslint-disable-line promise/prefer-await-to-then\n\tpromise.cancel = arrayPromise.cancel;\n\n\treturn promise;\n}\n\nexport function pEventIterator(emitter, event, options) {\n\tif (typeof options === 'function') {\n\t\toptions = {filter: options};\n\t}\n\n\t// Allow multiple events\n\tconst events = [event].flat();\n\n\toptions = {\n\t\trejectionEvents: ['error'],\n\t\tresolutionEvents: [],\n\t\tlimit: Number.POSITIVE_INFINITY,\n\t\tmultiArgs: false,\n\t\trejectionMultiArgs: false,\n\t\t...options,\n\t};\n\n\tconst {limit} = options;\n\tconst isValidLimit = limit >= 0 && (limit === Number.POSITIVE_INFINITY || Number.isInteger(limit));\n\tif (!isValidLimit) {\n\t\tthrow new TypeError('The `limit` option should be a non-negative integer or Infinity');\n\t}\n\n\toptions.signal?.throwIfAborted();\n\n\tif (limit === 0) {\n\t\t// Return an empty async iterator to avoid any further cost\n\t\treturn {\n\t\t\t[Symbol.asyncIterator]() {\n\t\t\t\treturn this;\n\t\t\t},\n\t\t\tasync next() {\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: undefined,\n\t\t\t\t};\n\t\t\t},\n\t\t};\n\t}\n\n\tconst {addListener, removeListener} = normalizeEmitter(emitter);\n\n\tlet isDone = false;\n\tlet error;\n\tlet hasPendingError = false;\n\tconst nextQueue = [];\n\tconst valueQueue = [];\n\tlet eventCount = 0;\n\tlet isLimitReached = false;\n\n\tconst valueHandler = (...arguments_) => {\n\t\teventCount++;\n\t\tisLimitReached = eventCount === limit;\n\n\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\n\t\t\tresolve({done: false, value});\n\n\t\t\tif (isLimitReached) {\n\t\t\t\tcancel();\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tvalueQueue.push(value);\n\n\t\tif (isLimitReached) {\n\t\t\tcancel();\n\t\t}\n\t};\n\n\tconst cancel = () => {\n\t\tisDone = true;\n\n\t\tfor (const event of events) {\n\t\t\tremoveListener(event, valueHandler);\n\t\t}\n\n\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\tremoveListener(rejectionEvent, rejectHandler);\n\t\t}\n\n\t\tfor (const resolutionEvent of options.resolutionEvents) {\n\t\t\tremoveListener(resolutionEvent, resolveHandler);\n\t\t}\n\n\t\twhile (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\t\t\tresolve({done: true, value: undefined});\n\t\t}\n\t};\n\n\tconst rejectHandler = (...arguments_) => {\n\t\terror = options.rejectionMultiArgs ? arguments_ : arguments_[0];\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {reject} = nextQueue.shift();\n\t\t\treject(error);\n\t\t} else {\n\t\t\thasPendingError = true;\n\t\t}\n\n\t\tcancel();\n\t};\n\n\tconst resolveHandler = async (...arguments_) => {\n\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\tif (options.filter) {\n\t\t\ttry {\n\t\t\t\tif (!(await options.filter(value))) {\n\t\t\t\t\tcancel();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} catch (filterError) {\n\t\t\t\tcancel();\n\t\t\t\tif (nextQueue.length > 0) {\n\t\t\t\t\tconst {reject} = nextQueue.shift();\n\t\t\t\t\treject(filterError);\n\t\t\t\t} else {\n\t\t\t\t\t// Store error for next iterator call\n\t\t\t\t\thasPendingError = true;\n\t\t\t\t\terror = filterError;\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\t\t\tresolve({done: true, value});\n\t\t} else {\n\t\t\tvalueQueue.push(value);\n\t\t}\n\n\t\tcancel();\n\t};\n\n\tfor (const event of events) {\n\t\taddListener(event, valueHandler);\n\t}\n\n\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\taddListener(rejectionEvent, rejectHandler);\n\t}\n\n\tfor (const resolutionEvent of options.resolutionEvents) {\n\t\taddListener(resolutionEvent, resolveHandler);\n\t}\n\n\tif (options.signal) {\n\t\toptions.signal.addEventListener('abort', () => {\n\t\t\trejectHandler(options.signal.reason);\n\t\t}, {once: true});\n\t}\n\n\treturn {\n\t\t[Symbol.asyncIterator]() {\n\t\t\treturn this;\n\t\t},\n\t\tasync next() {\n\t\t\tif (valueQueue.length > 0) {\n\t\t\t\tconst value = valueQueue.shift();\n\t\t\t\treturn {\n\t\t\t\t\tdone: isDone && valueQueue.length === 0 && !isLimitReached,\n\t\t\t\t\tvalue,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (hasPendingError) {\n\t\t\t\thasPendingError = false;\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tif (isDone) {\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: undefined,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tnextQueue.push({resolve, reject});\n\t\t\t});\n\t\t},\n\t\tasync return(value) {\n\t\t\tcancel();\n\t\t\treturn {\n\t\t\t\tdone: isDone,\n\t\t\t\tvalue,\n\t\t\t};\n\t\t},\n\t};\n}\n\nexport {TimeoutError} from 'p-timeout';\n", "import type { Startable } from '@libp2p/interface'\n\nexport interface DebouncedFunction extends Startable {\n (): void\n}\n\n/**\n * Returns a function wrapper that will only call the passed function once\n *\n * Important - the passed function should not throw or reject\n */\nexport function debounce (func: () => void | Promise<void>, wait: number): DebouncedFunction {\n let timeout: ReturnType<typeof setTimeout> | undefined\n\n const output = function (): void {\n const later = function (): void {\n timeout = undefined\n void func()\n }\n\n clearTimeout(timeout)\n timeout = setTimeout(later, wait)\n }\n output.start = (): void => {}\n output.stop = (): void => {\n clearTimeout(timeout)\n }\n\n return output\n}\n", "import type { RateLimiterResult } from './rate-limiter.ts'\n\n/**\n * A rate limit was hit\n */\nexport class RateLimitError extends Error {\n remainingPoints: number\n msBeforeNext: number\n consumedPoints: number\n isFirstInDuration: boolean\n\n constructor (message = 'Rate limit exceeded', props: RateLimiterResult) {\n super(message)\n this.name = 'RateLimitError'\n this.remainingPoints = props.remainingPoints\n this.msBeforeNext = props.msBeforeNext\n this.consumedPoints = props.consumedPoints\n this.isFirstInDuration = props.isFirstInDuration\n }\n}\n\nexport class QueueFullError extends Error {\n static name = 'QueueFullError'\n\n constructor (message: string = 'The queue was full') {\n super(message)\n this.name = 'QueueFullError'\n }\n}\n\nexport class UnexpectedEOFError extends Error {\n static name = 'UnexpectedEOFError'\n name = 'UnexpectedEOFError'\n}\n\nexport class MaxEarlyStreamsError extends Error {\n static name = 'MaxEarlyStreamsError'\n name = 'MaxEarlyStreamsError'\n}\n\nexport class StreamClosedError extends Error {\n static name = 'StreamClosedError'\n name = 'StreamClosedError'\n}\n", "import { AbortError } from '@libp2p/interface'\nimport pDefer from 'p-defer'\nimport type { AbortOptions } from '@libp2p/interface'\nimport type { DeferredPromise } from 'p-defer'\nimport type { ProgressOptions, ProgressEventListener } from 'progress-events'\n\nexport class JobRecipient<JobReturnType, JobOptions extends AbortOptions & ProgressOptions = any> {\n public deferred: DeferredPromise<JobReturnType>\n public signal?: AbortSignal\n public onProgress?: ProgressEventListener\n\n constructor (options?: Partial<Pick<JobOptions, 'signal' | 'onProgress'>>) {\n this.signal = options?.signal\n this.onProgress = options?.onProgress\n this.deferred = pDefer()\n\n this.onAbort = this.onAbort.bind(this)\n this.signal?.addEventListener('abort', this.onAbort)\n }\n\n onAbort (): void {\n this.deferred.reject(this.signal?.reason ?? new AbortError())\n }\n\n cleanup (): void {\n this.signal?.removeEventListener('abort', this.onAbort)\n }\n}\n", "import { AbortError } from '@libp2p/interface'\nimport { setMaxListeners } from 'main-event'\nimport { raceSignal } from 'race-signal'\nimport { JobRecipient } from './recipient.ts'\nimport type { JobStatus } from './index.ts'\nimport type { AbortOptions } from '@libp2p/interface'\nimport type { ProgressOptions } from 'progress-events'\n\n/**\n * Returns a random string\n */\nfunction randomId (): string {\n return `${(parseInt(String(Math.random() * 1e9), 10)).toString()}${Date.now()}`\n}\n\nexport interface JobTimeline {\n created: number\n started?: number\n finished?: number\n}\n\nexport class Job <JobOptions extends AbortOptions & ProgressOptions = AbortOptions, JobReturnType = unknown> {\n public id: string\n public fn: (options: JobOptions) => Promise<JobReturnType>\n public options: JobOptions\n public recipients: Array<JobRecipient<JobReturnType>>\n public status: JobStatus\n public readonly timeline: JobTimeline\n private readonly controller: AbortController\n private dispatchingProgress: boolean\n\n constructor (fn: (options: JobOptions) => Promise<JobReturnType>, options: any) {\n this.id = randomId()\n this.status = 'queued'\n this.fn = fn\n this.options = options\n this.recipients = []\n this.timeline = {\n created: Date.now()\n }\n\n this.controller = new AbortController()\n setMaxListeners(Infinity, this.controller.signal)\n\n this.dispatchingProgress = false\n\n this.onAbort = this.onAbort.bind(this)\n }\n\n abort (err: Error): void {\n this.controller.abort(err)\n }\n\n onAbort (): void {\n const allAborted = this.recipients.reduce((acc, curr) => {\n return acc && (curr.signal?.aborted === true)\n }, true)\n\n // if all recipients have aborted the job, actually abort the job\n if (allAborted) {\n this.controller.abort(new AbortError())\n this.cleanup()\n }\n }\n\n async join (options?: Partial<Pick<JobOptions, 'signal' | 'onProgress'>>): Promise<JobReturnType> {\n const recipient = new JobRecipient<JobReturnType>(options)\n this.recipients.push(recipient)\n\n options?.signal?.addEventListener('abort', this.onAbort)\n\n return recipient.deferred.promise\n }\n\n async run (): Promise<void> {\n this.status = 'running'\n this.timeline.started = Date.now()\n\n try {\n this.controller.signal.throwIfAborted()\n\n const result = await raceSignal(this.fn({\n ...(this.options ?? {}),\n signal: this.controller.signal,\n onProgress: (evt: any): void => {\n // Recipients can transitively re-enter this dispatcher; without\n // this guard a single event recurses until the stack overflows.\n if (this.dispatchingProgress) {\n return\n }\n\n this.dispatchingProgress = true\n\n try {\n this.recipients.forEach(recipient => {\n recipient.onProgress?.(evt)\n })\n } finally {\n this.dispatchingProgress = false\n }\n }\n }), this.controller.signal)\n\n this.recipients.forEach(recipient => {\n recipient.deferred.resolve(result)\n })\n\n this.status = 'complete'\n } catch (err) {\n this.recipients.forEach(recipient => {\n recipient.deferred.reject(err)\n })\n\n this.status = 'errored'\n } finally {\n this.timeline.finished = Date.now()\n this.cleanup()\n }\n }\n\n cleanup (): void {\n this.recipients.forEach(recipient => {\n recipient.cleanup()\n recipient.signal?.removeEventListener('abort', this.onAbort)\n })\n }\n}\n", "import { AbortError } from '@libp2p/interface'\nimport { pushable } from 'it-pushable'\nimport { TypedEventEmitter } from 'main-event'\nimport { pEvent } from 'p-event'\nimport { debounce } from '../debounce.ts'\nimport { QueueFullError } from '../errors.ts'\nimport { Job } from './job.ts'\nimport type { AbortOptions, Metrics } from '@libp2p/interface'\nimport type { ProgressOptions } from 'progress-events'\n\nexport type { Job, JobTimeline } from './job.ts'\nexport type { JobRecipient } from './recipient.ts'\n\nexport interface Comparator<T> {\n (a: T, b: T): -1 | 0 | 1\n}\n\nexport interface QueueInit<JobReturnType, JobOptions extends AbortOptions = AbortOptions> {\n /**\n * Concurrency limit.\n *\n * Minimum: `1`.\n *\n * @default Infinity\n */\n concurrency?: number\n\n /**\n * If the queue size grows to larger than this number the promise returned\n * from the add function will reject\n *\n * @default Infinity\n */\n maxSize?: number\n\n /**\n * The name of the metric for the queue length\n */\n metricName?: string\n\n /**\n * An implementation of the libp2p Metrics interface\n */\n metrics?: Metrics\n\n /**\n * An optional function that will sort the queue after a job has been added\n */\n sort?: Comparator<Job<JobOptions, JobReturnType>>\n}\n\nexport type JobStatus = 'queued' | 'running' | 'errored' | 'complete'\n\nexport interface RunFunction<Options extends AbortOptions = AbortOptions, ReturnType = void> {\n (options: Options): Promise<ReturnType>\n}\n\nexport interface JobMatcher<JobOptions extends AbortOptions = AbortOptions> {\n (options?: Partial<JobOptions>): boolean\n}\n\nexport interface QueueJobSuccess<JobReturnType, JobOptions extends AbortOptions = AbortOptions> {\n job: Job<JobOptions, JobReturnType>\n result: JobReturnType\n}\n\nexport interface QueueJobFailure<JobReturnType, JobOptions extends AbortOptions = AbortOptions> {\n job: Job<JobOptions, JobReturnType>\n error: Error\n}\n\nexport interface QueueEvents<JobReturnType, JobOptions extends AbortOptions = AbortOptions> {\n /**\n * A job is about to start running\n */\n active: CustomEvent\n\n /**\n * All jobs have finished and the queue is empty\n */\n idle: CustomEvent\n\n /**\n * The queue is empty, jobs may be running\n */\n empty: CustomEvent\n\n /**\n * A job was added to the queue\n */\n add: CustomEvent\n\n /**\n * A job has finished or failed\n */\n next: CustomEvent\n\n /**\n * A job has finished successfully\n */\n completed: CustomEvent<JobReturnType>\n\n /**\n * Emitted just after `\"completed\", a job has finished successfully - this\n * event gives access to the job and it's result\n */\n success: CustomEvent<QueueJobSuccess<JobReturnType, JobOptions>>\n\n /**\n * Emitted just after `\"error\", a job has failed - this event gives access to\n * the job and the thrown error\n */\n failure: CustomEvent<QueueJobFailure<JobReturnType, JobOptions>>\n}\n\n/**\n * Heavily influence by `p-queue` with the following differences:\n *\n * 1. Items remain at the head of the queue while they are running so `queue.size` includes `queue.pending` items - this is so interested parties can join the results of a queue item while it is running\n * 2. The options for a job are stored separately to the job in order for them to be modified while they are still in the queue\n */\nexport class Queue<JobReturnType = unknown, JobOptions extends AbortOptions & ProgressOptions = AbortOptions> extends TypedEventEmitter<QueueEvents<JobReturnType, JobOptions>> {\n public concurrency: number\n public maxSize: number\n public queue: Array<Job<JobOptions, JobReturnType>>\n private pending: number\n private readonly sort?: Comparator<Job<JobOptions, JobReturnType>>\n private paused: boolean\n\n constructor (init: QueueInit<JobReturnType, JobOptions> = {}) {\n super()\n\n this.concurrency = init.concurrency ?? Number.POSITIVE_INFINITY\n this.maxSize = init.maxSize ?? Number.POSITIVE_INFINITY\n this.pending = 0\n this.paused = false\n\n if (init.metricName != null) {\n init.metrics?.registerMetricGroup(init.metricName, {\n calculate: () => {\n return {\n size: this.queue.length,\n running: this.pending,\n queued: this.queue.length - this.pending\n }\n }\n })\n }\n\n this.sort = init.sort\n this.queue = []\n\n this.emitEmpty = debounce(this.emitEmpty.bind(this), 1)\n this.emitIdle = debounce(this.emitIdle.bind(this), 1)\n }\n\n emitEmpty (): void {\n if (this.size !== 0) {\n return\n }\n\n this.safeDispatchEvent('empty')\n }\n\n emitIdle (): void {\n if (this.running !== 0) {\n return\n }\n\n this.safeDispatchEvent('idle')\n }\n\n pause (): void {\n this.paused = true\n }\n\n resume (): void {\n if (!this.paused) {\n return\n }\n\n this.paused = false\n this.tryToStartAnother()\n }\n\n private tryToStartAnother (): boolean {\n if (this.paused) {\n return false\n }\n\n if (this.size === 0) {\n this.emitEmpty()\n\n if (this.running === 0) {\n this.emitIdle()\n }\n\n return false\n }\n\n if (this.pending < this.concurrency) {\n let job: Job<JobOptions, JobReturnType> | undefined\n\n for (const j of this.queue) {\n if (j.status === 'queued') {\n job = j\n break\n }\n }\n\n if (job == null) {\n return false\n }\n\n this.safeDispatchEvent('active')\n\n this.pending++\n\n void job.run()\n .finally(() => {\n // remove the job from the queue\n for (let i = 0; i < this.queue.length; i++) {\n if (this.queue[i] === job) {\n this.queue.splice(i, 1)\n break\n }\n }\n\n this.pending--\n this.tryToStartAnother()\n this.safeDispatchEvent('next')\n })\n\n return true\n }\n\n return false\n }\n\n private enqueue (job: Job<JobOptions, JobReturnType>): void {\n this.queue.push(job)\n\n if (this.sort != null) {\n this.queue.sort(this.sort)\n }\n }\n\n /**\n * Adds a sync or async task to the queue. Always returns a promise.\n */\n async add (fn: RunFunction<JobOptions, JobReturnType>, options?: JobOptions): Promise<JobReturnType> {\n options?.signal?.throwIfAborted()\n\n if (this.size === this.maxSize) {\n throw new QueueFullError()\n }\n\n const job = new Job<JobOptions, JobReturnType>(fn, options)\n this.enqueue(job)\n this.safeDispatchEvent('add')\n\n const result = job.join(options)\n .then(result => {\n this.safeDispatchEvent('completed', { detail: result })\n this.safeDispatchEvent('success', { detail: { job, result } })\n\n return result\n })\n .catch(err => {\n if (job.status === 'queued') {\n // job was aborted before it started - remove the job from the queue\n for (let i = 0; i < this.queue.length; i++) {\n if (this.queue[i] === job) {\n this.queue.splice(i, 1)\n break\n }\n }\n }\n\n this.safeDispatchEvent('failure', { detail: { job, error: err } })\n\n throw err\n })\n\n this.tryToStartAnother()\n\n return result\n }\n\n /**\n * Clear the queue\n */\n clear (): void {\n this.queue.splice(0, this.queue.length)\n }\n\n /**\n * Abort all jobs in the queue and clear it\n */\n abort (): void {\n this.queue.forEach(job => {\n job.abort(new AbortError())\n })\n\n this.clear()\n }\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 (options?: AbortOptions): Promise<void> {\n // Instantly resolve if the queue is empty\n if (this.size === 0) {\n return\n }\n\n await pEvent(this, 'empty', options)\n }\n\n /**\n * @returns A promise that settles when the queue size is less than the given\n * limit: `queue.size < limit`.\n *\n * If you want to avoid having the queue grow beyond a certain size you can\n * `await queue.onSizeLessThan()` before adding a new item.\n *\n * Note that this only limits the number of items waiting to start. There\n * could still be up to `concurrency` jobs already running that this call does\n * not include in its calculation.\n */\n async onSizeLessThan (limit: number, options?: AbortOptions): Promise<void> {\n // Instantly resolve if the queue is empty.\n if (this.size < limit) {\n return\n }\n\n await pEvent(this, 'next', {\n ...options,\n filter: () => this.size < limit\n })\n }\n\n /**\n * The difference with `.onEmpty` is that `.onIdle` guarantees that all work\n * from the queue has finished. `.onEmpty` merely signals that the queue is\n * 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\n * promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle (options?: AbortOptions): Promise<void> {\n // Instantly resolve if none pending and if nothing else is queued\n if (this.pending === 0 && this.size === 0) {\n return\n }\n\n await pEvent(this, 'idle', options)\n }\n\n /**\n * Size of the queue including running items\n */\n get size (): number {\n return this.queue.length\n }\n\n /**\n * The number of queued items waiting to run.\n */\n get queued (): number {\n return this.queue.length - this.pending\n }\n\n /**\n * The number of items currently running.\n */\n get running (): number {\n return this.pending\n }\n\n /**\n * Returns an async generator that makes it easy to iterate over the results\n * of jobs added to the queue.\n *\n * The generator will end when the queue becomes idle, that is there are no\n * jobs running and no jobs that have yet to run.\n *\n * If you need to keep the queue open indefinitely, consider using it-pushable\n * instead.\n */\n async * toGenerator (options?: AbortOptions): AsyncGenerator<JobReturnType, void, unknown> {\n options?.signal?.throwIfAborted()\n\n const stream = pushable<JobReturnType>({\n objectMode: true\n })\n\n const cleanup = (err?: Error): void => {\n if (err != null) {\n this.abort()\n } else {\n this.clear()\n }\n\n stream.end(err)\n }\n\n const onQueueJobComplete = (evt: CustomEvent<JobReturnType>): void => {\n if (evt.detail != null) {\n stream.push(evt.detail)\n }\n }\n\n const onQueueFailure = (evt: CustomEvent<QueueJobFailure<JobReturnType, JobOptions>>): void => {\n cleanup(evt.detail.error)\n }\n\n const onQueueIdle = (): void => {\n cleanup()\n }\n\n // clear the queue and throw if the query is aborted\n const onSignalAbort = (): void => {\n cleanup(new AbortError('Queue aborted'))\n }\n\n // add listeners\n this.addEventListener('completed', onQueueJobComplete)\n this.addEventListener('failure', onQueueFailure)\n this.addEventListener('idle', onQueueIdle)\n options?.signal?.addEventListener('abort', onSignalAbort)\n\n try {\n yield * stream\n } finally {\n // remove listeners\n this.removeEventListener('completed', onQueueJobComplete)\n this.removeEventListener('failure', onQueueFailure)\n this.removeEventListener('idle', onQueueIdle)\n options?.signal?.removeEventListener('abort', onSignalAbort)\n\n // empty the queue for when the user has broken out of a loop early\n cleanup()\n }\n }\n}\n", "/**\n * @packageDocumentation\n *\n * Similar to [AbortSignal.any](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/any_static)\n * except the returned promise has a `.clear` method that removes all event\n * listeners added to passed signals preventing memory leaks.\n *\n * At the time of writing at least, `AbortSignal.any` leaks memory in Node.js\n * and Deno environments:\n *\n * - https://github.com/nodejs/node/issues/54614\n * - https://github.com/denoland/deno/issues/24842\n *\n * @example\n *\n * ```js\n * import { anySignal } from 'any-signal'\n *\n * const userController = new AbortController()\n *\n * // Abort after 1 second\n * const timeoutSignal = AbortSignal.timeout(1000)\n *\n * const combinedSignal = anySignal([userController.signal, timeoutSignal])\n * combinedSignal.addEventListener('abort', () => console.log('Abort!'))\n *\n * try {\n * // The user or the timeout can now abort the action\n * await performSomeAction({ signal: combinedSignal })\n * } finally {\n * // Clear will clean up internal event handlers\n * combinedSignal.clear()\n * }\n * ```\n */\n\nexport interface ClearableSignal extends AbortSignal {\n clear(): void\n}\n\n/**\n * Takes an array of AbortSignals and returns a single signal.\n * If any signals are aborted, the returned signal will be aborted.\n */\nexport function anySignal (signals: Array<AbortSignal | undefined | null>): ClearableSignal {\n const controller = new globalThis.AbortController()\n\n function onAbort (): void {\n const reason = signals\n .filter(s => s?.aborted === true)\n .map(s => s?.reason)\n .pop()\n\n controller.abort(reason)\n\n for (const signal of signals) {\n if (signal?.removeEventListener != null) {\n signal.removeEventListener('abort', onAbort)\n }\n }\n }\n\n for (const signal of signals) {\n if (signal?.aborted === true) {\n onAbort()\n break\n }\n\n if (signal?.addEventListener != null) {\n signal.addEventListener('abort', onAbort)\n }\n }\n\n function clear (): void {\n for (const signal of signals) {\n if (signal?.removeEventListener != null) {\n signal.removeEventListener('abort', onAbort)\n }\n }\n }\n\n const signal = controller.signal as ClearableSignal\n signal.clear = clear\n\n return signal\n}\n", "/**\n * @packageDocumentation\n *\n * Collects all `Uint8Array` values from an (async)iterable and returns them as a single `Uint8Array`.\n *\n * @example\n *\n * ```javascript\n * import toBuffer from 'it-to-buffer'\n *\n * // This can also be an iterator, generator, etc\n * const values = [Buffer.from([0, 1]), Buffer.from([2, 3])]\n *\n * const result = toBuffer(values)\n *\n * console.info(result) // Buffer[0, 1, 2, 3]\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import toBuffer from 'it-to-buffer'\n *\n * const values = async function * () {\n * yield Buffer.from([0, 1])\n * yield Buffer.from([2, 3])\n * }\n *\n * const result = await toBuffer(values())\n *\n * console.info(result) // Buffer[0, 1, 2, 3]\n * ```\n */\n\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\n\nfunction isAsyncIterable <T> (thing: any): thing is AsyncIterable<T> {\n return thing[Symbol.asyncIterator] != null\n}\n\n/**\n * Takes an (async) iterable that yields buffer-like-objects and concats them\n * into one buffer\n */\nfunction toBuffer (source: Iterable<Uint8Array>): Uint8Array<ArrayBuffer>\nfunction toBuffer (source: Iterable<Uint8Array> | AsyncIterable<Uint8Array>): Promise<Uint8Array<ArrayBuffer>>\nfunction toBuffer (source: Iterable<Uint8Array> | AsyncIterable<Uint8Array>): Promise<Uint8Array<ArrayBuffer>> | Uint8Array<ArrayBuffer> {\n if (isAsyncIterable(source)) {\n return (async () => {\n let buffer = new Uint8Array(0)\n\n for await (const buf of source) {\n buffer = uint8ArrayConcat([buffer, buf], buffer.length + buf.length)\n }\n\n return buffer\n })()\n }\n\n const bufs = []\n let length = 0\n\n for (const buf of source) {\n bufs.push(buf)\n length += buf.byteLength\n }\n\n return uint8ArrayConcat(bufs, length)\n}\n\nexport default toBuffer\n", "import { bytes as binary, CID } from './index.ts'\nimport type * as API from './interface.ts'\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", "import { Queue } from '@libp2p/utils'\nimport filter from 'it-filter'\nimport toBuffer from 'it-to-buffer'\nimport { createUnsafe } from 'multiformats/block'\nimport type {\n GraphWalker,\n GraphWalkerComponents,\n GraphWalkerInit,\n GraphNode,\n WalkOptions\n} from '@helia/interface'\nimport type { AbortOptions } from '@libp2p/interface'\nimport type { CID } from 'multiformats'\n\nexport type { GraphWalker, GraphWalkerComponents, GraphWalkerInit, GraphNode, WalkOptions }\n\n/**\n * A depth-first walker descends into child blocks before processing successor\n * sibling blocks\n */\nexport function depthFirstWalker (init?: GraphWalkerInit): (components: GraphWalkerComponents) => GraphWalker {\n return (components) => new DepthFirstGraphWalker(components, init)\n}\n\n/**\n * A breadth-first walker processes sibling blocks before child blocks\n */\nexport function breadthFirstWalker (init?: GraphWalkerInit): (components: GraphWalkerComponents) => GraphWalker {\n return (components) => new BreadthFirstGraphWalker(components, init)\n}\n\n/**\n * A natural order walker processes blocks in the order defined by the codec and\n * does not try to sort them\n */\nexport function naturalOrderWalker (init?: GraphWalkerInit): (components: GraphWalkerComponents) => GraphWalker {\n return (components) => new NaturalOrderGraphWalker(components, init)\n}\n\ninterface JobOptions extends AbortOptions {\n cid: CID\n depth: number\n path: CID[]\n}\n\nabstract class AbstractGraphWalker {\n private readonly components: GraphWalkerComponents\n\n constructor (components: GraphWalkerComponents, init: GraphWalkerInit = {}) {\n this.components = components\n }\n\n async * walk <T = any> (cid: CID, options?: WalkOptions<T>): AsyncGenerator<GraphNode<T>> {\n const queue = this.getQueue()\n const gen = filter(queue.toGenerator(options), (node) => node != null) as AsyncGenerator<GraphNode<T>>\n let finished = false\n const maxDepth = options?.depth ?? Infinity\n\n const job = async (opts: JobOptions): Promise<GraphNode<T> | undefined> => {\n const cid = opts.cid\n const bytes = await toBuffer(this.components.blockstore.get(cid, opts))\n const block = createUnsafe<T, number, number, 0 | 1>({\n cid,\n bytes,\n codec: await this.components.getCodec(cid.code)\n })\n\n if (opts.depth < maxDepth) {\n for (const [, linkedCid] of block.links()) {\n if (options?.includeChild?.(linkedCid, block) === false) {\n continue\n }\n\n queue.add(job, {\n ...opts,\n cid: linkedCid,\n depth: opts.depth + 1,\n path: [...opts.path, linkedCid]\n })\n // eslint-disable-next-line no-loop-func\n .catch(err => {\n // only throw if the generator is still yielding results, otherwise\n // it can cause unhandled promise rejections\n if (!finished) {\n gen.throw(err)\n }\n })\n }\n }\n\n return {\n block,\n depth: opts.depth,\n path: opts.path\n }\n }\n\n queue.add(job, {\n ...options,\n cid,\n depth: 0,\n path: [cid]\n })\n .catch(err => {\n // only throw if the generator is still yielding results, otherwise it\n // can cause unhandled promise rejections\n if (!finished) {\n gen.throw(err)\n }\n })\n\n try {\n yield * gen\n } finally {\n finished = true\n // abort any in-progress operations\n queue.abort()\n }\n }\n\n abstract getQueue <T> (): Queue<GraphNode<T> | undefined, JobOptions>\n}\n\nclass DepthFirstGraphWalker extends AbstractGraphWalker {\n getQueue<T>(): Queue<GraphNode<T> | undefined, JobOptions> {\n return new Queue<GraphNode<T> | undefined, JobOptions>({\n concurrency: 1,\n sort: (a, b) => {\n if (a.options.depth === b.options.depth) {\n return 0\n }\n\n if (a.options.depth < b.options.depth) {\n return 1\n }\n\n return -1\n }\n })\n }\n}\n\nclass BreadthFirstGraphWalker extends AbstractGraphWalker {\n getQueue<T>(): Queue<GraphNode<T> | undefined, JobOptions> {\n return new Queue<GraphNode<T> | undefined, JobOptions>({\n concurrency: 1,\n sort: (a, b) => {\n if (a.options.depth === b.options.depth) {\n return 0\n }\n\n if (a.options.depth < b.options.depth) {\n return -1\n }\n\n return 1\n }\n })\n }\n}\n\nexport class NaturalOrderGraphWalker extends AbstractGraphWalker {\n getQueue<T>(): Queue<GraphNode<T> | undefined, JobOptions> {\n return new Queue<GraphNode<T> | undefined, JobOptions>({\n concurrency: 1\n })\n }\n}\n", "import { InvalidParametersError } from '@libp2p/interface'\nimport * as cborg from 'cborg'\nimport { Key } from 'interface-datastore'\nimport { base36 } from 'multiformats/bases/base36'\nimport { CID } from 'multiformats/cid'\nimport { CustomProgressEvent } from 'progress-events'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { AlreadyPinnedError } from './errors.ts'\nimport { depthFirstWalker } from './graph-walker.ts'\nimport type { CodecLoader } from '@helia/interface'\nimport type { AddOptions, IsPinnedOptions, LsOptions, Pin, Pins, RmOptions } from '@helia/interface/pins'\nimport type { AbortOptions } from '@libp2p/interface'\nimport type { Blockstore } from 'interface-blockstore'\nimport type { Datastore } from 'interface-datastore'\nimport type { Version } from 'multiformats/cid'\n\ninterface DatastorePin {\n /**\n * 0 for a direct pin or an arbitrary (+ve, whole) number or Infinity\n */\n depth: number\n\n /**\n * User-specific metadata for the pin\n */\n metadata: Record<string, string | number | boolean>\n}\n\ninterface DatastorePinnedBlock {\n pinCount: number\n pinnedBy: Uint8Array[]\n}\n\n/**\n * Callback for updating a {@link DatastorePinnedBlock}'s properties when\n * calling `#updatePinnedBlock`\n *\n * The callback should return `false` to prevent any pinning modifications to\n * the block, and true in all other cases.\n */\ninterface WithPinnedBlockCallback {\n (pinnedBlock: DatastorePinnedBlock): boolean\n}\n\nconst DATASTORE_PIN_PREFIX = '/pin/'\nconst DATASTORE_BLOCK_PREFIX = '/pinned-block/'\nconst DATASTORE_ENCODING = base36\n\nfunction toDSKey (cid: CID): Key {\n if (cid.version === 0) {\n cid = cid.toV1()\n }\n\n return new Key(`${DATASTORE_PIN_PREFIX}${cid.toString(DATASTORE_ENCODING)}`)\n}\n\nexport class PinsImpl implements Pins {\n private readonly datastore: Datastore\n private readonly blockstore: Blockstore\n private readonly getCodec: CodecLoader\n\n constructor (datastore: Datastore, blockstore: Blockstore, getCodec: CodecLoader) {\n this.datastore = datastore\n this.blockstore = blockstore\n this.getCodec = getCodec\n }\n\n async * add (cid: CID<unknown, number, number, Version>, options: AddOptions = {}): AsyncGenerator<CID, void, undefined> {\n const pinKey = toDSKey(cid)\n\n if (await this.datastore.has(pinKey)) {\n throw new AlreadyPinnedError('Already pinned')\n }\n\n const depth = Math.round(options.depth ?? Infinity)\n\n if (depth < 0) {\n throw new InvalidParametersError('Depth must be greater than or equal to 0')\n }\n\n const walker = (options.walker ?? depthFirstWalker())({\n blockstore: this.blockstore,\n getCodec: this.getCodec\n })\n\n for await (const node of walker.walk(cid, { ...options, depth })) {\n const childCid = node.block.cid\n await this.#updatePinnedBlock(childCid, (pinnedBlock: DatastorePinnedBlock) => {\n // do not update pinned block if this block is already pinned by this CID\n if (pinnedBlock.pinnedBy.find(c => uint8ArrayEquals(c, cid.bytes)) != null) {\n return false\n }\n\n pinnedBlock.pinCount++\n pinnedBlock.pinnedBy.push(cid.bytes)\n return true\n }, options)\n\n yield childCid\n }\n\n const pin: DatastorePin = {\n depth,\n metadata: options.metadata ?? {}\n }\n\n await this.datastore.put(pinKey, cborg.encode(pin), options)\n }\n\n /**\n * Update the pin count for the CID\n */\n async #updatePinnedBlock (cid: CID, withPinnedBlock: WithPinnedBlockCallback, options: AddOptions): Promise<void> {\n const blockKey = new Key(`${DATASTORE_BLOCK_PREFIX}${DATASTORE_ENCODING.encode(cid.multihash.bytes)}`)\n\n let pinnedBlock: DatastorePinnedBlock = {\n pinCount: 0,\n pinnedBy: []\n }\n\n try {\n pinnedBlock = cborg.decode(await this.datastore.get(blockKey, options))\n } catch (err: any) {\n if (err.name !== 'NotFoundError') {\n throw err\n }\n }\n\n const shouldContinue = withPinnedBlock(pinnedBlock)\n\n if (!shouldContinue) {\n return\n }\n\n if (pinnedBlock.pinCount === 0) {\n if (await this.datastore.has(blockKey)) {\n await this.datastore.delete(blockKey)\n return\n }\n }\n\n await this.datastore.put(blockKey, cborg.encode(pinnedBlock), options)\n options.onProgress?.(new CustomProgressEvent<CID>('helia:pin:add', cid))\n }\n\n async * rm (cid: CID<unknown, number, number, Version>, options: RmOptions = {}): AsyncGenerator<CID, void, undefined> {\n const pinKey = toDSKey(cid)\n const buf = await this.datastore.get(pinKey, options)\n const pin = cborg.decode(buf)\n\n await this.datastore.delete(pinKey, options)\n\n const walker = (options.walker ?? depthFirstWalker())({\n blockstore: this.blockstore,\n getCodec: this.getCodec\n })\n\n for await (const node of walker.walk(cid, { ...options, depth: pin.depth })) {\n const childCid = node.block.cid\n await this.#updatePinnedBlock(childCid, (pinnedBlock): boolean => {\n pinnedBlock.pinCount--\n pinnedBlock.pinnedBy = pinnedBlock.pinnedBy.filter(c => uint8ArrayEquals(c, cid.bytes))\n return true\n }, {\n ...options,\n depth: pin.depth\n })\n\n yield childCid\n }\n }\n\n async * ls (options: LsOptions = {}): AsyncGenerator<Pin, void, undefined> {\n for await (const { key, value } of this.datastore.query({\n prefix: DATASTORE_PIN_PREFIX + (options.cid != null ? `${options.cid.toString(base36)}` : '')\n }, options)) {\n const cid = CID.parse(key.toString().substring(5), base36)\n const pin = cborg.decode(value)\n\n yield {\n cid,\n ...pin\n }\n }\n }\n\n async isPinned (cid: CID, options: IsPinnedOptions = {}): Promise<boolean> {\n const blockKey = new Key(`${DATASTORE_BLOCK_PREFIX}${DATASTORE_ENCODING.encode(cid.multihash.bytes)}`)\n\n return this.datastore.has(blockKey, options)\n }\n\n async get (cid: CID, options?: AbortOptions): Promise<Pin> {\n const pinKey = toDSKey(cid)\n const buf = await this.datastore.get(pinKey, options)\n\n return cborg.decode(buf)\n }\n\n async setMetadata (cid: CID, metadata: Record<string, string | number | boolean> | undefined, options?: AbortOptions): Promise<void> {\n const pinKey = toDSKey(cid)\n const buf = await this.datastore.get(pinKey, options)\n const pin: DatastorePin = cborg.decode(buf)\n\n pin.metadata = metadata ?? {}\n\n await this.datastore.put(pinKey, cborg.encode(pin), options)\n }\n}\n", "export class InsufficientProvidersError extends Error {\n static name = 'InsufficientProvidersError'\n\n constructor (message = 'Insufficient providers found') {\n super(message)\n this.name = 'InsufficientProvidersError'\n }\n}\n\nexport class NoRoutersAvailableError extends Error {\n static name = 'NoRoutersAvailableError'\n\n constructor (message = 'No routers available') {\n super(message)\n this.name = 'NoRoutersAvailableError'\n }\n}\n\nexport class UnknownHashAlgorithmError extends Error {\n static name = 'UnknownHashAlgorithmError'\n\n constructor (message = 'Unknown hash algorithm') {\n super(message)\n this.name = 'UnknownHashAlgorithmError'\n }\n}\n\nexport class UnknownCodecError extends Error {\n static name = 'UnknownCodecError'\n\n constructor (message = 'Unknown codec') {\n super(message)\n this.name = 'UnknownCodecError'\n }\n}\n\nexport class InvalidCodecError extends Error {\n static name = 'InvalidCodecError'\n\n constructor (message = 'Invalid codec') {\n super(message)\n this.name = 'InvalidCodecError'\n }\n}\n\nexport class UnknownCryptoError extends Error {\n static name = 'UnknownCryptoError'\n name = 'UnknownCryptoError'\n}\n", "import { NoRoutersAvailableError } from '@helia/interface'\nimport { NotFoundError, start, stop } from '@libp2p/interface'\nimport { Queue } from '@libp2p/utils'\nimport merge from 'it-merge'\nimport { CustomProgressEvent } from 'progress-events'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { GetFailedError } from './errors.ts'\nimport type { Routing as RoutingInterface, Provider, RoutingOptions, RoutingFindProvidersProgressEvents, RoutingProvideProgressEvents, RoutingPutProgressEvents, RoutingGetProgressEvents, RoutingFindPeerProgressEvents, RoutingGetClosestPeersProgressEvents, RoutingCancelReprovideProgressEvents, Router, Peer } from '@helia/interface'\nimport type { ComponentLogger, Logger, Metrics, Startable } from '@libp2p/interface'\nimport type { AbortOptions } from 'abort-error'\nimport type { CID } from 'multiformats/cid'\n\nconst DEFAULT_PROVIDER_LOOKUP_CONCURRENCY = 5\n\nexport interface RoutingInit {\n routers: Router[]\n providerLookupConcurrency?: number\n}\n\nexport interface RoutingComponents {\n logger: ComponentLogger\n metrics?: Metrics\n}\n\ninterface PeerQueueOptions extends AbortOptions {\n peer: CID\n}\n\nexport class Routing implements RoutingInterface, Startable {\n public name: string\n\n private readonly log: Logger\n private readonly routers: Router[]\n private readonly providerLookupConcurrency: number\n\n constructor (components: RoutingComponents, init: RoutingInit) {\n this.name = 'helia'\n this.log = components.logger.forComponent('helia:routing')\n this.routers = init.routers ?? []\n this.providerLookupConcurrency = init.providerLookupConcurrency ?? DEFAULT_PROVIDER_LOOKUP_CONCURRENCY\n\n this.findProviders = components.metrics?.traceFunction('helia.routing.findProviders', this.findProviders.bind(this), {\n optionsIndex: 1\n }) ?? this.findProviders\n this.provide = components.metrics?.traceFunction('helia.routing.provide', this.provide.bind(this), {\n optionsIndex: 1\n }) ?? this.provide\n this.cancelReprovide = components.metrics?.traceFunction('helia.routing.cancelReprovide', this.cancelReprovide.bind(this), {\n optionsIndex: 1\n }) ?? this.cancelReprovide\n this.put = components.metrics?.traceFunction('helia.routing.put', this.put.bind(this), {\n optionsIndex: 2\n }) ?? this.put\n this.get = components.metrics?.traceFunction('helia.routing.get', this.get.bind(this), {\n optionsIndex: 1\n }) ?? this.get\n this.findPeer = components.metrics?.traceFunction('helia.routing.findPeer', this.findPeer.bind(this), {\n optionsIndex: 1\n }) ?? this.findPeer\n this.getClosestPeers = components.metrics?.traceFunction('helia.routing.getClosestPeers', this.getClosestPeers.bind(this), {\n optionsIndex: 1\n }) ?? this.getClosestPeers\n }\n\n async start (): Promise<void> {\n await start(...this.routers)\n }\n\n async stop (): Promise<void> {\n await stop(...this.routers)\n }\n\n hasRouter (name: string): boolean {\n return this.routers.findIndex(r => r.name === name) !== -1\n }\n\n addRouter (router: Router): void {\n this.routers.push(router)\n }\n\n /**\n * Iterates over all content routers in parallel to find providers of the\n * given key\n */\n async * findProviders (key: CID, options: RoutingOptions<RoutingFindProvidersProgressEvents> = {}): AsyncIterable<Provider> {\n if (this.routers.length === 0) {\n throw new NoRoutersAvailableError('No content routers available')\n }\n\n // provider multiaddrs are only cached for a limited time, so they can come\n // back as an empty array - when this happens we have to do a FIND_PEER\n // query to get updated addresses, but we shouldn't block on this so use a\n // separate bounded queue to perform this lookup\n const queue = new Queue<Provider | null, PeerQueueOptions>({\n concurrency: this.providerLookupConcurrency\n })\n\n let foundProviders = 0\n const errors: Error[] = []\n const self = this\n let routersFinished = 0\n\n this.log('findProviders for %c start using routers %s', key, this.routers.map(r => r.toString()).join(', '))\n\n const routers = supports(this.routers, 'findProviders')\n .map(async function * (router) {\n let foundProviders = 0\n\n options?.onProgress?.(new CustomProgressEvent('helia:routing:find-providers:start', {\n routing: router.name,\n cid: key\n }))\n\n try {\n for await (const prov of router.findProviders(key, options)) {\n foundProviders++\n\n // @ts-expect-error router.name is a string, needs to be specific\n options?.onProgress?.(new CustomProgressEvent('helia:routing:find-providers:provider', {\n routing: router.name,\n cid: key,\n provider: prov\n }))\n\n yield prov\n }\n } catch (err: any) {\n errors.push(err)\n } finally {\n self.log('router %s found %d providers for %c', router, foundProviders, key)\n\n options?.onProgress?.(new CustomProgressEvent('helia:routing:find-providers:end', {\n routing: router.name,\n cid: key,\n found: foundProviders\n }))\n\n routersFinished++\n\n // if all routers have finished and there are no jobs to find updated\n // peer multiaddres running or queued, cause the generator to exit\n if (routersFinished === routers.length && queue.size === 0) {\n queue.emitIdle()\n }\n }\n })\n\n for await (const peer of merge(\n queue.toGenerator(),\n ...routers)\n ) {\n // the peer was yielded by a content router without multiaddrs and we\n // failed to load them\n if (peer == null) {\n continue\n }\n\n // have to refresh peer info for this peer to get updated multiaddrs\n if (peer.multiaddrs.length === 0) {\n // already looking this peer up\n if (queue.queue.find(job => job.options.peer.equals(peer.id)) != null) {\n continue\n }\n\n queue.add(async () => {\n try {\n const provider = await this.findPeer(peer.id, options)\n\n if (provider.multiaddrs.length === 0) {\n return null\n }\n\n return {\n ...provider,\n protocols: peer.protocols,\n routing: peer.routing\n }\n } catch (err) {\n this.log.error('could not load multiaddrs for peer %p - %e', peer.id, err)\n return null\n }\n }, {\n peer: peer.id,\n signal: options.signal\n })\n .catch(err => {\n this.log.error('could not load multiaddrs for peer %p - %e', peer.id, err)\n })\n\n continue\n }\n\n foundProviders++\n yield peer\n }\n\n this.log('findProviders finished, found %d providers for %c', foundProviders, key)\n }\n\n /**\n * Iterates over all content routers in parallel to notify it is\n * a provider of the given key\n */\n async provide (key: CID, options: RoutingOptions<RoutingProvideProgressEvents> = {}): Promise<void> {\n if (this.routers.length === 0) {\n throw new NoRoutersAvailableError('No content routers available')\n }\n\n await Promise.all(\n supports(this.routers, 'provide')\n .map(async (router) => {\n options?.onProgress?.(new CustomProgressEvent('helia:routing:provide:start', {\n routing: router.name,\n cid: key\n }))\n\n await router.provide(key, options)\n\n options?.onProgress?.(new CustomProgressEvent('helia:routing:provide:end', {\n routing: router.name,\n cid: key\n }))\n })\n )\n }\n\n async cancelReprovide (key: CID, options: RoutingOptions<RoutingCancelReprovideProgressEvents> = {}): Promise<void> {\n await Promise.all(\n supports(this.routers, 'cancelReprovide')\n .map(async (router) => {\n options?.onProgress?.(new CustomProgressEvent('helia:routing:cancel-reprovide:start', {\n routing: router.name,\n cid: key\n }))\n\n await router.cancelReprovide(key, options)\n\n options?.onProgress?.(new CustomProgressEvent('helia:routing:cancel-reprovide:end', {\n routing: router.name,\n cid: key\n }))\n })\n )\n }\n\n /**\n * Store the given key/value pair in the available content routings\n */\n async put (key: Uint8Array, value: Uint8Array, options?: RoutingOptions<RoutingPutProgressEvents>): Promise<void> {\n await Promise.all(\n supports(this.routers, 'put')\n .map(async (router) => {\n options?.onProgress?.(new CustomProgressEvent('helia:routing:put:start', {\n routing: router.name,\n key,\n value\n }))\n\n await router.put(key, value, options)\n\n options?.onProgress?.(new CustomProgressEvent('helia:routing:put:end', {\n routing: router.name,\n key,\n value\n }))\n })\n )\n }\n\n /**\n * Get the value to the given key. The first value offered by any configured\n * router will be returned.\n */\n async get (key: Uint8Array, options?: RoutingOptions<RoutingGetProgressEvents>): Promise<Uint8Array> {\n const errors: Error[] = []\n let result: Uint8Array | undefined\n\n try {\n result = await Promise.any(\n supports(this.routers, 'get')\n .map(async (router) => {\n options?.onProgress?.(new CustomProgressEvent('helia:routing:get:start', {\n routing: router.name,\n key\n }))\n\n try {\n return await router.get(key, options)\n } catch (err: any) {\n this.log('router %s failed with %e', router, err)\n errors.push(err)\n } finally {\n options?.onProgress?.(new CustomProgressEvent('helia:routing:get:end', {\n routing: router.name,\n key\n }))\n }\n })\n )\n } catch {\n // ignore AggregateError as we will throw a better-named one\n }\n\n if (result == null) {\n throw new GetFailedError(errors, `Failed to get value key ${uint8ArrayToString(key, 'base58btc')}`)\n }\n\n return result\n }\n\n /**\n * Iterates over all peer routers in parallel to find the given peer\n */\n async findPeer (id: CID, options?: RoutingOptions<RoutingFindPeerProgressEvents>): Promise<Peer> {\n if (this.routers.length === 0) {\n throw new NoRoutersAvailableError('No peer routers available')\n }\n\n const self = this\n const source = merge(\n ...supports(this.routers, 'findPeer')\n .map(router => (async function * () {\n options?.onProgress?.(new CustomProgressEvent('helia:routing:find-peer:start', {\n routing: router.name,\n peerId: id\n }))\n\n try {\n yield await router.findPeer(id, options)\n } catch (err) {\n self.log.error(err)\n } finally {\n options?.onProgress?.(new CustomProgressEvent('helia:routing:find-peer:end', {\n routing: router.name,\n peerId: id\n }))\n }\n })())\n )\n\n for await (const peer of source) {\n if (peer == null) {\n continue\n }\n\n return peer\n }\n\n throw new NotFoundError('Could not find peer in routing')\n }\n\n /**\n * Attempt to find the closest peers on the network to the given key\n */\n async * getClosestPeers (key: Uint8Array, options: RoutingOptions<RoutingGetClosestPeersProgressEvents> = {}): AsyncIterable<Peer> {\n if (this.routers.length === 0) {\n throw new NoRoutersAvailableError('No peer routers available')\n }\n\n for await (const peer of merge(\n ...supports(this.routers, 'getClosestPeers')\n .map(async function * (router) {\n options?.onProgress?.(new CustomProgressEvent('helia:routing:get-closest-peers:start', {\n routing: router.name,\n key\n }))\n\n try {\n yield * router.getClosestPeers(key, options)\n } finally {\n options?.onProgress?.(new CustomProgressEvent('helia:routing:get-closest-peers:end', {\n routing: router.name,\n key\n }))\n }\n })\n )) {\n if (peer == null) {\n continue\n }\n\n yield peer\n }\n }\n}\n\nfunction supports <Operation extends keyof Routing> (routers: any[], key: Operation): Array<Pick<Routing, Operation | 'name'>> {\n return routers.filter(router => router[key] != null)\n}\n", "/**\n * @packageDocumentation\n *\n * A simple error class and options interface that seems to get copied from\n * project to project.\n *\n * @example Using AbortError\n *\n * ```JavaScript\n * import { AbortError } from 'abort-error'\n *\n * // a promise that will be settled later\n * const deferred = Promise.withResolvers()\n *\n * const signal = AbortSignal.timeout(1000)\n * signal.addEventListener('abort', () => {\n * deferred.reject(new AbortError())\n * })\n * ```\n *\n * @example Using AbortOptions\n *\n * ```TypeScript\n * import type { AbortOptions } from 'abort-error'\n *\n * async function myFunction (options?: AbortOptions) {\n * return fetch('https://example.com', {\n * signal: options?.signal\n * })\n * }\n * ```\n */\n\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\nexport class AbortError extends Error {\n static name = 'AbortError'\n name = 'AbortError'\n\n constructor (message: string = 'The operation was aborted', ...rest: any[]) {\n super(message, ...rest)\n }\n}\n", "/**\n * @packageDocumentation\n *\n * Race an event against an AbortSignal, taking care to remove any event\n * listeners that were added.\n *\n * @example Getting started\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * setTimeout(() => {\n * // too late\n * emitter.dispatchEvent(new CustomEvent('event'))\n * }, 1000)\n *\n * // throws an AbortError\n * const resolve = await raceEvent(emitter, 'event', controller.signal)\n * ```\n *\n * @example Aborting the promise with an error event\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const emitter = new EventTarget()\n *\n * setTimeout(() => {\n * emitter.dispatchEvent(new CustomEvent('failure', {\n * detail: new Error('Oh no!')\n * }))\n * }, 1000)\n *\n * // throws 'Oh no!' error\n * const resolve = await raceEvent(emitter, 'success', AbortSignal.timeout(5000), {\n * errorEvent: 'failure'\n * })\n * ```\n *\n * @example Customising the thrown AbortError\n *\n * The error message and `.code` property of the thrown `AbortError` can be\n * specified by passing options:\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * // throws a Error: Oh no!\n * const resolve = await raceEvent(emitter, 'event', controller.signal, {\n * errorMessage: 'Oh no!',\n * errorCode: 'ERR_OH_NO'\n * })\n * ```\n *\n * @example Only resolving on specific events\n *\n * Where multiple events with the same type are emitted, a `filter` function can\n * be passed to only resolve on one of them:\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * // throws a Error: Oh no!\n * const resolve = await raceEvent(emitter, 'event', controller.signal, {\n * filter: (evt: Event) => {\n * return evt.detail.foo === 'bar'\n * }\n * })\n * ```\n *\n * @example Terminating early by throwing from the filter\n *\n * You can cause listening for the event to cease and all event listeners to be\n * removed by throwing from the filter:\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * // throws Error: Cannot continue\n * const resolve = await raceEvent(emitter, 'event', controller.signal, {\n * filter: (evt) => {\n * if (...reasons) {\n * throw new Error('Cannot continue')\n * }\n *\n * return true\n * }\n * })\n * ```\n */\n\nimport { AbortError } from 'abort-error'\nimport type { EventEmitter } from 'node:events'\n\nexport interface RaceEventOptions<T> {\n /**\n * The message for the error thrown if the signal aborts\n */\n errorMessage?: string\n\n /**\n * The code for the error thrown if the signal aborts\n */\n errorCode?: string\n\n /**\n * The name of an event emitted on the emitter that should cause the returned\n * promise to reject. The rejection reason will be the `.detail` field of the\n * event.\n *\n * @default \"error\"\n */\n errorEvent?: string\n\n /**\n * If the 'errorEvent' option has been passed, and the emitted event has no\n * `.detail` field, reject the promise with this error instead.\n */\n error?: Error\n\n /**\n * When multiple events with the same name may be emitted, pass a filter\n * function here to allow ignoring ones that should not cause the returned\n * promise to resolve.\n */\n filter?(evt: T): boolean\n}\n\n/**\n * Race a promise against an abort signal\n */\nexport async function raceEvent <T> (emitter: EventTarget | EventEmitter, eventName: string, signal?: AbortSignal, opts?: RaceEventOptions<T>): Promise<T> {\n // create the error here so we have more context in the stack trace\n const error = new AbortError(opts?.errorMessage)\n\n if (opts?.errorCode != null) {\n // @ts-expect-error not a field of AbortError\n error.code = opts.errorCode\n }\n\n const errorEvent = opts?.errorEvent ?? 'error'\n\n if (signal?.aborted === true) {\n return Promise.reject(error)\n }\n\n return new Promise((resolve, reject) => {\n function removeListeners (): void {\n removeListener(signal, 'abort', abortListener)\n removeListener(emitter, eventName, eventListener)\n removeListener(emitter, errorEvent, errorEventListener)\n }\n\n const eventListener = (evt: any): void => {\n try {\n if (opts?.filter?.(evt) === false) {\n return\n }\n } catch (err: any) {\n removeListeners()\n reject(err)\n return\n }\n\n removeListeners()\n resolve(evt)\n }\n\n const errorEventListener = (evt: any): void => {\n removeListeners()\n\n if (evt instanceof Error) {\n reject(evt)\n return\n }\n\n reject(evt.detail ?? opts?.error ?? new Error(`The \"${opts?.errorEvent}\" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))\n }\n\n const abortListener = (): void => {\n removeListeners()\n reject(error)\n }\n\n addListener(signal, 'abort', abortListener)\n addListener(emitter, eventName, eventListener)\n addListener(emitter, errorEvent, errorEventListener)\n })\n}\n\nfunction addListener (emitter: EventEmitter | EventTarget | undefined, event: string, listener: any): void {\n if (emitter == null) {\n return\n }\n\n if (isEventTarget(emitter)) {\n emitter.addEventListener(event, listener)\n } else {\n emitter.addListener(event, listener)\n }\n}\n\nfunction removeListener (emitter: EventEmitter | EventTarget | undefined, event: string, listener: any): void {\n if (emitter == null) {\n return\n }\n\n if (isEventTarget(emitter)) {\n emitter.removeEventListener(event, listener)\n } else {\n emitter.removeListener(event, listener)\n }\n}\n\nfunction isEventTarget (emitter: any): emitter is EventTarget {\n return typeof emitter.addEventListener === 'function' && typeof emitter.removeEventListener === 'function'\n}\n", "export class QueueFullError extends Error {\n static name = 'QueueFullError'\n\n constructor (message: string = 'The queue was full') {\n super(message)\n this.name = 'QueueFullError'\n }\n}\n", "import { AbortError } from 'abort-error'\n\nexport class JobRecipient<JobReturnType> {\n public deferred: PromiseWithResolvers<JobReturnType>\n public signal?: AbortSignal\n\n constructor (signal?: AbortSignal) {\n this.signal = signal\n this.deferred = Promise.withResolvers()\n\n this.onAbort = this.onAbort.bind(this)\n this.signal?.addEventListener('abort', this.onAbort)\n }\n\n onAbort (): void {\n this.deferred.reject(this.signal?.reason ?? new AbortError())\n }\n\n cleanup (): void {\n this.signal?.removeEventListener('abort', this.onAbort)\n }\n}\n", "import { AbortError } from 'abort-error'\nimport { setMaxListeners } from 'main-event'\nimport { raceSignal } from 'race-signal'\nimport { JobRecipient } from './recipient.ts'\nimport type { JobStatus } from './index.ts'\nimport type { AbortOptions } from 'abort-error'\n\n/**\n * Returns a random string\n */\nfunction randomId (): string {\n return `${(parseInt(String(Math.random() * 1e9), 10)).toString()}${Date.now()}`\n}\n\nexport interface JobTimeline {\n created: number\n started?: number\n finished?: number\n}\n\nexport class Job <JobOptions extends AbortOptions = AbortOptions, JobReturnType = unknown> {\n public id: string\n public fn: (options: JobOptions) => Promise<JobReturnType>\n public options: JobOptions\n public recipients: Array<JobRecipient<JobReturnType>>\n public status: JobStatus\n public readonly timeline: JobTimeline\n private readonly controller: AbortController\n\n constructor (fn: (options: JobOptions) => Promise<JobReturnType>, options: any) {\n this.id = randomId()\n this.status = 'queued'\n this.fn = fn\n this.options = options\n this.recipients = []\n this.timeline = {\n created: Date.now()\n }\n\n this.controller = new AbortController()\n setMaxListeners(Infinity, this.controller.signal)\n\n this.onAbort = this.onAbort.bind(this)\n }\n\n abort (err: Error): void {\n this.controller.abort(err)\n }\n\n onAbort (): void {\n const allAborted = this.recipients.reduce((acc, curr) => {\n return acc && (curr.signal?.aborted === true)\n }, true)\n\n // if all recipients have aborted the job, actually abort the job\n if (allAborted) {\n this.controller.abort(new AbortError())\n this.cleanup()\n }\n }\n\n async join (options: AbortOptions = {}): Promise<JobReturnType> {\n const recipient = new JobRecipient<JobReturnType>(options.signal)\n this.recipients.push(recipient)\n\n options.signal?.addEventListener('abort', this.onAbort)\n\n return recipient.deferred.promise\n }\n\n async run (): Promise<void> {\n this.status = 'running'\n this.timeline.started = Date.now()\n\n try {\n this.controller.signal.throwIfAborted()\n\n const result = await raceSignal(this.fn({\n ...(this.options ?? {}),\n signal: this.controller.signal\n }), this.controller.signal)\n\n this.recipients.forEach(recipient => {\n recipient.deferred.resolve(result)\n })\n\n this.status = 'complete'\n } catch (err) {\n this.recipients.forEach(recipient => {\n recipient.deferred.reject(err)\n })\n\n this.status = 'errored'\n } finally {\n this.timeline.finished = Date.now()\n this.cleanup()\n }\n }\n\n cleanup (): void {\n this.recipients.forEach(recipient => {\n recipient.cleanup()\n recipient.signal?.removeEventListener('abort', this.onAbort)\n })\n }\n}\n", "/**\n * A function with additional start/stop methods\n */\nexport interface DebouncedFunction {\n (): void\n\n start(): void\n stop(): void\n}\n\n/**\n * Returns a function wrapper that will only call the passed function once\n *\n * Important - the passed function should not throw or reject\n */\nexport function debounce (func: () => void | Promise<void>, wait: number): DebouncedFunction {\n let timeout: ReturnType<typeof setTimeout> | undefined\n\n const output = function (): void {\n const later = function (): void {\n timeout = undefined\n void func()\n }\n\n clearTimeout(timeout)\n timeout = setTimeout(later, wait)\n }\n output.start = (): void => {}\n output.stop = (): void => {\n clearTimeout(timeout)\n }\n\n return output\n}\n", "/**\n * @packageDocumentation\n *\n * Based on `p-queue` but with access to the underlying queue, aborting a task\n * removes it from the queue and you can iterate over the queue results.\n *\n * @example\n *\n * ```ts\n * import all from 'it-all'\n * import { Queue } from 'it-queue'\n *\n * const queue = new Queue({\n * concurrency: Infinity\n * })\n * void queue.add(async () => {\n * return 'hello'\n * })\n * void queue.add(async () => {\n * return 'world'\n * })\n *\n * const results = await all(queue)\n * // ['hello', 'world']\n *\n * // how many items are in the queue (includes running items)\n * console.info(queue.size)\n *\n * // how many items are running\n * console.info(queue.running)\n *\n * // how many items have not started running yet\n * console.info(queue.queued)\n * ```\n */\n\nimport { AbortError } from 'abort-error'\nimport { pushable } from 'it-pushable'\nimport { TypedEventEmitter } from 'main-event'\nimport { raceEvent } from 'race-event'\nimport { QueueFullError } from './errors.ts'\nimport { Job } from './job.ts'\nimport { debounce } from './utils.ts'\nimport type { AbortOptions } from 'abort-error'\nexport type { Job, JobTimeline } from './job.ts'\nexport type { JobRecipient } from './recipient.ts'\n\nexport interface Comparator<T> {\n (a: T, b: T): -1 | 0 | 1\n}\n\nexport interface QueueInit<JobReturnType, JobOptions extends AbortOptions = AbortOptions> {\n /**\n * Concurrency limit.\n *\n * Minimum: `1`.\n *\n * @default Infinity\n */\n concurrency?: number\n\n /**\n * If the queue size grows to larger than this number the promise returned\n * from the add function will reject\n *\n * @default Infinity\n */\n maxSize?: number\n\n /**\n * An optional function that will sort the queue after a job has been added\n */\n sort?: Comparator<Job<JobOptions, JobReturnType>>\n\n /**\n * If false, `.start` will need to be called to start processing jobs\n *\n * @default true\n */\n autoStart?: boolean\n}\n\nexport type JobStatus = 'queued' | 'running' | 'errored' | 'complete'\n\nexport interface RunFunction<Options extends AbortOptions = AbortOptions, ReturnType = void> {\n (options: Options): Promise<ReturnType>\n}\n\nexport interface JobMatcher<JobOptions extends AbortOptions = AbortOptions> {\n (options?: Partial<JobOptions>): boolean\n}\n\nexport interface QueueJobSuccess<JobReturnType, JobOptions extends AbortOptions = AbortOptions> {\n job: Job<JobOptions, JobReturnType>\n result: JobReturnType\n}\n\nexport interface QueueJobFailure<JobReturnType, JobOptions extends AbortOptions = AbortOptions> {\n job: Job<JobOptions, JobReturnType>\n error: Error\n}\n\nexport interface QueueEvents<JobReturnType, JobOptions extends AbortOptions = AbortOptions> {\n /**\n * A job is about to start running\n */\n active: CustomEvent\n\n /**\n * All jobs have finished and the queue is empty\n */\n idle: CustomEvent\n\n /**\n * The queue is empty, jobs may be running\n */\n empty: CustomEvent\n\n /**\n * A job was added to the queue\n */\n add: CustomEvent\n\n /**\n * A job has finished or failed\n */\n next: CustomEvent\n\n /**\n * Emitted just after `\"completed\", a job has finished successfully - this\n * event gives access to the job and it's result\n */\n success: CustomEvent<QueueJobSuccess<JobReturnType, JobOptions>>\n\n /**\n * A job has failed - this event gives access to the job and the thrown error\n */\n failure: CustomEvent<QueueJobFailure<JobReturnType, JobOptions>>\n}\n\n/**\n * Heavily influence by `p-queue` with the following differences:\n *\n * 1. Items remain at the head of the queue while they are running so `queue.size` includes `queue.pending` items - this is so interested parties can join the results of a queue item while it is running\n * 2. The options for a job are stored separately to the job in order for them to be modified while they are still in the queue\n * 3. If a job's abort signal fires before execution begins, it is removed from the queue immediately\n * 4. 'success'/'failure' events are emitted instead of 'error'/'complete'\n */\nexport class Queue<JobReturnType = unknown, JobOptions extends AbortOptions = AbortOptions> extends TypedEventEmitter<QueueEvents<JobReturnType, JobOptions>> {\n public concurrency: number\n public maxSize: number\n public queue: Array<Job<JobOptions, JobReturnType>>\n private pending: number\n private readonly sort?: Comparator<Job<JobOptions, JobReturnType>>\n private autoStart: boolean\n\n constructor (init: QueueInit<JobReturnType, JobOptions> = {}) {\n super()\n\n this.concurrency = init.concurrency ?? Number.POSITIVE_INFINITY\n this.maxSize = init.maxSize ?? Number.POSITIVE_INFINITY\n this.pending = 0\n this.autoStart = init.autoStart ?? true\n\n this.sort = init.sort\n this.queue = []\n\n this.emitEmpty = debounce(this.emitEmpty.bind(this), 1)\n this.emitIdle = debounce(this.emitIdle.bind(this), 1)\n }\n\n [Symbol.asyncIterator] (): AsyncGenerator<JobReturnType, void, unknown> {\n return this.toGenerator()\n }\n\n emitEmpty (): void {\n if (this.size !== 0) {\n return\n }\n\n this.safeDispatchEvent('empty')\n }\n\n emitIdle (): void {\n if (this.running !== 0) {\n return\n }\n\n this.safeDispatchEvent('idle')\n }\n\n private tryToStartAnother (): boolean {\n if (this.size === 0) {\n this.emitEmpty()\n\n if (this.running === 0) {\n this.emitIdle()\n }\n\n return false\n }\n\n if (this.pending < this.concurrency) {\n let job: Job<JobOptions, JobReturnType> | undefined\n\n for (const j of this.queue) {\n if (j.status === 'queued') {\n job = j\n break\n }\n }\n\n if (job == null) {\n return false\n }\n\n this.safeDispatchEvent('active')\n\n this.pending++\n\n void job.run()\n .finally(() => {\n // remove the job from the queue\n for (let i = 0; i < this.queue.length; i++) {\n if (this.queue[i] === job) {\n this.queue.splice(i, 1)\n break\n }\n }\n\n this.pending--\n this.safeDispatchEvent('next')\n if (this.autoStart) {\n this.tryToStartAnother()\n }\n })\n\n return true\n }\n\n return false\n }\n\n private enqueue (job: Job<JobOptions, JobReturnType>): void {\n this.queue.push(job)\n\n if (this.sort != null) {\n this.queue.sort(this.sort)\n }\n }\n\n /**\n * Start the queue. If the `autoStart` parameter passed to the constructor was\n * not `false` this is a no-op\n */\n start (): void {\n if (this.autoStart !== false) {\n return\n }\n\n this.autoStart = true\n this.tryToStartAnother()\n }\n\n /**\n * Prevent further jobs from running - call `.start` to start the queue again\n */\n pause (): void {\n this.autoStart = false\n }\n\n /**\n * Adds a sync or async task to the queue. Always returns a promise.\n */\n async add (fn: RunFunction<JobOptions, JobReturnType>, options?: JobOptions): Promise<JobReturnType> {\n options?.signal?.throwIfAborted()\n\n if (this.size === this.maxSize) {\n throw new QueueFullError()\n }\n\n const job = new Job<JobOptions, JobReturnType>(fn, options)\n this.enqueue(job)\n this.safeDispatchEvent('add')\n\n if (this.autoStart) {\n this.tryToStartAnother()\n }\n\n return job.join(options)\n .then(result => {\n this.safeDispatchEvent('success', { detail: { job, result } })\n\n return result\n })\n .catch(err => {\n if (job.status === 'queued') {\n // job was aborted before it started - remove the job from the queue\n for (let i = 0; i < this.queue.length; i++) {\n if (this.queue[i] === job) {\n this.queue.splice(i, 1)\n break\n }\n }\n }\n\n this.safeDispatchEvent('failure', { detail: { job, error: err } })\n\n throw err\n })\n }\n\n /**\n * Clear the queue\n */\n clear (): void {\n this.queue.splice(0, this.queue.length)\n }\n\n /**\n * Abort all jobs in the queue and clear it\n */\n abort (): void {\n this.queue.forEach(job => {\n job.abort(new AbortError())\n })\n\n this.clear()\n }\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 (options?: AbortOptions): Promise<void> {\n // Instantly resolve if the queue is empty\n if (this.size === 0) {\n return\n }\n\n await raceEvent(this, 'empty', options?.signal)\n }\n\n /**\n * @returns A promise that settles when the queue size is less than the given\n * limit: `queue.size < limit`.\n *\n * If you want to avoid having the queue grow beyond a certain size you can\n * `await queue.onSizeLessThan()` before adding a new item.\n *\n * Note that this only limits the number of items waiting to start. There\n * could still be up to `concurrency` jobs already running that this call does\n * not include in its calculation.\n */\n async onSizeLessThan (limit: number, options?: AbortOptions): Promise<void> {\n // Instantly resolve if the queue is empty.\n if (this.size < limit) {\n return\n }\n\n await raceEvent(this, 'next', options?.signal, {\n filter: () => this.size < limit\n })\n }\n\n /**\n * The difference with `.onEmpty` is that `.onIdle` guarantees that all work\n * from the queue has finished. `.onEmpty` merely signals that the queue is\n * 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\n * promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle (options?: AbortOptions): Promise<void> {\n // Instantly resolve if none pending and if nothing else is queued\n if (this.pending === 0 && this.size === 0) {\n return\n }\n\n await raceEvent(this, 'idle', options?.signal)\n }\n\n /**\n * Size of the queue including running items\n */\n get size (): number {\n return this.queue.length\n }\n\n /**\n * The number of queued items waiting to run.\n */\n get queued (): number {\n return this.queue.length - this.pending\n }\n\n /**\n * The number of items currently running.\n */\n get running (): number {\n return this.pending\n }\n\n /**\n * Returns an async generator that makes it easy to iterate over the results\n * of jobs added to the queue.\n *\n * The generator will end when the queue becomes idle, that is there are no\n * jobs running and no jobs that have yet to run.\n *\n * If you need to keep the queue open indefinitely, consider using it-pushable\n * instead.\n */\n async * toGenerator (options?: AbortOptions): AsyncGenerator<JobReturnType, void, unknown> {\n options?.signal?.throwIfAborted()\n\n const stream = pushable<JobReturnType>({\n objectMode: true\n })\n\n const cleanup = (err?: Error): void => {\n if (err != null) {\n this.abort()\n } else {\n this.clear()\n }\n\n stream.end(err)\n }\n\n const onQueueJobComplete = (evt: CustomEvent<QueueJobSuccess<JobReturnType, JobOptions>>): void => {\n if (evt.detail != null) {\n stream.push(evt.detail.result)\n }\n }\n\n const onQueueError = (evt: CustomEvent<QueueJobFailure<JobReturnType, JobOptions>>): void => {\n cleanup(evt.detail.error)\n }\n\n const onQueueIdle = (): void => {\n cleanup()\n }\n\n // clear the queue and throw if the query is aborted\n const onSignalAbort = (): void => {\n cleanup(new AbortError('Queue aborted'))\n }\n\n // add listeners\n this.addEventListener('success', onQueueJobComplete)\n this.addEventListener('failure', onQueueError)\n this.addEventListener('idle', onQueueIdle)\n options?.signal?.addEventListener('abort', onSignalAbort)\n\n try {\n yield * stream\n } finally {\n // remove listeners\n this.removeEventListener('success', onQueueJobComplete)\n this.removeEventListener('failure', onQueueError)\n this.removeEventListener('idle', onQueueIdle)\n options?.signal?.removeEventListener('abort', onSignalAbort)\n\n // empty the queue for when the user has broken out of a loop early\n cleanup()\n }\n }\n}\n", "export const WORKER_REQUEST_READ_LOCK = 'lock:worker:request-read'\nexport const WORKER_ABORT_READ_LOCK_REQUEST = 'lock:worker:abort-read-request'\nexport const WORKER_RELEASE_READ_LOCK = 'lock:worker:release-read'\nexport const MASTER_GRANT_READ_LOCK = 'lock:master:grant-read'\nexport const MASTER_READ_LOCK_ERROR = 'lock:master:error-read'\n\nexport const WORKER_REQUEST_WRITE_LOCK = 'lock:worker:request-write'\nexport const WORKER_ABORT_WRITE_LOCK_REQUEST = 'lock:worker:abort-write-request'\nexport const WORKER_RELEASE_WRITE_LOCK = 'lock:worker:release-write'\nexport const MASTER_GRANT_WRITE_LOCK = 'lock:master:grant-write'\nexport const MASTER_WRITE_LOCK_ERROR = 'lock:master:error-write'\n\nexport const WORKER_FINALIZE = 'lock:worker:finalize'\n\nexport const BROADCAST_CHANNEL_NAME = 'mortice'\n\nexport const defaultOptions = {\n singleProcess: false\n}\n", "import {\n WORKER_FINALIZE\n} from '../constants.js'\nimport type { AbortEventData, AbortRequestType, FinalizeEventData, MorticeEvents, RequestType } from '../mortice.js'\nimport type { TypedEventTarget } from 'main-event'\n\nexport const handleChannelWorkerLockRequest = (emitter: TypedEventTarget<MorticeEvents>, channel: BroadcastChannel, masterEvent: RequestType, abortMasterEvent: AbortRequestType, requestType: string, abortType: string, errorType: string, releaseType: string, grantType: string) => {\n return (event: MessageEvent) => {\n if (event.data == null) {\n return\n }\n\n const requestEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n }\n\n // worker is requesting lock\n if (requestEvent.type === requestType) {\n emitter.safeDispatchEvent(masterEvent, {\n detail: {\n name: requestEvent.name,\n identifier: requestEvent.identifier,\n handler: async (): Promise<void> => {\n // grant lock to worker\n channel.postMessage({\n type: grantType,\n name: requestEvent.name,\n identifier: requestEvent.identifier\n })\n\n // wait for worker to finish\n await new Promise<void>((resolve) => {\n const releaseEventListener = (event: MessageEvent): void => {\n if (event?.data == null) {\n return\n }\n\n const releaseEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n }\n\n if (releaseEvent.type === releaseType && releaseEvent.identifier === requestEvent.identifier) {\n channel.removeEventListener('message', releaseEventListener)\n resolve()\n }\n }\n\n channel.addEventListener('message', releaseEventListener)\n })\n },\n onError: (err: Error) => {\n // send error to worker\n channel.postMessage({\n type: errorType,\n name: requestEvent.name,\n identifier: requestEvent.identifier,\n error: {\n message: err.message,\n name: err.name,\n stack: err.stack\n }\n })\n }\n }\n })\n }\n\n // worker is no longer interested in requesting the lock\n if (requestEvent.type === abortType) {\n emitter.safeDispatchEvent<AbortEventData>(abortMasterEvent, {\n detail: {\n name: requestEvent.name,\n identifier: requestEvent.identifier\n }\n })\n }\n\n // worker is done with lock\n if (requestEvent.type === WORKER_FINALIZE) {\n emitter.safeDispatchEvent<FinalizeEventData>('finalizeRequest', {\n detail: {\n name: requestEvent.name\n }\n })\n }\n }\n}\n", "export const nanoid = (size: number = 10): string => {\n return Math.random().toString().substring(2, size + 2)\n}\n", "import {\n WORKER_REQUEST_READ_LOCK,\n WORKER_RELEASE_READ_LOCK,\n MASTER_GRANT_READ_LOCK,\n WORKER_REQUEST_WRITE_LOCK,\n WORKER_RELEASE_WRITE_LOCK,\n MASTER_GRANT_WRITE_LOCK,\n WORKER_ABORT_READ_LOCK_REQUEST,\n WORKER_ABORT_WRITE_LOCK_REQUEST,\n MASTER_READ_LOCK_ERROR,\n MASTER_WRITE_LOCK_ERROR,\n WORKER_FINALIZE,\n BROADCAST_CHANNEL_NAME\n} from '../constants.js'\nimport { nanoid } from '../utils.js'\nimport type { Mortice, Release } from '../index.js'\nimport type { AbortOptions } from 'abort-error'\n\nexport class MorticeChannelWorker implements Mortice {\n private name: string\n private channel: BroadcastChannel\n\n constructor (name: string) {\n this.name = name\n this.channel = new BroadcastChannel(BROADCAST_CHANNEL_NAME)\n }\n\n readLock (options?: AbortOptions): Promise<Release> {\n return this.sendRequest(\n WORKER_REQUEST_READ_LOCK,\n WORKER_ABORT_READ_LOCK_REQUEST,\n MASTER_GRANT_READ_LOCK,\n MASTER_READ_LOCK_ERROR,\n WORKER_RELEASE_READ_LOCK,\n options\n )\n }\n\n writeLock (options?: AbortOptions): Promise<Release> {\n return this.sendRequest(\n WORKER_REQUEST_WRITE_LOCK,\n WORKER_ABORT_WRITE_LOCK_REQUEST,\n MASTER_GRANT_WRITE_LOCK,\n MASTER_WRITE_LOCK_ERROR,\n WORKER_RELEASE_WRITE_LOCK,\n options\n )\n }\n\n finalize (): void {\n this.channel.postMessage({\n type: WORKER_FINALIZE,\n name: this.name\n })\n\n this.channel.close()\n }\n\n private async sendRequest (requestType: string, abortType: string, grantType: string, errorType: string, releaseType: string, options?: AbortOptions): Promise<Release> {\n options?.signal?.throwIfAborted()\n const id = nanoid()\n\n this.channel.postMessage({\n type: requestType,\n identifier: id,\n name: this.name\n })\n\n return new Promise<Release>((resolve, reject) => {\n const abortListener = (): void => {\n this.channel.postMessage({\n type: abortType,\n identifier: id,\n name: this.name\n })\n }\n\n options?.signal?.addEventListener('abort', abortListener, {\n once: true\n })\n\n const listener = (event: MessageEvent): void => {\n if (event.data?.identifier !== id) {\n return\n }\n\n if (event.data?.type === grantType) {\n this.channel.removeEventListener('message', listener)\n options?.signal?.removeEventListener('abort', abortListener)\n\n // lock granted\n resolve(() => {\n // release lock\n this.channel.postMessage({\n type: releaseType,\n identifier: id,\n name: this.name\n })\n })\n }\n\n if (event.data.type === errorType) {\n this.channel.removeEventListener('message', listener)\n options?.signal?.removeEventListener('abort', abortListener)\n\n // error while waiting for grant of lock\n const err = new Error()\n\n if (event.data.error != null) {\n err.message = event.data.error.message\n err.name = event.data.error.name\n err.stack = event.data.error.stack\n }\n\n reject(err)\n }\n }\n\n this.channel.addEventListener('message', listener)\n })\n }\n}\n", "import { TypedEventEmitter } from 'main-event'\nimport {\n WORKER_REQUEST_READ_LOCK,\n WORKER_RELEASE_READ_LOCK,\n MASTER_GRANT_READ_LOCK,\n WORKER_REQUEST_WRITE_LOCK,\n WORKER_RELEASE_WRITE_LOCK,\n MASTER_GRANT_WRITE_LOCK,\n WORKER_ABORT_READ_LOCK_REQUEST,\n WORKER_ABORT_WRITE_LOCK_REQUEST,\n MASTER_READ_LOCK_ERROR,\n MASTER_WRITE_LOCK_ERROR,\n BROADCAST_CHANNEL_NAME,\n defaultOptions\n} from './constants.js'\nimport { handleChannelWorkerLockRequest } from './main/channel.ts'\nimport { MorticeChannelWorker } from './workers/channel.ts'\nimport type { Mortice, MorticeOptions } from './index.js'\nimport type { MorticeEvents } from './mortice.js'\nimport type { TypedEventTarget } from 'main-event'\n\nexport default (options: Required<MorticeOptions>): Mortice | TypedEventTarget<MorticeEvents> => {\n options = Object.assign({}, defaultOptions, options)\n const isPrimary = Boolean(globalThis.document) || options.singleProcess\n\n if (isPrimary) {\n const channel = new BroadcastChannel(BROADCAST_CHANNEL_NAME)\n const emitter = new TypedEventEmitter<MorticeEvents>()\n\n channel.addEventListener('message', handleChannelWorkerLockRequest(\n emitter,\n channel,\n 'requestReadLock',\n 'abortReadLockRequest',\n WORKER_REQUEST_READ_LOCK,\n WORKER_ABORT_READ_LOCK_REQUEST,\n MASTER_READ_LOCK_ERROR,\n WORKER_RELEASE_READ_LOCK,\n MASTER_GRANT_READ_LOCK\n ))\n channel.addEventListener('message', handleChannelWorkerLockRequest(\n emitter,\n channel,\n 'requestWriteLock',\n 'abortWriteLockRequest',\n WORKER_REQUEST_WRITE_LOCK,\n WORKER_ABORT_WRITE_LOCK_REQUEST,\n MASTER_WRITE_LOCK_ERROR,\n WORKER_RELEASE_WRITE_LOCK,\n MASTER_GRANT_WRITE_LOCK\n ))\n\n return emitter\n }\n\n return new MorticeChannelWorker(options.name)\n}\n", "import { AbortError } from 'abort-error'\nimport { Queue } from 'it-queue'\nimport impl from './node.js'\nimport type { Mortice, MorticeOptions, Release } from './index.js'\nimport type { AbortOptions } from 'abort-error'\nimport type { TypedEventTarget } from 'main-event'\n\nexport type RequestType = 'requestReadLock' | 'requestWriteLock'\nexport type AbortRequestType = 'abortReadLockRequest' | 'abortWriteLockRequest'\nexport type FinalizeRequestType = 'finalizeRequest'\n\nexport interface RequestEventData {\n name: string\n identifier: string\n handler(): Promise<void>\n onError(err: Error): void\n}\n\nexport interface RequestEvent {\n type: string\n identifier: string\n name: string,\n error?: {\n name: string\n message: string\n stack: string\n }\n}\n\nexport interface AbortEventData {\n name: string\n identifier: string\n}\n\nexport interface FinalizeEventData {\n name: string\n}\n\nexport interface MorticeEvents {\n requestReadLock: CustomEvent<RequestEventData>\n abortReadLockRequest: CustomEvent<AbortEventData>\n requestWriteLock: CustomEvent<RequestEventData>\n abortWriteLockRequest: CustomEvent<AbortEventData>\n finalizeRequest: CustomEvent<FinalizeEventData>\n}\n\nconst mutexes: Map<string, Mortice> = new Map()\nlet implementation: Mortice | TypedEventTarget<MorticeEvents>\n\nexport function isMortice (obj?: any): obj is Mortice {\n return typeof obj?.readLock === 'function' && typeof obj?.writeLock === 'function'\n}\n\nexport function getImplementation (opts: Required<MorticeOptions>): Mortice | TypedEventTarget<MorticeEvents> {\n if (implementation == null) {\n implementation = impl(opts)\n\n if (!isMortice(implementation)) {\n const emitter = implementation\n\n // we are master, set up worker requests\n emitter.addEventListener('requestReadLock', (event: CustomEvent<RequestEventData>) => {\n const mutexName = event.detail.name\n const identifier = event.detail.identifier\n const mutex = mutexes.get(mutexName)\n\n if (mutex == null) {\n return\n }\n\n const abortController = new AbortController()\n\n const abortListener = (event: CustomEvent<AbortEventData>): void => {\n if (event.detail.name !== mutexName || event.detail.identifier !== identifier) {\n return\n }\n\n abortController.abort()\n }\n\n emitter.addEventListener('abortReadLockRequest', abortListener)\n\n void mutex.readLock({\n signal: abortController.signal\n })\n .then(async release => {\n await event.detail.handler()\n .finally(() => {\n release()\n })\n })\n .catch(err => {\n event.detail.onError(err)\n })\n .finally(() => {\n emitter.removeEventListener('abortReadLockRequest', abortListener)\n })\n })\n\n emitter.addEventListener('requestWriteLock', (event: CustomEvent<RequestEventData>) => {\n const mutexName = event.detail.name\n const identifier = event.detail.identifier\n const mutex = mutexes.get(mutexName)\n\n if (mutex == null) {\n return\n }\n\n const abortController = new AbortController()\n\n const abortListener = (event: CustomEvent<AbortEventData>): void => {\n if (event.detail.name !== mutexName || event.detail.identifier !== identifier) {\n return\n }\n\n abortController.abort()\n }\n\n emitter.addEventListener('abortWriteLockRequest', abortListener)\n\n void mutex.writeLock({\n signal: abortController.signal\n })\n .then(async release => {\n await event.detail.handler()\n .finally(() => {\n release()\n })\n })\n .catch(err => {\n event.detail.onError(err)\n })\n .finally(() => {\n emitter.removeEventListener('abortWriteLockRequest', abortListener)\n })\n })\n\n emitter.addEventListener('finalizeRequest', (event: CustomEvent<FinalizeEventData>): void => {\n const mutexName = event.detail.name\n const mutex = mutexes.get(mutexName)\n\n if (mutex == null) {\n return\n }\n\n mutex.finalize()\n })\n }\n }\n\n return implementation\n}\n\nasync function createReleasable (queue: Queue, options?: AbortOptions): Promise<Release> {\n let res: (release: Release) => void\n let rej: (err: Error) => void\n\n const p = new Promise<Release>((resolve, reject) => {\n res = resolve\n rej = reject\n })\n\n const listener = (): void => {\n rej(new AbortError())\n }\n\n options?.signal?.addEventListener('abort', listener, {\n once: true\n })\n\n queue.add(async () => {\n await new Promise<void>((resolve) => {\n res(() => {\n options?.signal?.removeEventListener('abort', listener)\n resolve()\n })\n })\n }, {\n signal: options?.signal\n })\n .catch((err) => {\n rej(err)\n })\n\n return p\n}\n\nexport const createMutex = (name: string, options: Required<MorticeOptions>): Mortice => {\n let mutex = mutexes.get(name)\n\n if (mutex != null) {\n return mutex\n }\n\n const implementation = getImplementation(options)\n\n // a Mortice instance will be returned if we are a worker, otherwise if we are\n // primary an event target will be returned that fires events when workers\n // request a lock\n if (isMortice(implementation)) {\n mutex = implementation\n\n mutexes.set(name, mutex)\n\n return mutex\n }\n\n const masterQueue = new Queue({\n concurrency: 1\n })\n let readQueue: Queue | null\n\n mutex = {\n async readLock (opts?: AbortOptions) {\n // If there's already a read queue, just add the task to it\n if (readQueue != null) {\n return createReleasable(readQueue, opts)\n }\n\n // Create a new read queue\n readQueue = new Queue({\n concurrency: options.concurrency,\n autoStart: false\n })\n const localReadQueue = readQueue\n\n // Add the task to the read queue\n const readPromise = createReleasable(readQueue, opts)\n\n void masterQueue.add(async () => {\n // Start the task only once the master queue has completed processing\n // any previous tasks\n localReadQueue.start()\n\n // Once all the tasks in the read queue have completed, remove it so\n // that the next read lock will occur after any write locks that were\n // started in the interim\n await localReadQueue.onIdle()\n .then(() => {\n if (readQueue === localReadQueue) {\n readQueue = null\n }\n })\n })\n\n return readPromise\n },\n async writeLock (opts?: AbortOptions) {\n // Remove the read queue reference, so that any later read locks will be\n // added to a new queue that starts after this write lock has been\n // released\n readQueue = null\n\n return createReleasable(masterQueue, opts)\n },\n finalize: () => {\n mutexes.delete(name)\n },\n queue: masterQueue\n }\n\n mutexes.set(name, mutex)\n\n // if requested, finalize the lock once the last lock holder has released it\n if (options.autoFinalize === true) {\n masterQueue.addEventListener('idle', () => {\n mutex.finalize()\n }, {\n once: true\n })\n }\n\n return mutex\n}\n", "/**\n * @packageDocumentation\n *\n * - Reads occur concurrently\n * - Writes occur one at a time\n * - No reads occur while a write operation is in progress\n * - Locks can be created with different names\n * - Reads/writes can time out\n *\n * @example\n *\n * ```ts\n * import mortice from 'mortice'\n * import delay from 'delay'\n *\n * // the lock name & options objects are both optional\n * const mutex = mortice()\n *\n * Promise.all([\n * (async () => {\n * const release = await mutex.readLock()\n *\n * try {\n * console.info('read 1')\n * } finally {\n * release()\n * }\n * })(),\n * (async () => {\n * const release = await mutex.readLock()\n *\n * try {\n * console.info('read 2')\n * } finally {\n * release()\n * }\n * })(),\n * (async () => {\n * const release = await mutex.writeLock()\n *\n * try {\n * await delay(1000)\n *\n * console.info('write 1')\n * } finally {\n * release()\n * }\n * })(),\n * (async () => {\n * const release = await mutex.readLock()\n *\n * try {\n * console.info('read 3')\n * } finally {\n * release()\n * }\n * })()\n * ])\n * ```\n *\n * read 1\n * read 2\n * <small pause>\n * write 1\n * read 3\n *\n * ## Clean up\n *\n * Mutexes are stored globally reference by name, this is so you can obtain the\n * same lock from different contexts, including workers.\n *\n * When a mutex is no longer required, the `.finalize` function should be called\n * to remove any internal references to it.\n *\n * ```ts\n * import mortice from 'mortice'\n *\n * const mutex = mortice()\n *\n * // ...some time later\n *\n * mutex.finalize()\n * ```\n *\n * ## Auto clean up\n *\n * If your app generates a lot of short-lived mutexes and you want to clean them\n * up after the last lock has been released, pass the `autoFinalize` option to\n * mortice in the owning context:\n *\n ```ts\n * import mortice from 'mortice'\n *\n * const mutex = mortice({\n * autoFinalize: true\n * })\n *\n * const release = await mutex.readLock()\n * // ...some time later\n *\n * release()\n *\n * // mutex will be freed soon after\n * ```\n *\n * ## React native support\n *\n * This module should run on react native but it only supports single-process\n * concurrency as it's not clear to the author (disclaimer - not a react native\n * dev) what the officially supported process concurrency model is.\n *\n * Please open an issue if this is a feature you would like to see added.\n */\n\nimport { Queue } from 'it-queue'\nimport { createMutex } from './mortice.ts'\nimport type { AbortOptions } from 'abort-error'\n\nexport interface MorticeOptions {\n /**\n * An optional name for the lock\n */\n name?: string\n\n /**\n * How many read operations are executed concurrently\n *\n * @default Infinity\n */\n concurrency?: number\n\n /**\n * By default the the lock will be held on the main thread and child/worker\n * processes will coordinate to share the lock.\n *\n * Set this to true if each main/child/worker thread should maintain it's own\n * lock with no coordination between them.\n *\n * @default false\n */\n singleProcess?: boolean\n\n /**\n * If true, the lock will be finalized after the last reader/writer releases\n * it.\n *\n * @default false\n */\n autoFinalize?: boolean\n}\n\nexport interface Mortice {\n /**\n * Acquire a read lock. Multiple reads will occur simultaneously up to the\n * concurrency limit passed to the constructor.\n */\n readLock(options?: AbortOptions): Promise<Release>\n\n /**\n * Acquire a write lock. The write lock will wait for any in-flight reads to\n * complete, then prevent any further reads or writes until the lock is\n * released.\n */\n writeLock(options?: AbortOptions): Promise<Release>\n\n /**\n * Removes this mutex from the global state, after invoking this method it\n * cannot be used any more.\n */\n finalize(): void\n\n /**\n * If this is the main thread, the state of the read/write queue may be\n * inspected here\n */\n queue?: Queue\n}\n\nexport interface Release {\n (): void\n}\n\nconst defaultOptions = {\n name: 'lock',\n concurrency: Infinity,\n singleProcess: false,\n autoFinalize: false\n}\n\nexport default function createMortice (options?: MorticeOptions): Mortice {\n const opts: Required<MorticeOptions> = Object.assign({}, defaultOptions, options)\n\n return createMutex(opts.name, opts)\n}\n", "import { start, stop } from '@libp2p/interface'\nimport createMortice from 'mortice'\nimport { BlockPinnedError } from './errors.ts'\nimport type { Routing } from '@helia/interface'\nimport type { Blocks, Pair, DeleteManyBlocksProgressEvents, DeleteBlockProgressEvents, GetBlockProgressEvents, GetManyBlocksProgressEvents, PutManyBlocksProgressEvents, PutBlockProgressEvents, GetAllBlocksProgressEvents, GetOfflineOptions, SessionBlockstore } from '@helia/interface/blocks'\nimport type { Pins } from '@helia/interface/pins'\nimport type { AbortOptions, Startable } from '@libp2p/interface'\nimport type { Blockstore, InputPair } from 'interface-blockstore'\nimport type { Mortice } from 'mortice'\nimport type { CID } from 'multiformats/cid'\nimport type { ProgressOptions } from 'progress-events'\n\nexport interface BlockStorageInit {\n holdGcLock?: boolean\n}\n\nexport interface GetOptions extends AbortOptions {\n progress?(evt: Event): void\n}\n\n/**\n * BlockStorage is a hybrid blockstore that puts/gets blocks from a configured\n * blockstore (that may be on disk, s3, or something else). If the blocks are\n * not present Bitswap will be used to fetch them from network peers.\n */\nexport class BlockStorage implements Blocks, Startable {\n public lock: Mortice\n private readonly child: Blocks\n private readonly pins: Pins\n private readonly routing: Routing\n private started: boolean\n\n /**\n * Create a new BlockStorage\n */\n constructor (blockstore: Blocks, pins: Pins, routing: Routing, options: BlockStorageInit = {}) {\n this.child = blockstore\n this.pins = pins\n this.routing = routing\n this.lock = createMortice({\n singleProcess: options.holdGcLock\n })\n this.started = false\n }\n\n isStarted (): boolean {\n return this.started\n }\n\n async start (): Promise<void> {\n await start(this.child)\n this.started = true\n }\n\n async stop (): Promise<void> {\n await stop(this.child)\n this.started = false\n }\n\n unwrap (): Blockstore {\n return this.child\n }\n\n /**\n * Put a block to the underlying datastore\n */\n async put (cid: CID, block: Uint8Array, options: AbortOptions & ProgressOptions<PutBlockProgressEvents> = {}): Promise<CID> {\n options?.signal?.throwIfAborted()\n const releaseLock = await this.lock.readLock()\n\n try {\n return await this.child.put(cid, block, options)\n } finally {\n releaseLock()\n }\n }\n\n /**\n * Put a multiple blocks to the underlying datastore\n */\n async * putMany (blocks: Iterable<InputPair> | AsyncIterable<InputPair>, options: AbortOptions & ProgressOptions<PutManyBlocksProgressEvents> = {}): AsyncGenerator<CID> {\n options?.signal?.throwIfAborted()\n const releaseLock = await this.lock.readLock()\n\n try {\n yield * this.child.putMany(blocks, options)\n } finally {\n releaseLock()\n }\n }\n\n /**\n * Get a block by cid\n */\n async * get (cid: CID, options: GetOfflineOptions & AbortOptions & ProgressOptions<GetBlockProgressEvents> = {}): AsyncGenerator<Uint8Array> {\n options?.signal?.throwIfAborted()\n const releaseLock = await this.lock.readLock()\n\n try {\n yield * this.child.get(cid, options)\n } finally {\n releaseLock()\n }\n }\n\n /**\n * Get multiple blocks back from an (async) iterable of cids\n */\n async * getMany (cids: Iterable<CID> | AsyncIterable<CID>, options: GetOfflineOptions & AbortOptions & ProgressOptions<GetManyBlocksProgressEvents> = {}): AsyncGenerator<Pair> {\n options?.signal?.throwIfAborted()\n const releaseLock = await this.lock.readLock()\n\n try {\n yield * this.child.getMany(cids, options)\n } finally {\n releaseLock()\n }\n }\n\n /**\n * Delete a block from the blockstore\n */\n async delete (cid: CID, options: AbortOptions & ProgressOptions<DeleteBlockProgressEvents> = {}): Promise<void> {\n options?.signal?.throwIfAborted()\n const releaseLock = await this.lock.writeLock()\n\n try {\n if (await this.pins.isPinned(cid)) {\n throw new BlockPinnedError('Block was pinned - please unpin and try again')\n }\n\n // stop re-providing this CID if necessary\n await this.routing.cancelReprovide(cid, options)\n\n await this.child.delete(cid, options)\n } finally {\n releaseLock()\n }\n }\n\n /**\n * Delete multiple blocks from the blockstore\n */\n async * deleteMany (cids: Iterable<CID> | AsyncIterable<CID>, options: AbortOptions & ProgressOptions<DeleteManyBlocksProgressEvents> = {}): AsyncGenerator<CID> {\n options?.signal?.throwIfAborted()\n const releaseLock = await this.lock.writeLock()\n\n try {\n const storage = this\n\n yield * this.child.deleteMany((async function * (): AsyncGenerator<CID> {\n for await (const cid of cids) {\n if (await storage.pins.isPinned(cid)) {\n throw new BlockPinnedError('Block was pinned - please unpin and try again')\n }\n\n // stop re-providing this CID if necessary\n await storage.routing.cancelReprovide(cid, options)\n\n yield cid\n }\n }()), options)\n } finally {\n releaseLock()\n }\n }\n\n async has (cid: CID, options: AbortOptions = {}): Promise<boolean> {\n options?.signal?.throwIfAborted()\n const releaseLock = await this.lock.readLock()\n\n try {\n return await this.child.has(cid, options)\n } finally {\n releaseLock()\n }\n }\n\n async * getAll (options: AbortOptions & ProgressOptions<GetAllBlocksProgressEvents> = {}): AsyncGenerator<Pair> {\n options?.signal?.throwIfAborted()\n const releaseLock = await this.lock.readLock()\n\n try {\n yield * this.child.getAll(options)\n } finally {\n releaseLock()\n }\n }\n\n createSession (root: CID, options?: AbortOptions): SessionBlockstore {\n options?.signal?.throwIfAborted()\n return this.child.createSession(root, options)\n }\n}\n", "import { Key } from 'interface-datastore'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { InvalidDatastoreVersionError } from '../errors.ts'\nimport type { Datastore } from 'interface-datastore'\n\nconst DS_VERSION_KEY = new Key('/version')\nconst CURRENT_VERSION = 1\n\nexport async function assertDatastoreVersionIsCurrent (datastore: Datastore): Promise<void> {\n if (!(await datastore.has(DS_VERSION_KEY))) {\n await datastore.put(DS_VERSION_KEY, uint8ArrayFromString(`${CURRENT_VERSION}`))\n\n return\n }\n\n const buf = await datastore.get(DS_VERSION_KEY)\n const str = uint8ArrayToString(buf)\n const version = parseInt(str, 10)\n\n if (version !== CURRENT_VERSION) {\n // TODO: write migrations when we break compatibility - for an example, see https://github.com/ipfs/js-ipfs-repo/tree/master/packages/ipfs-repo-migrations\n throw new InvalidDatastoreVersionError('Invalid datastore version, a datastore migration may be required')\n }\n}\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\n/**\n * @param {Map<any, any>} map\n * @returns {null}\n */\nfunction mapEncoder (map) {\n for (const key of map.keys()) {\n if (typeof key !== 'string' || key.length === 0) {\n throw new Error('Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded')\n }\n }\n return null\n}\n\nconst _encodeOptions = {\n float64: true,\n typeEncoders: {\n Map: mapEncoder,\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 {import('cborg').TagDecodeControl} decode\n * @returns {CID}\n */\nfunction cidDecoder (decode) {\n const bytes = /** @type {Uint8Array} */ (decode())\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 {{ [tagNumber: number]: import('cborg').TagDecoder }} */\n tags: { [CID_CBOR_TAG]: cidDecoder }\n}\n\nexport const decodeOptions = {\n ..._decodeOptions,\n tags: { ..._decodeOptions.tags }\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", "/* eslint max-depth: [\"error\", 7] */\nimport { Token, Type } from 'cborg'\nimport * as cborgJson from 'cborg/json'\nimport { CID } from 'multiformats'\nimport { base64 } from 'multiformats/bases/base64'\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ByteView<T>} ByteView\n */\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ArrayBufferView<T>} ArrayBufferView\n */\n/**\n * @template T\n * @typedef {import('multiformats').ToString<T>} ToString\n */\n/**\n * @typedef {import('cborg/interface').DecodeTokenizer} DecodeTokenizer\n */\n\n/**\n * @template T\n * @param {ByteView<T> | ArrayBufferView<T>} buf\n * @returns {ByteView<T>}\n */\nfunction 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. Encoding a CID means replacing it with a `{\"/\":\"<CidString>}`\n * object as per the DAG-JSON spec.\n *\n * @param {any} obj\n * @returns {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 cidString = cid.toString()\n\n return [\n new Token(Type.map, Infinity, 1),\n new Token(Type.string, '/', 1), // key\n new Token(Type.string, cidString, cidString.length), // value\n new Token(Type.break, undefined, 1)\n ]\n}\n\n/**\n * bytesEncoder will receive all Uint8Arrays (and friends) during encode, it\n * needs to replace it with a `{\"/\":{\"bytes\":\"Base64ByteString\"}}` object as\n * per the DAG-JSON spec.\n *\n * @param {Uint8Array} bytes\n * @returns {Token[]|null}\n */\nfunction bytesEncoder (bytes) {\n const bytesString = base64.encode(bytes).slice(1) // no mbase prefix\n return [\n new Token(Type.map, Infinity, 1),\n new Token(Type.string, '/', 1), // key\n new Token(Type.map, Infinity, 1), // value\n new Token(Type.string, 'bytes', 5), // inner key\n new Token(Type.string, bytesString, bytesString.length), // inner value\n new Token(Type.break, undefined, 1),\n new Token(Type.break, undefined, 1)\n ]\n}\n\n/**\n * taBytesEncoder wraps bytesEncoder() but for the more exotic typed arrays so\n * that we access the underlying ArrayBuffer data\n *\n * @param {Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array|Float64Array|Uint8ClampedArray|BigInt64Array|BigUint64Array} obj\n * @returns {Token[]|null}\n */\nfunction taBytesEncoder (obj) {\n return bytesEncoder(new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))\n}\n\n/**\n * abBytesEncoder wraps bytesEncoder() but for plain ArrayBuffers\n *\n * @param {ArrayBuffer} ab\n * @returns {Token[]|null}\n */\nfunction abBytesEncoder (ab) {\n return bytesEncoder(new Uint8Array(ab))\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 // process with standard number encoder\n}\n\nconst encodeOptions = {\n typeEncoders: {\n Object: cidEncoder,\n Buffer: bytesEncoder,\n Uint8Array: bytesEncoder,\n Int8Array: taBytesEncoder,\n Uint16Array: taBytesEncoder,\n Int16Array: taBytesEncoder,\n Uint32Array: taBytesEncoder,\n Int32Array: taBytesEncoder,\n Float32Array: taBytesEncoder,\n Float64Array: taBytesEncoder,\n Uint8ClampedArray: taBytesEncoder,\n BigInt64Array: taBytesEncoder,\n BigUint64Array: taBytesEncoder,\n DataView: taBytesEncoder,\n ArrayBuffer: abBytesEncoder,\n undefined: undefinedEncoder,\n number: numberEncoder\n }\n}\n\n/**\n * @implements {DecodeTokenizer}\n */\nclass DagJsonTokenizer extends cborgJson.Tokenizer {\n /**\n * @param {Uint8Array} data\n * @param {object} [options]\n */\n constructor (data, options) {\n super(data, options)\n /** @type {Token[]} */\n this.tokenBuffer = []\n }\n\n /**\n * @returns {boolean}\n */\n done () {\n return this.tokenBuffer.length === 0 && super.done()\n }\n\n /**\n * @returns {Token}\n */\n _next () {\n if (this.tokenBuffer.length > 0) {\n // @ts-ignore https://github.com/Microsoft/TypeScript/issues/30406\n return this.tokenBuffer.pop()\n }\n return super.next()\n }\n\n /**\n * Implements rules outlined in https://github.com/ipld/specs/pull/356\n *\n * @returns {Token}\n */\n next () {\n const token = this._next()\n\n if (Type.equals(token.type, Type.map)) {\n const keyToken = this._next()\n if (Type.equals(keyToken.type, Type.string) && keyToken.value === '/') {\n const valueToken = this._next()\n if (Type.equals(valueToken.type, Type.string)) { // *must* be a CID\n const breakToken = this._next() // swallow the end-of-map token\n if (!Type.equals(breakToken.type, Type.break)) {\n throw new Error('Invalid encoded CID form')\n }\n this.tokenBuffer.push(valueToken) // CID.parse will pick this up after our tag token\n return new Token(Type.tag, 42, 0)\n }\n if (Type.equals(valueToken.type, Type.map)) {\n const innerKeyToken = this._next()\n if (Type.equals(innerKeyToken.type, Type.string) && innerKeyToken.value === 'bytes') {\n const innerValueToken = this._next()\n if (Type.equals(innerValueToken.type, Type.string)) { // *must* be Bytes\n for (let i = 0; i < 2; i++) {\n const breakToken = this._next() // swallow two end-of-map tokens\n if (!Type.equals(breakToken.type, Type.break)) {\n throw new Error('Invalid encoded Bytes form')\n }\n }\n const bytes = base64.decode(`m${innerValueToken.value}`)\n return new Token(Type.bytes, bytes, innerValueToken.value.length)\n }\n this.tokenBuffer.push(innerValueToken) // bail\n }\n this.tokenBuffer.push(innerKeyToken) // bail\n }\n this.tokenBuffer.push(valueToken) // bail\n }\n this.tokenBuffer.push(keyToken) // bail\n }\n return token\n }\n}\n\nconst decodeOptions = {\n allowIndefinite: false,\n allowUndefined: false,\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 {{ [tagNumber: number]: import('cborg').TagDecoder }} */\n tags: {\n // TAG(42)STRING(\"bafy...\") from the tokenizer, decode to get the string\n 42: (decode) => CID.parse(/** @type {string} */ (decode()))\n }\n}\n\nexport const name = 'dag-json'\nexport const code = 0x0129\n\n/**\n * @template T\n * @param {T} node\n * @returns {ByteView<T>}\n */\nexport const encode = (node) => cborgJson.encode(node, encodeOptions)\n\n/**\n * @template T\n * @param {ByteView<T> | ArrayBufferView<T>} data\n * @returns {T}\n */\nexport const decode = (data) => {\n const buf = toByteView(data)\n // the tokenizer is stateful so we need a single instance of it\n const options = Object.assign(decodeOptions, { tokenizer: new DagJsonTokenizer(buf, decodeOptions) })\n return cborgJson.decode(buf, options)\n}\n\n/**\n * @template T\n * @param {T} node\n * @returns {ToString<T>}\n */\nexport const format = (node) => utf8Decoder.decode(encode(node))\nexport { format as stringify }\nconst utf8Decoder = new TextDecoder()\n\n/**\n * @template T\n * @param {ToString<T>} data\n * @returns {T}\n */\nexport const parse = (data) => decode(utf8Encoder.encode(data))\nconst utf8Encoder = new TextEncoder()\n", "import { Type } from '../token.js'\nimport { encodeCustom } from '../encode.js'\nimport { encodeErrPrefix } from '../common.js'\nimport { asU8A, fromString } from '../byte-utils.js'\n\n/**\n * @typedef {import('../../interface.js').EncodeOptions} EncodeOptions\n * @typedef {import('../../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../token.js').Token} Token\n */\n\nclass JSONEncoder extends Array {\n constructor () {\n super()\n /** @type {{type:Type,elements:number}[]} */\n this.inRecursive = []\n }\n\n /**\n * @param {ByteWriter} buf\n */\n prefix (buf) {\n const recurs = this.inRecursive[this.inRecursive.length - 1]\n if (recurs) {\n if (Type.equals(recurs.type, Type.array)) {\n recurs.elements++\n if (recurs.elements !== 1) { // >first\n buf.push([44]) // ','\n }\n }\n if (Type.equals(recurs.type, Type.map)) {\n recurs.elements++\n if (recurs.elements !== 1) { // >first\n if (recurs.elements % 2 === 1) { // key\n buf.push([44]) // ','\n } else {\n buf.push([58]) // ':'\n }\n }\n }\n }\n }\n\n /**\n * @param {ByteWriter} buf\n * @param {Token} token\n */\n [Type.uint.major] (buf, token) {\n this.prefix(buf)\n const is = String(token.value)\n const isa = []\n for (let i = 0; i < is.length; i++) {\n isa[i] = is.charCodeAt(i)\n }\n buf.push(isa)\n }\n\n /**\n * @param {ByteWriter} buf\n * @param {Token} token\n */\n [Type.negint.major] (buf, token) {\n // @ts-ignore hack\n this[Type.uint.major](buf, token)\n }\n\n /**\n * @param {ByteWriter} _buf\n * @param {Token} _token\n */\n [Type.bytes.major] (_buf, _token) {\n throw new Error(`${encodeErrPrefix} unsupported type: Uint8Array`)\n }\n\n /**\n * @param {ByteWriter} buf\n * @param {Token} token\n */\n [Type.string.major] (buf, token) {\n this.prefix(buf)\n // buf.push(34) // '\"'\n // encodeUtf8(token.value, byts)\n // buf.push(34) // '\"'\n const byts = fromString(JSON.stringify(token.value))\n buf.push(byts.length > 32 ? asU8A(byts) : byts)\n }\n\n /**\n * @param {ByteWriter} buf\n * @param {Token} _token\n */\n [Type.array.major] (buf, _token) {\n this.prefix(buf)\n this.inRecursive.push({ type: Type.array, elements: 0 })\n buf.push([91]) // '['\n }\n\n /**\n * @param {ByteWriter} buf\n * @param {Token} _token\n */\n [Type.map.major] (buf, _token) {\n this.prefix(buf)\n this.inRecursive.push({ type: Type.map, elements: 0 })\n buf.push([123]) // '{'\n }\n\n /**\n * @param {ByteWriter} _buf\n * @param {Token} _token\n */\n [Type.tag.major] (_buf, _token) {}\n\n /**\n * @param {ByteWriter} buf\n * @param {Token} token\n */\n [Type.float.major] (buf, token) {\n if (token.type.name === 'break') {\n const recurs = this.inRecursive.pop()\n if (recurs) {\n if (Type.equals(recurs.type, Type.array)) {\n buf.push([93]) // ']'\n } else if (Type.equals(recurs.type, Type.map)) {\n buf.push([125]) // '}'\n /* c8 ignore next 3 */\n } else {\n throw new Error('Unexpected recursive type; this should not happen!')\n }\n return\n }\n /* c8 ignore next 2 */\n throw new Error('Unexpected break; this should not happen!')\n }\n if (token.value === undefined) {\n throw new Error(`${encodeErrPrefix} unsupported type: undefined`)\n }\n\n this.prefix(buf)\n if (token.type.name === 'true') {\n buf.push([116, 114, 117, 101]) // 'true'\n return\n } else if (token.type.name === 'false') {\n buf.push([102, 97, 108, 115, 101]) // 'false'\n return\n } else if (token.type.name === 'null') {\n buf.push([110, 117, 108, 108]) // 'null'\n return\n }\n\n // number\n const is = String(token.value)\n const isa = []\n let dp = false\n for (let i = 0; i < is.length; i++) {\n isa[i] = is.charCodeAt(i)\n if (!dp && (isa[i] === 46 || isa[i] === 101 || isa[i] === 69)) { // '[.eE]'\n dp = true\n }\n }\n if (!dp) { // need a decimal point for floats\n isa.push(46) // '.'\n isa.push(48) // '0'\n }\n buf.push(isa)\n }\n}\n\n// The below code is mostly taken and modified from https://github.com/feross/buffer\n// Licensed MIT. Copyright (c) Feross Aboukhadijeh\n// function encodeUtf8 (string, byts) {\n// let codePoint\n// const length = string.length\n// let leadSurrogate = null\n\n// for (let i = 0; i < length; ++i) {\n// codePoint = string.charCodeAt(i)\n\n// // is surrogate component\n// if (codePoint > 0xd7ff && codePoint < 0xe000) {\n// // last char was a lead\n// if (!leadSurrogate) {\n// // no lead yet\n// /* c8 ignore next 9 */\n// if (codePoint > 0xdbff) {\n// // unexpected trail\n// byts.push(0xef, 0xbf, 0xbd)\n// continue\n// } else if (i + 1 === length) {\n// // unpaired lead\n// byts.push(0xef, 0xbf, 0xbd)\n// continue\n// }\n\n// // valid lead\n// leadSurrogate = codePoint\n\n// continue\n// }\n\n// // 2 leads in a row\n// /* c8 ignore next 5 */\n// if (codePoint < 0xdc00) {\n// byts.push(0xef, 0xbf, 0xbd)\n// leadSurrogate = codePoint\n// continue\n// }\n\n// // valid surrogate pair\n// codePoint = (leadSurrogate - 0xd800 << 10 | codePoint - 0xdc00) + 0x10000\n// /* c8 ignore next 4 */\n// } else if (leadSurrogate) {\n// // valid bmp char, but last char was a lead\n// byts.push(0xef, 0xbf, 0xbd)\n// }\n\n// leadSurrogate = null\n\n// // encode utf8\n// if (codePoint < 0x80) {\n// // special JSON escapes\n// switch (codePoint) {\n// case 8: // '\\b'\n// byts.push(92, 98) // '\\\\b'\n// continue\n// case 9: // '\\t'\n// byts.push(92, 116) // '\\\\t'\n// continue\n// case 10: // '\\n'\n// byts.push(92, 110) // '\\\\n'\n// continue\n// case 12: // '\\f'\n// byts.push(92, 102) // '\\\\f'\n// continue\n// case 13: // '\\r'\n// byts.push(92, 114) // '\\\\r'\n// continue\n// case 34: // '\"'\n// byts.push(92, 34) // '\\\\\"'\n// continue\n// case 92: // '\\\\'\n// byts.push(92, 92) // '\\\\\\\\'\n// continue\n// }\n\n// byts.push(codePoint)\n// } else if (codePoint < 0x800) {\n// /* c8 ignore next 1 */\n// byts.push(\n// codePoint >> 0x6 | 0xc0,\n// codePoint & 0x3f | 0x80\n// )\n// } else if (codePoint < 0x10000) {\n// /* c8 ignore next 1 */\n// byts.push(\n// codePoint >> 0xc | 0xe0,\n// codePoint >> 0x6 & 0x3f | 0x80,\n// codePoint & 0x3f | 0x80\n// )\n// /* c8 ignore next 9 */\n// } else if (codePoint < 0x110000) {\n// byts.push(\n// codePoint >> 0x12 | 0xf0,\n// codePoint >> 0xc & 0x3f | 0x80,\n// codePoint >> 0x6 & 0x3f | 0x80,\n// codePoint & 0x3f | 0x80\n// )\n// } else {\n// /* c8 ignore next 2 */\n// throw new Error('Invalid code point')\n// }\n// }\n// }\n\n/**\n * @param {(Token|Token[])[]} e1\n * @param {(Token|Token[])[]} e2\n * @returns {number}\n */\nfunction mapSorter (e1, e2) {\n if (Array.isArray(e1[0]) || Array.isArray(e2[0])) {\n throw new Error(`${encodeErrPrefix} complex map keys are not supported`)\n }\n const keyToken1 = e1[0]\n const keyToken2 = e2[0]\n if (keyToken1.type !== Type.string || keyToken2.type !== Type.string) {\n throw new Error(`${encodeErrPrefix} non-string map keys are not supported`)\n }\n if (keyToken1 < keyToken2) {\n return -1\n }\n if (keyToken1 > keyToken2) {\n return 1\n }\n /* c8 ignore next 1 */\n throw new Error(`${encodeErrPrefix} unexpected duplicate map keys, this is not supported`)\n}\n\nconst defaultEncodeOptions = { addBreakTokens: true, mapSorter }\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 // @ts-ignore TokenTypeEncoder[] requires compareTokens() on each encoder, we don't use them here\n return encodeCustom(data, new JSONEncoder(), options)\n}\n\nexport { encode }\n", "import { decode as _decode, decodeFirst as _decodeFirst } from '../decode.js'\nimport { Token, Type } from '../token.js'\nimport { decodeCodePointsArray } from '../byte-utils.js'\nimport { decodeErrPrefix } from '../common.js'\n\n/**\n * @typedef {import('../../interface.js').DecodeOptions} DecodeOptions\n * @typedef {import('../../interface.js').DecodeTokenizer} DecodeTokenizer\n */\n\n/**\n * @implements {DecodeTokenizer}\n */\nclass Tokenizer {\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 /** @type {string[]} */\n this.modeStack = ['value']\n this.lastToken = ''\n }\n\n pos () {\n return this._pos\n }\n\n /**\n * @returns {boolean}\n */\n done () {\n return this._pos >= this.data.length\n }\n\n /**\n * @returns {number}\n */\n ch () {\n return this.data[this._pos]\n }\n\n /**\n * @returns {string}\n */\n currentMode () {\n return this.modeStack[this.modeStack.length - 1]\n }\n\n skipWhitespace () {\n let c = this.ch()\n // @ts-ignore\n while (c === 32 /* ' ' */ || c === 9 /* '\\t' */ || c === 13 /* '\\r' */ || c === 10 /* '\\n' */) {\n c = this.data[++this._pos]\n }\n }\n\n /**\n * @param {number[]} str\n */\n expect (str) {\n if (this.data.length - this._pos < str.length) {\n throw new Error(`${decodeErrPrefix} unexpected end of input at position ${this._pos}`)\n }\n for (let i = 0; i < str.length; i++) {\n if (this.data[this._pos++] !== str[i]) {\n throw new Error(`${decodeErrPrefix} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...str)}'`)\n }\n }\n }\n\n parseNumber () {\n const startPos = this._pos\n let negative = false\n let float = false\n\n /**\n * @param {number[]} chars\n */\n const swallow = (chars) => {\n while (!this.done()) {\n const ch = this.ch()\n if (chars.includes(ch)) {\n this._pos++\n } else {\n break\n }\n }\n }\n\n // lead\n if (this.ch() === 45) { // '-'\n negative = true\n this._pos++\n }\n if (this.ch() === 48) { // '0'\n this._pos++\n if (this.ch() === 46) { // '.'\n this._pos++\n float = true\n } else {\n return new Token(Type.uint, 0, this._pos - startPos)\n }\n }\n swallow([48, 49, 50, 51, 52, 53, 54, 55, 56, 57]) // DIGIT\n if (negative && this._pos === startPos + 1) {\n throw new Error(`${decodeErrPrefix} unexpected token at position ${this._pos}`)\n }\n if (!this.done() && this.ch() === 46) { // '.'\n if (float) {\n throw new Error(`${decodeErrPrefix} unexpected token at position ${this._pos}`)\n }\n float = true\n this._pos++\n swallow([48, 49, 50, 51, 52, 53, 54, 55, 56, 57]) // DIGIT\n }\n if (!this.done() && (this.ch() === 101 || this.ch() === 69)) { // '[eE]'\n float = true\n this._pos++\n if (!this.done() && (this.ch() === 43 || this.ch() === 45)) { // '+', '-'\n this._pos++\n }\n swallow([48, 49, 50, 51, 52, 53, 54, 55, 56, 57]) // DIGIT\n }\n // @ts-ignore\n const numStr = String.fromCharCode.apply(null, this.data.subarray(startPos, this._pos))\n const num = parseFloat(numStr)\n if (float) {\n return new Token(Type.float, num, this._pos - startPos)\n }\n if (this.options.allowBigInt !== true || Number.isSafeInteger(num)) {\n return new Token(num >= 0 ? Type.uint : Type.negint, num, this._pos - startPos)\n }\n return new Token(num >= 0 ? Type.uint : Type.negint, BigInt(numStr), this._pos - startPos)\n }\n\n /**\n * @returns {Token}\n */\n parseString () {\n /* c8 ignore next 4 */\n if (this.ch() !== 34) { // '\"'\n // this would be a programming error\n throw new Error(`${decodeErrPrefix} unexpected character at position ${this._pos}; this shouldn't happen`)\n }\n this._pos++\n\n // check for simple fast-path, all printable ascii, no escapes\n // >0x10000 elements may fail fn.apply() (http://stackoverflow.com/a/22747272/680742)\n for (let i = this._pos, l = 0; i < this.data.length && l < 0x10000; i++, l++) {\n const ch = this.data[i]\n if (ch === 92 || ch < 32 || ch >= 128) { // '\\', ' ', control-chars or non-trivial\n break\n }\n if (ch === 34) { // '\"'\n // @ts-ignore\n const str = String.fromCharCode.apply(null, this.data.subarray(this._pos, i))\n this._pos = i + 1\n return new Token(Type.string, str, l)\n }\n }\n\n const startPos = this._pos\n const chars = []\n\n const readu4 = () => {\n if (this._pos + 4 >= this.data.length) {\n throw new Error(`${decodeErrPrefix} unexpected end of unicode escape sequence at position ${this._pos}`)\n }\n let u4 = 0\n for (let i = 0; i < 4; i++) {\n let ch = this.ch()\n if (ch >= 48 && ch <= 57) { // '0' && '9'\n ch -= 48\n } else if (ch >= 97 && ch <= 102) { // 'a' && 'f'\n ch = ch - 97 + 10\n } else if (ch >= 65 && ch <= 70) { // 'A' && 'F'\n ch = ch - 65 + 10\n } else {\n throw new Error(`${decodeErrPrefix} unexpected unicode escape character at position ${this._pos}`)\n }\n u4 = u4 * 16 + ch\n this._pos++\n }\n return u4\n }\n\n // mostly taken from feross/buffer and adjusted to fit\n const readUtf8Char = () => {\n const firstByte = this.ch()\n let codePoint = null\n /* c8 ignore next 1 */\n let bytesPerSequence = (firstByte > 0xef) ? 4 : (firstByte > 0xdf) ? 3 : (firstByte > 0xbf) ? 2 : 1\n\n if (this._pos + bytesPerSequence > this.data.length) {\n throw new Error(`${decodeErrPrefix} unexpected unicode sequence at position ${this._pos}`)\n }\n\n let secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n /* c8 ignore next 6 */\n // this case is dealt with by the caller function\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = this.data[this._pos + 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 = this.data[this._pos + 1]\n thirdByte = this.data[this._pos + 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 = this.data[this._pos + 1]\n thirdByte = this.data[this._pos + 2]\n fourthByte = this.data[this._pos + 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 /* 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 chars.push(codePoint >>> 10 & 0x3ff | 0xd800)\n codePoint = 0xdc00 | codePoint & 0x3ff\n }\n\n chars.push(codePoint)\n this._pos += bytesPerSequence\n }\n\n // TODO: could take the approach of a quick first scan for special chars like encoding/json/decode.go#unquoteBytes\n // and converting all of the ascii chars from the base array in bulk\n while (!this.done()) {\n const ch = this.ch()\n let ch1\n switch (ch) {\n case 92: // '\\'\n this._pos++\n if (this.done()) {\n throw new Error(`${decodeErrPrefix} unexpected string termination at position ${this._pos}`)\n }\n ch1 = this.ch()\n this._pos++\n switch (ch1) {\n case 34: // '\"'\n case 39: // '\\''\n case 92: // '\\'\n case 47: // '/'\n chars.push(ch1)\n break\n case 98: // 'b'\n chars.push(8)\n break\n case 116: // 't'\n chars.push(9)\n break\n case 110: // 'n'\n chars.push(10)\n break\n case 102: // 'f'\n chars.push(12)\n break\n case 114: // 'r'\n chars.push(13)\n break\n case 117: // 'u'\n chars.push(readu4())\n break\n default:\n throw new Error(`${decodeErrPrefix} unexpected string escape character at position ${this._pos}`)\n }\n break\n case 34: // '\"'\n this._pos++\n return new Token(Type.string, decodeCodePointsArray(chars), this._pos - startPos)\n default:\n if (ch < 32) { // ' '\n throw new Error(`${decodeErrPrefix} invalid control character at position ${this._pos}`)\n } else if (ch < 0x80) {\n chars.push(ch)\n this._pos++\n } else {\n readUtf8Char()\n }\n }\n }\n\n throw new Error(`${decodeErrPrefix} unexpected end of string at position ${this._pos}`)\n }\n\n /**\n * @returns {Token}\n */\n parseValue () {\n switch (this.ch()) {\n case 123: // '{'\n this.modeStack.push('obj-start')\n this._pos++\n return new Token(Type.map, Infinity, 1)\n case 91: // '['\n this.modeStack.push('array-start')\n this._pos++\n return new Token(Type.array, Infinity, 1)\n case 34: { // '\"'\n return this.parseString()\n }\n case 110: // 'n' / null\n this.expect([110, 117, 108, 108]) // 'null'\n return new Token(Type.null, null, 4)\n case 102: // 'f' / // false\n this.expect([102, 97, 108, 115, 101]) // 'false'\n return new Token(Type.false, false, 5)\n case 116: // 't' / // true\n this.expect([116, 114, 117, 101]) // 'true'\n return new Token(Type.true, true, 4)\n case 45: // '-'\n case 48: // '0'\n case 49: // '1'\n case 50: // '2'\n case 51: // '3'\n case 52: // '4'\n case 53: // '5'\n case 54: // '6'\n case 55: // '7'\n case 56: // '8'\n case 57: // '9'\n return this.parseNumber()\n default:\n throw new Error(`${decodeErrPrefix} unexpected character at position ${this._pos}`)\n }\n }\n\n /**\n * @returns {Token}\n */\n next () {\n this.skipWhitespace()\n switch (this.currentMode()) {\n case 'value':\n this.modeStack.pop()\n return this.parseValue()\n case 'array-value': {\n this.modeStack.pop()\n if (this.ch() === 93) { // ']'\n this._pos++\n this.skipWhitespace()\n return new Token(Type.break, undefined, 1)\n }\n if (this.ch() !== 44) { // ','\n throw new Error(`${decodeErrPrefix} unexpected character at position ${this._pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`)\n }\n this._pos++\n this.modeStack.push('array-value')\n this.skipWhitespace()\n return this.parseValue()\n }\n case 'array-start': {\n this.modeStack.pop()\n if (this.ch() === 93) { // ']'\n this._pos++\n this.skipWhitespace()\n return new Token(Type.break, undefined, 1)\n }\n this.modeStack.push('array-value')\n this.skipWhitespace()\n return this.parseValue()\n }\n // @ts-ignore\n case 'obj-key':\n if (this.ch() === 125) { // '}'\n this.modeStack.pop()\n this._pos++\n this.skipWhitespace()\n return new Token(Type.break, undefined, 1)\n }\n if (this.ch() !== 44) { // ','\n throw new Error(`${decodeErrPrefix} unexpected character at position ${this._pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`)\n }\n this._pos++\n this.skipWhitespace()\n case 'obj-start': { // eslint-disable-line no-fallthrough\n this.modeStack.pop()\n if (this.ch() === 125) { // '}'\n this._pos++\n this.skipWhitespace()\n return new Token(Type.break, undefined, 1)\n }\n const token = this.parseString()\n this.skipWhitespace()\n if (this.ch() !== 58) { // ':'\n throw new Error(`${decodeErrPrefix} unexpected character at position ${this._pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`)\n }\n this._pos++\n this.modeStack.push('obj-value')\n return token\n }\n case 'obj-value': {\n this.modeStack.pop()\n this.modeStack.push('obj-key')\n this.skipWhitespace()\n return this.parseValue()\n }\n /* c8 ignore next 2 */\n default:\n throw new Error(`${decodeErrPrefix} unexpected parse state at position ${this._pos}; this shouldn't happen`)\n }\n }\n}\n\n/**\n * @param {Uint8Array} data\n * @param {DecodeOptions} [options]\n * @returns {any}\n */\nfunction decode (data, options) {\n options = Object.assign({ tokenizer: new Tokenizer(data, options) }, options)\n return _decode(data, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {DecodeOptions} [options]\n * @returns {[any, Uint8Array]}\n */\nfunction decodeFirst (data, options) {\n options = Object.assign({ tokenizer: new Tokenizer(data, options) }, options)\n return _decodeFirst(data, options)\n}\n\nexport { decode, decodeFirst, Tokenizer }\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", "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", "export function isPromise <T> (p?: any): p is Promise<T> {\n return p?.then != null\n}\n", "import { UnknownCodecError } from '@helia/interface'\nimport * as dagCbor from '@ipld/dag-cbor'\nimport * as dagJson from '@ipld/dag-json'\nimport * as dagPb from '@ipld/dag-pb'\nimport * as json from 'multiformats/codecs/json'\nimport * as raw from 'multiformats/codecs/raw'\nimport { isPromise } from './is-promise.ts'\nimport type { CodecLoader } from '@helia/interface'\nimport type { BlockCodec } from 'multiformats/codecs/interface'\n\nexport function getCodec (initialCodecs: Array<BlockCodec<any, any>> = [], loadCodec?: CodecLoader): CodecLoader {\n const codecs: Record<number, BlockCodec<any, any>> = {\n [dagPb.code]: dagPb,\n [raw.code]: raw,\n [dagCbor.code]: dagCbor,\n [dagJson.code]: dagJson,\n [json.code]: json\n }\n\n initialCodecs.forEach(codec => {\n codecs[codec.code] = codec\n })\n\n return async (code) => {\n let codec = codecs[code]\n\n if (codec == null && loadCodec != null) {\n const res = loadCodec(code)\n\n if (isPromise(res)) {\n codec = await res\n } else {\n codec = res\n }\n\n codecs[codec.code] = codec\n }\n\n if (codec != null) {\n return codec\n }\n\n throw new UnknownCodecError(`Could not load codec for ${code}`)\n }\n}\n", "import { UnknownCryptoError } from '@helia/interface'\nimport { ecdsaCrypto, ed25519Crypto, rsaCrypto } from '@ipshipyard/crypto'\nimport { isPromise } from './is-promise.ts'\nimport type { CryptoLoader } from '@helia/interface'\nimport type { Crypto } from '@ipshipyard/crypto'\n\nexport function getCrypto (initialCryptos: Array<Crypto> = [], loadCrypto?: CryptoLoader): CryptoLoader {\n const cryptos: Record<string | number, Crypto> = {}\n\n initialCryptos = [\n ecdsaCrypto(),\n ed25519Crypto(),\n rsaCrypto(),\n ...initialCryptos\n ]\n\n initialCryptos.forEach(crypto => {\n cryptos[crypto.type] = crypto\n cryptos[crypto.code] = crypto\n })\n\n return async (nameOrCode) => {\n let crypto = cryptos[nameOrCode]\n\n if (crypto == null && loadCrypto != null) {\n const res = loadCrypto(nameOrCode)\n\n if (isPromise(res)) {\n crypto = await res\n } else {\n crypto = res\n }\n\n cryptos[crypto.type] = crypto\n cryptos[crypto.code] = crypto\n }\n\n if (crypto != null) {\n return crypto\n }\n\n throw new UnknownCryptoError(`Could not load crypto for ${crypto}`)\n }\n}\n", "import { UnknownHashAlgorithmError } from '@helia/interface'\nimport { identity } from 'multiformats/hashes/identity'\nimport { sha256, sha512 } from 'multiformats/hashes/sha2'\nimport { isPromise } from './is-promise.ts'\nimport type { HasherLoader } from '@helia/interface'\nimport type { MultihashHasher } from 'multiformats/hashes/interface'\n\nexport function getHasher (initialHashers: MultihashHasher[] = [], loadHasher?: HasherLoader): HasherLoader {\n const hashers: Record<number, MultihashHasher> = {\n [sha256.code]: sha256,\n [sha512.code]: sha512,\n [identity.code]: identity\n }\n\n initialHashers.forEach(hasher => {\n hashers[hasher.code] = hasher\n })\n\n return async (code) => {\n let hasher = hashers[code]\n\n if (hasher == null && loadHasher != null) {\n const res = loadHasher(code)\n\n if (isPromise(res)) {\n hasher = await res\n } else {\n hasher = res\n }\n\n hashers[hasher.code] = hasher\n }\n\n if (hasher != null) {\n return hasher\n }\n\n throw new UnknownHashAlgorithmError(`No hasher configured for multihash code 0x${code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`)\n }\n}\n", "import { NotFoundError } from 'interface-store'\nimport { BaseBlockstore } from './base.ts'\nimport type { AbortOptions } from 'abort-error'\nimport type { Blockstore, Pair } from 'interface-blockstore'\nimport type { CID } from 'multiformats/cid'\n\n// https://github.com/multiformats/multicodec/blob/d06fc6194710e8909bac64273c43f16b56ca4c34/table.csv#L2\nconst IDENTITY_CODEC = 0x00\n\nclass IdentityHashDigestTooLongError extends Error {\n static name = 'IdentityHashDigestTooLongError'\n name = 'IdentityHashDigestTooLongError'\n}\n\nexport interface IdentityBlockstoreInit {\n maxDigestLength?: number\n}\n\nexport class IdentityBlockstore extends BaseBlockstore {\n private readonly child?: Blockstore\n private readonly maxDigestLength?: number\n\n constructor (child?: Blockstore, init?: IdentityBlockstoreInit) {\n super()\n\n this.child = child\n this.maxDigestLength = init?.maxDigestLength\n }\n\n put (key: CID, block: Uint8Array | Iterable<Uint8Array> | AsyncIterable<Uint8Array>, options?: AbortOptions): CID | Promise<CID> {\n if (key.multihash.code === IDENTITY_CODEC) {\n if (this.maxDigestLength != null && key.multihash.digest.byteLength > this.maxDigestLength) {\n throw new IdentityHashDigestTooLongError(`Identity digest too long - ${key.multihash.digest.byteLength} > this.maxDigestLength`)\n }\n\n options?.signal?.throwIfAborted()\n return key\n }\n\n if (this.child == null) {\n options?.signal?.throwIfAborted()\n return key\n }\n\n return this.child.put(key, block, options)\n }\n\n async * get (key: CID, options?: AbortOptions): AsyncGenerator<Uint8Array> {\n if (key.multihash.code === IDENTITY_CODEC) {\n if (this.maxDigestLength != null && key.multihash.digest.byteLength > this.maxDigestLength) {\n throw new IdentityHashDigestTooLongError(`Identity digest too long - ${key.multihash.digest.byteLength} > this.maxDigestLength`)\n }\n\n options?.signal?.throwIfAborted()\n yield key.multihash.digest\n return\n }\n\n if (this.child == null) {\n options?.signal?.throwIfAborted()\n throw new NotFoundError()\n }\n\n yield * this.child.get(key, options)\n }\n\n has (key: CID, options?: AbortOptions): boolean | Promise<boolean> {\n if (key.multihash.code === IDENTITY_CODEC) {\n if (this.maxDigestLength != null && key.multihash.digest.byteLength > this.maxDigestLength) {\n throw new IdentityHashDigestTooLongError(`Identity digest too long - ${key.multihash.digest.byteLength} > this.maxDigestLength`)\n }\n\n options?.signal?.throwIfAborted()\n return true\n }\n\n if (this.child == null) {\n options?.signal?.throwIfAborted()\n return false\n }\n\n return this.child.has(key, options)\n }\n\n delete (key: CID, options?: AbortOptions): void | Promise<void> {\n if (key.code === IDENTITY_CODEC) {\n if (this.maxDigestLength != null && key.multihash.digest.byteLength > this.maxDigestLength) {\n throw new IdentityHashDigestTooLongError(`Identity digest too long - ${key.multihash.digest.byteLength} > this.maxDigestLength`)\n }\n\n options?.signal?.throwIfAborted()\n return\n }\n\n if (this.child != null) {\n return this.child.delete(key, options)\n }\n }\n\n async * getAll (options?: AbortOptions): AsyncGenerator<Pair> {\n if (this.child != null) {\n yield * this.child.getAll(options)\n }\n\n options?.signal?.throwIfAborted()\n }\n}\n", "/**\n * @packageDocumentation\n *\n * Calls a function for each value in an (async)iterable.\n *\n * The function can be sync or async.\n *\n * Async functions can be awaited on so may slow down processing of the (async)iterable.\n *\n * @example\n *\n * ```javascript\n * import each from 'it-foreach'\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 * // prints [0, 0], [1, 1], [2, 2], [3, 3], [4, 4]\n * const arr = drain(\n * each(values, console.info)\n * )\n * ```\n *\n * Async sources and callbacks must be awaited:\n *\n * ```javascript\n * import each from 'it-foreach'\n * import drain from 'it-drain'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * // prints [0, 0], [1, 1], [2, 2], [3, 3], [4, 4]\n * const arr = await drain(\n * each(values(), console.info)\n * )\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\nfunction isPromise <T = unknown> (thing: any): thing is Promise<T> {\n return thing?.then != null\n}\n\n/**\n * Invokes the passed function for each item in an iterable\n */\nfunction forEach <T> (source: Iterable<T>, fn: (thing: T, index: number) => Promise<void>): AsyncGenerator<T, void, undefined>\nfunction forEach <T> (source: Iterable<T>, fn: (thing: T, index: number) => void): Generator<T, void, undefined>\nfunction forEach <T> (source: Iterable<T> | AsyncIterable<T>, fn: (thing: T, index: number) => void | Promise<void>): AsyncGenerator<T, void, undefined>\nfunction forEach <T> (source: Iterable<T> | AsyncIterable<T>, fn: (thing: T, index: number) => void | Promise<void>): AsyncGenerator<T, void, undefined> | Generator<T, void, undefined> {\n let index = 0\n\n if (isAsyncIterable(source)) {\n return (async function * () {\n for await (const val of source) {\n const res = fn(val, index++)\n\n if (isPromise(res)) {\n await res\n }\n\n yield val\n }\n })()\n }\n\n // if fn 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 = fn(value, index++)\n\n if (typeof res?.then === 'function') {\n return (async function * () {\n await res\n yield value\n\n for (const val of peekable) {\n const res = fn(val, index++)\n\n if (isPromise(res)) {\n await res\n }\n\n yield val\n }\n })()\n }\n\n const func = fn as (val: T, index: number) => void\n\n return (function * () {\n yield value\n\n for (const val of peekable) {\n func(val, index++)\n yield val\n }\n })()\n}\n\nexport default forEach\n", "import { InvalidMultihashError, InvalidParametersError, setMaxListeners } from '@libp2p/interface'\nimport { anySignal } from 'any-signal'\nimport { IdentityBlockstore } from 'blockstore-core/identity'\nimport filter from 'it-filter'\nimport forEach from 'it-foreach'\nimport { CustomProgressEvent } from 'progress-events'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { BlockNotFoundWhileOfflineError, InvalidConfigurationError, LoadBlockFailedError } from '../errors.ts'\nimport { isPromise } from './is-promise.ts'\nimport type { HasherLoader } from '@helia/interface'\nimport type { BlockBroker, Pair, DeleteManyBlocksProgressEvents, DeleteBlockProgressEvents, GetBlockProgressEvents, GetManyBlocksProgressEvents, PutManyBlocksProgressEvents, PutBlockProgressEvents, GetAllBlocksProgressEvents, GetOfflineOptions, BlockRetrievalOptions } from '@helia/interface/blocks'\nimport type { AbortOptions, ComponentLogger, Logger, LoggerOptions } from '@libp2p/interface'\nimport type { Blockstore, InputPair } from 'interface-blockstore'\nimport type { CID } from 'multiformats/cid'\nimport type { MultihashDigest, MultihashHasher } from 'multiformats/hashes/interface'\nimport type { ProgressEvent, ProgressOptions } from 'progress-events'\n\nexport interface StorageComponents<Broker extends BlockBroker<ProgressEvent<any, any>, ProgressEvent<any, any>>> {\n blockstore: Blockstore\n logger: ComponentLogger\n blockBrokers: Broker[]\n getHasher: HasherLoader\n}\n\nexport interface StorageInit {\n maxIdentityHashDigestLength?: number\n}\n\nconst DEFAULT_MAX_IDENTITY_HASH_DIGEST_LENGTH = 128\n\nexport class Storage <Broker extends BlockBroker<ProgressEvent<any, any>, ProgressEvent<any, any>>> implements Blockstore {\n protected readonly child: Blockstore\n protected readonly getHasher: HasherLoader\n protected log: Logger\n protected readonly logger: ComponentLogger\n protected readonly blockBrokers: Broker[]\n\n /**\n * Create a new BlockStorage\n */\n constructor (components: StorageComponents<Broker>, init: StorageInit = {}) {\n this.log = components.logger.forComponent('helia:networked-storage')\n this.logger = components.logger\n this.blockBrokers = components.blockBrokers\n this.child = new IdentityBlockstore(components.blockstore, {\n maxDigestLength: init.maxIdentityHashDigestLength ?? DEFAULT_MAX_IDENTITY_HASH_DIGEST_LENGTH\n })\n this.getHasher = components.getHasher\n }\n\n /**\n * Put a block to the underlying datastore\n */\n async put (cid: CID, block: Uint8Array, options: AbortOptions & ProgressOptions<PutBlockProgressEvents> = {}): Promise<CID> {\n if (await this.child.has(cid, options)) {\n options.onProgress?.(new CustomProgressEvent<CID>('blocks:put:duplicate', cid))\n return cid\n }\n\n options.onProgress?.(new CustomProgressEvent<CID>('blocks:put:providers:notify', cid))\n\n await Promise.all(\n this.blockBrokers.map(async broker => broker.announce?.(cid, options))\n )\n\n options.onProgress?.(new CustomProgressEvent<CID>('blocks:put:blockstore:put', cid))\n\n return this.child.put(cid, block, options)\n }\n\n /**\n * Put a multiple blocks to the underlying datastore\n */\n async * putMany (blocks: Iterable<InputPair> | AsyncIterable<InputPair>, options: AbortOptions & ProgressOptions<PutManyBlocksProgressEvents> = {}): AsyncGenerator<CID> {\n const missingBlocks = filter(blocks, async ({ cid }): Promise<boolean> => {\n const has = await this.child.has(cid, options)\n\n if (has) {\n options.onProgress?.(new CustomProgressEvent<CID>('blocks:put-many:duplicate', cid))\n }\n\n return !has\n })\n\n const notifyEach = forEach(missingBlocks, async ({ cid }): Promise<void> => {\n options.onProgress?.(new CustomProgressEvent<CID>('blocks:put-many:providers:notify', cid))\n await Promise.all(\n this.blockBrokers.map(async broker => broker.announce?.(cid, options))\n )\n })\n\n options.onProgress?.(new CustomProgressEvent('blocks:put-many:blockstore:put-many'))\n yield * this.child.putMany(notifyEach, options)\n }\n\n /**\n * Get a block by cid\n */\n async * get (cid: CID, options: GetOfflineOptions & AbortOptions & ProgressOptions<GetBlockProgressEvents> = {}): AsyncGenerator<Uint8Array> {\n const has = await this.child.has(cid, options)\n const offline = options.offline === true\n\n if (!has) {\n if (offline) {\n throw new BlockNotFoundWhileOfflineError('The block was present in the blockstore and the node is running offline so cannot fetch it')\n }\n\n const hasher = await this.getHasher(cid.multihash.code)\n options?.signal?.throwIfAborted()\n\n // we do not have the block locally, get it from a block provider\n\n options.onProgress?.(new CustomProgressEvent<CID>('blocks:get:providers:get', cid))\n const block = await raceBlockRetrievers(cid, this.blockBrokers, hasher, {\n ...options,\n log: this.log\n })\n options.onProgress?.(new CustomProgressEvent<CID>('blocks:get:blockstore:put', cid))\n await this.child.put(cid, block, options)\n\n // notify other block providers of the new block\n options.onProgress?.(new CustomProgressEvent<CID>('blocks:get:providers:notify', cid))\n await Promise.all(\n this.blockBrokers.map(async broker => broker.announce?.(cid, options))\n )\n\n yield block\n return\n }\n\n options.onProgress?.(new CustomProgressEvent<CID>('blocks:get:blockstore:get', cid))\n\n yield * this.child.get(cid, options)\n }\n\n /**\n * Get multiple blocks back from an (async) iterable of cids\n */\n async * getMany (cids: Iterable<CID> | AsyncIterable<CID>, options: GetOfflineOptions & AbortOptions & ProgressOptions<GetManyBlocksProgressEvents> = {}): AsyncGenerator<Pair> {\n options.onProgress?.(new CustomProgressEvent('blocks:get-many:blockstore:get-many'))\n\n yield * this.child.getMany(forEach(cids, async (cid): Promise<void> => {\n const has = await this.child.has(cid, options)\n const offline = options.offline === true\n\n if (!has) {\n if (offline) {\n throw new BlockNotFoundWhileOfflineError('The block was present in the blockstore and the node is running offline so cannot fetch it')\n }\n\n const hasher = await this.getHasher(cid.multihash.code)\n options?.signal?.throwIfAborted()\n\n // we do not have the block locally, get it from a block provider\n options.onProgress?.(new CustomProgressEvent<CID>('blocks:get-many:providers:get', cid))\n const block = await raceBlockRetrievers(cid, this.blockBrokers, hasher, {\n ...options,\n log: this.log\n })\n options.onProgress?.(new CustomProgressEvent<CID>('blocks:get-many:blockstore:put', cid))\n await this.child.put(cid, block, options)\n\n // notify other block providers of the new block\n options.onProgress?.(new CustomProgressEvent<CID>('blocks:get-many:providers:notify', cid))\n await Promise.all(\n this.blockBrokers.map(async broker => broker.announce?.(cid, options))\n )\n }\n }))\n }\n\n /**\n * Delete a block from the blockstore\n */\n async delete (cid: CID, options: AbortOptions & ProgressOptions<DeleteBlockProgressEvents> = {}): Promise<void> {\n options.onProgress?.(new CustomProgressEvent<CID>('blocks:delete:blockstore:delete', cid))\n\n await this.child.delete(cid, options)\n }\n\n /**\n * Delete multiple blocks from the blockstore\n */\n async * deleteMany (cids: Iterable<CID> | AsyncIterable<CID>, options: AbortOptions & ProgressOptions<DeleteManyBlocksProgressEvents> = {}): AsyncGenerator<CID> {\n options.onProgress?.(new CustomProgressEvent('blocks:delete-many:blockstore:delete-many'))\n yield * this.child.deleteMany((async function * (): AsyncGenerator<CID> {\n for await (const cid of cids) {\n yield cid\n }\n }()), options)\n }\n\n async has (cid: CID, options: AbortOptions = {}): Promise<boolean> {\n return this.child.has(cid, options)\n }\n\n async * getAll (options: AbortOptions & ProgressOptions<GetAllBlocksProgressEvents> = {}): AsyncGenerator<Pair> {\n options.onProgress?.(new CustomProgressEvent('blocks:get-all:blockstore:get-many'))\n yield * this.child.getAll(options)\n }\n}\n\n/**\n * Race block providers cancelling any pending requests once the block has been\n * found.\n */\nasync function raceBlockRetrievers (cid: CID, blockBrokers: BlockBroker[], hasher: MultihashHasher, options: AbortOptions & LoggerOptions): Promise<Uint8Array> {\n const validateFn = getCidBlockVerifierFunction(cid, hasher)\n\n const controller = new AbortController()\n const signal = anySignal([controller.signal, options.signal])\n setMaxListeners(Infinity, controller.signal, signal)\n\n const retrievers: Array<Required<Pick<BlockBroker, 'name' | 'retrieve'>>> = []\n\n for (const broker of blockBrokers) {\n if (isRetrievingBlockBroker(broker)) {\n retrievers.push(broker)\n }\n }\n\n if (retrievers.length === 0) {\n throw new InvalidConfigurationError(`No block brokers capable of retrieving blocks are configured, the CID ${cid} cannot be fetched from the network`)\n }\n\n try {\n return await Promise.any(\n retrievers\n .map(async retriever => {\n try {\n let blocksWereValidated = false\n const block = await retriever.retrieve(cid, {\n ...options,\n signal,\n validateFn: async (block: Uint8Array): Promise<void> => {\n await validateFn(block)\n options.signal?.throwIfAborted()\n blocksWereValidated = true\n }\n })\n\n if (!blocksWereValidated) {\n // the blockBroker either did not throw an error when attempting to validate the block\n // or did not call the validateFn at all. We should validate the block ourselves\n await validateFn(block)\n options.signal?.throwIfAborted()\n }\n\n return block\n } catch (err) {\n options.log.error('could not retrieve verified block for %c from %s - %e', cid, retriever.name, err)\n throw err\n }\n })\n )\n } catch (err: any) {\n throw new LoadBlockFailedError(err.errors, `Failed to load block for ${cid}`)\n } finally {\n // we have the block from the fastest block retriever, abort any still\n // in-flight retrieve attempts\n controller.abort()\n signal.clear()\n }\n}\n\nfunction isRetrievingBlockBroker (broker: BlockBroker): broker is Required<Pick<BlockBroker, 'name' | 'retrieve'>> {\n return typeof broker.retrieve === 'function'\n}\n\nexport const getCidBlockVerifierFunction = (cid: CID, hasher: MultihashHasher): Required<BlockRetrievalOptions>['validateFn'] => {\n if (hasher == null) {\n throw new InvalidParametersError(`No hasher configured for multihash code 0x${cid.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`)\n }\n\n return async (block: Uint8Array): Promise<void> => {\n // verify block\n let hash: MultihashDigest<number>\n const res = hasher.digest(block, {\n // support truncated hashes where they are truncated\n truncate: cid.multihash.digest.byteLength\n })\n\n if (isPromise(res)) {\n hash = await res\n } else {\n hash = res\n }\n\n if (!uint8ArrayEquals(hash.digest, cid.multihash.digest)) {\n // if a hash mismatch occurs for a TrustlessGatewayBlockBroker, we should try another gateway\n throw new InvalidMultihashError('Hash of downloaded block did not match multihash from passed CID')\n }\n }\n}\n", "import { setMaxListeners } from '@libp2p/interface'\nimport { anySignal } from 'any-signal'\nimport { Storage } from './storage.ts'\nimport type { StorageComponents } from './storage.ts'\nimport type { Pair, DeleteManyBlocksProgressEvents, DeleteBlockProgressEvents, GetBlockProgressEvents, GetManyBlocksProgressEvents, PutManyBlocksProgressEvents, PutBlockProgressEvents, GetAllBlocksProgressEvents, GetOfflineOptions, SessionBlockstore, SessionBlockBroker } from '@helia/interface/blocks'\nimport type { AbortOptions } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { InputPair } from 'interface-blockstore'\nimport type { CID } from 'multiformats/cid'\nimport type { ProgressOptions } from 'progress-events'\n\nexport interface SessionStorageInit {\n root: CID\n}\n\n/**\n * Storage subclass that can cancel any ongoing operation at any point.\n */\nexport class SessionStorage extends Storage<SessionBlockBroker> implements SessionBlockstore {\n private readonly closeController: AbortController\n\n constructor (components: StorageComponents<SessionBlockBroker>, init: SessionStorageInit) {\n super(components)\n\n // because brokers are allowed to continue searching for providers after the\n // session has been created, we need a way to tell them that the user has\n // finished using the session any in-flight requests should be cancelled\n this.closeController = new AbortController()\n setMaxListeners(Infinity, this.closeController.signal)\n\n this.log = components.logger.forComponent(`helia:session-storage:${init.root}`)\n }\n\n close (): void {\n this.closeController.abort()\n }\n\n async addPeer (peer: CID | Multiaddr | Multiaddr[], options?: AbortOptions): Promise<void> {\n await Promise.all(\n this.blockBrokers\n .map(broker => broker.addPeer(peer, options))\n )\n }\n\n /**\n * Put a block to the underlying datastore\n */\n async put (cid: CID, block: Uint8Array, options: AbortOptions & ProgressOptions<PutBlockProgressEvents> = {}): Promise<CID> {\n const signal = anySignal([this.closeController.signal, options.signal])\n setMaxListeners(Infinity, signal)\n\n try {\n return await super.put(cid, block, {\n ...options,\n signal\n })\n } finally {\n signal.clear()\n }\n }\n\n /**\n * Put a multiple blocks to the underlying datastore\n */\n async * putMany (blocks: Iterable<InputPair> | AsyncIterable<InputPair>, options: AbortOptions & ProgressOptions<PutManyBlocksProgressEvents> = {}): AsyncGenerator<CID> {\n const signal = anySignal([this.closeController.signal, options.signal])\n setMaxListeners(Infinity, signal)\n\n try {\n yield * super.putMany(blocks, {\n ...options,\n signal\n })\n } finally {\n signal.clear()\n }\n }\n\n /**\n * Get a block by cid\n */\n async * get (cid: CID, options: GetOfflineOptions & AbortOptions & ProgressOptions<GetBlockProgressEvents> = {}): AsyncGenerator<Uint8Array> {\n const signal = anySignal([this.closeController.signal, options.signal])\n setMaxListeners(Infinity, signal)\n\n try {\n yield * super.get(cid, {\n ...options,\n signal\n })\n } finally {\n signal.clear()\n }\n }\n\n /**\n * Get multiple blocks back from an (async) iterable of cids\n */\n async * getMany (cids: Iterable<CID> | AsyncIterable<CID>, options: GetOfflineOptions & AbortOptions & ProgressOptions<GetManyBlocksProgressEvents> = {}): AsyncGenerator<Pair> {\n const signal = anySignal([this.closeController.signal, options.signal])\n setMaxListeners(Infinity, signal)\n\n try {\n yield * super.getMany(cids, {\n ...options,\n signal\n })\n } finally {\n signal.clear()\n }\n }\n\n /**\n * Delete a block from the blockstore\n */\n async delete (cid: CID, options: AbortOptions & ProgressOptions<DeleteBlockProgressEvents> = {}): Promise<void> {\n const signal = anySignal([this.closeController.signal, options.signal])\n setMaxListeners(Infinity, signal)\n\n try {\n await super.delete(cid, {\n ...options,\n signal\n })\n } finally {\n signal.clear()\n }\n }\n\n /**\n * Delete multiple blocks from the blockstore\n */\n async * deleteMany (cids: Iterable<CID> | AsyncIterable<CID>, options: AbortOptions & ProgressOptions<DeleteManyBlocksProgressEvents> = {}): AsyncGenerator<CID> {\n const signal = anySignal([this.closeController.signal, options.signal])\n setMaxListeners(Infinity, signal)\n\n try {\n yield * super.deleteMany(cids, {\n ...options,\n signal\n })\n } finally {\n signal.clear()\n }\n }\n\n async has (cid: CID, options: AbortOptions = {}): Promise<boolean> {\n const signal = anySignal([this.closeController.signal, options.signal])\n setMaxListeners(Infinity, signal)\n\n try {\n return await super.has(cid, {\n ...options,\n signal\n })\n } finally {\n signal.clear()\n }\n }\n\n async * getAll (options: AbortOptions & ProgressOptions<GetAllBlocksProgressEvents> = {}): AsyncGenerator<Pair> {\n const signal = anySignal([this.closeController.signal, options.signal])\n setMaxListeners(Infinity, signal)\n\n try {\n yield * super.getAll({\n ...options,\n signal\n })\n } finally {\n signal.clear()\n }\n }\n}\n", "import { start, stop } from '@libp2p/interface'\nimport { InvalidConfigurationError } from '../errors.ts'\nimport { SessionStorage } from './session-storage.ts'\nimport { Storage } from './storage.ts'\nimport type { StorageComponents, StorageInit } from './storage.ts'\nimport type { BlockBroker, Blocks, CreateSessionOptions, SessionBlockstore } from '@helia/interface/blocks'\nimport type { Startable } from '@libp2p/interface'\nimport type { AbortOptions } from 'abort-error'\nimport type { Blockstore } from 'interface-blockstore'\nimport type { CID } from 'multiformats/cid'\n\nexport interface GetOptions extends AbortOptions {\n progress?(evt: Event): void\n}\n\nexport type NetworkedStorageComponents = StorageComponents<BlockBroker>\n\n/**\n * Networked storage wraps a regular blockstore - when getting blocks if the\n * blocks are not present, the configured BlockBrokers will be used to fetch them.\n */\nexport class NetworkedStorage extends Storage<BlockBroker> implements Blocks, Startable {\n private started: boolean\n\n /**\n * Create a new BlockStorage\n */\n constructor (components: NetworkedStorageComponents, init: StorageInit = {}) {\n super(components, init)\n\n this.started = false\n }\n\n isStarted (): boolean {\n return this.started\n }\n\n async start (): Promise<void> {\n await start(this.child, ...this.blockBrokers)\n this.started = true\n }\n\n async stop (): Promise<void> {\n await stop(this.child, ...this.blockBrokers)\n this.started = false\n }\n\n unwrap (): Blockstore {\n return this.child\n }\n\n createSession (root: CID, options?: CreateSessionOptions): SessionBlockstore {\n if (this.blockBrokers.length === 0) {\n throw new InvalidConfigurationError('No block brokers configured')\n }\n\n const blockBrokers = this.blockBrokers\n .map(broker => broker.createSession?.(options))\n .filter(broker => broker != null)\n\n if (blockBrokers.length === 0) {\n throw new InvalidConfigurationError(`No configured block brokers support sessions - tried ${this.blockBrokers.map(b => b.name).join(', ')}`)\n }\n\n return new SessionStorage({\n blockstore: this.child,\n blockBrokers,\n getHasher: this.getHasher,\n logger: this.logger\n }, {\n root\n })\n }\n}\n", "import { DEFAULT_SESSION_MIN_PROVIDERS, DEFAULT_SESSION_MAX_PROVIDERS, DEFAULT_CID_PEER_FILTER_SIZE, InsufficientProvidersError } from '@helia/interface'\nimport { AbortError, TypedEventEmitter, setMaxListeners } from '@libp2p/interface'\nimport { createScalableCuckooFilter, Queue } from '@libp2p/utils'\nimport { base64 } from 'multiformats/bases/base64'\nimport pDefer from 'p-defer'\nimport { raceSignal } from 'race-signal'\nimport type { BlockBroker, BlockRetrievalOptions, CreateSessionOptions } from '@helia/interface'\nimport type { AbortOptions, ComponentLogger, Logger } from '@libp2p/interface'\nimport type { Filter } from '@libp2p/utils'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { CID } from 'multiformats/cid'\nimport type { DeferredPromise } from 'p-defer'\nimport type { ProgressEvent } from 'progress-events'\n\nexport interface AbstractSessionComponents {\n logger: ComponentLogger\n}\n\nexport interface AbstractCreateSessionOptions extends CreateSessionOptions {\n name: string\n}\n\nexport interface BlockstoreSessionEvents<Provider> {\n provider: CustomEvent<Provider>\n}\n\ninterface Request {\n promise: Promise<Uint8Array>\n observers: number\n queryFilter: Filter\n}\n\nexport abstract class AbstractSession<Provider, RetrieveBlockProgressEvents extends ProgressEvent> extends TypedEventEmitter<BlockstoreSessionEvents<Provider>> implements BlockBroker<RetrieveBlockProgressEvents> {\n public abstract name: string\n private initialPeerSearchComplete?: Promise<void>\n private readonly requests: Map<string, Request>\n private readonly logName: string\n protected log: Logger\n protected logger: ComponentLogger\n private readonly minProviders: number\n private readonly maxProviders: number\n public readonly providers: Provider[]\n private readonly evictionFilter: Filter\n private readonly initialProviders: Array<CID | Multiaddr | Multiaddr[]>\n private readonly cidPeerFilterSize: number\n\n constructor (components: AbstractSessionComponents, init: AbstractCreateSessionOptions) {\n super()\n\n setMaxListeners(Infinity, this)\n this.logName = init.name\n this.logger = components.logger\n this.log = components.logger.forComponent(this.logName)\n this.requests = new Map()\n this.minProviders = init.minProviders ?? DEFAULT_SESSION_MIN_PROVIDERS\n this.maxProviders = init.maxProviders ?? DEFAULT_SESSION_MAX_PROVIDERS\n this.cidPeerFilterSize = init.cidPeerFilterSize ?? DEFAULT_CID_PEER_FILTER_SIZE\n this.providers = []\n this.evictionFilter = createScalableCuckooFilter(this.maxProviders)\n this.initialProviders = [...(init.providers ?? [])]\n }\n\n async retrieve (cid: CID, options: BlockRetrievalOptions<RetrieveBlockProgressEvents> = {}): Promise<Uint8Array> {\n // see if we are already requesting this CID in this session\n const cidStr = base64.encode(cid.multihash.bytes)\n const existingJob = this.requests.get(cidStr)\n\n if (existingJob != null) {\n this.log('join existing request for %c', cid)\n existingJob.observers++\n return existingJob.promise\n }\n\n const deferred: DeferredPromise<Uint8Array> = pDefer()\n const request = {\n promise: deferred.promise,\n observers: 1,\n queryFilter: createScalableCuckooFilter(this.cidPeerFilterSize)\n }\n this.requests.set(cidStr, request)\n\n // if this is the first time this session has been used\n let first = false\n\n if (this.initialPeerSearchComplete == null) {\n first = true\n this.log = this.logger.forComponent(`${this.logName}:${cid}`)\n this.initialPeerSearchComplete = this.findProviders(cid, this.minProviders, options)\n }\n\n let foundBlock = false\n\n // this queue manages outgoing requests - as new peers are added to the\n // session they will be added to the queue so we can request the current\n // block from multiple peers as they are discovered\n const queue = new Queue<Uint8Array, { provider: Provider, priority?: number } & AbortOptions>({\n concurrency: this.maxProviders\n })\n queue.addEventListener('failure', (evt) => {\n this.log.error('error querying provider %s, evicting from session - %e', evt.detail.job.options.provider, evt.detail.error)\n this.evict(evt.detail.job.options.provider)\n })\n queue.addEventListener('success', (evt) => {\n // peer has sent block, return it to the caller\n foundBlock = true\n deferred.resolve(evt.detail.result)\n })\n queue.addEventListener('idle', () => {\n if (foundBlock) {\n this.log.trace('session idle, found block')\n // we either found the block or the user gave up\n return\n }\n\n if (options.signal?.aborted === true) {\n this.log.trace('session idle, signal aborted')\n return\n }\n\n // find more session peers and retry\n Promise.resolve()\n .then(async () => {\n this.log('no session peers had block for for %c, finding new providers', cid)\n\n // evict this.minProviders random providers to make room for more\n for (let i = 0; i < this.minProviders; i++) {\n if (this.providers.length === 0) {\n break\n }\n\n const provider = this.providers[Math.floor(Math.random() * this.providers.length)]\n this.evict(provider)\n }\n\n // find new providers for the CID\n await this.findProviders(cid, this.minProviders, options)\n\n // keep trying until the abort signal fires\n this.log('found new providers re-retrieving %c', cid)\n this.requests.delete(cidStr)\n deferred.resolve(await this.retrieve(cid, options))\n })\n .catch(err => {\n this.log.error('could not find new providers for %c - %e', cid, err)\n deferred.reject(err)\n })\n })\n\n const peerAddedToSessionListener = (event: CustomEvent<Provider>): void => {\n const filterKey = this.toFilterKey(event.detail)\n\n if (request.queryFilter.has(filterKey)) {\n return\n }\n\n request.queryFilter.add(filterKey)\n\n // dispatch progress notification\n this.emitFoundProviderProgressEvent(cid, event.detail, options)\n\n queue.add(async () => {\n return this.queryProvider(cid, event.detail, options)\n }, {\n provider: event.detail\n })\n .catch(err => {\n if (options.signal?.aborted === true) {\n // skip logging error if signal was aborted because abort can happen\n // on success (e.g. another session found the block)\n return\n }\n\n this.log.error('error retrieving session block for %c - %e', cid, err)\n })\n }\n\n // add new session peers to query as they are discovered\n this.addEventListener('provider', peerAddedToSessionListener)\n\n if (first) {\n try {\n await raceSignal(this.initialPeerSearchComplete, options.signal)\n\n if (first) {\n this.log('found initial session peers for %c', cid)\n }\n } catch (err) {\n if (first) {\n this.log('failed to find initial session peers for %c - %e', cid, err)\n }\n\n this.requests.delete(cidStr)\n\n if (request.observers > 1) {\n // only need to reject request if another context is now also waiting\n // for the result - otherwise we can end up with an unhandled promise\n // rejection\n deferred.reject(err)\n }\n\n throw err\n }\n }\n\n // query each session peer directly\n Promise.all(\n [...this.providers]\n .filter(provider => {\n const filterKey = this.toFilterKey(provider)\n const has = request.queryFilter.has(filterKey)\n\n if (!has) {\n request.queryFilter.add(this.toFilterKey(provider))\n }\n\n return !has\n })\n .map(async (provider) => {\n return queue.add(async () => this.queryProvider(cid, provider, options), {\n provider\n })\n })\n )\n .catch(err => {\n if (options.signal?.aborted === true) {\n // skip logging error if signal was aborted because abort can happen\n // on success (e.g. another session found the block)\n return\n }\n\n this.log.error('error retrieving session block for %c - %e', cid, err)\n })\n\n const signalAbortedListener = (): void => {\n deferred.reject(new AbortError(options.signal?.reason ?? 'Session aborted'))\n queue.abort()\n }\n\n options.signal?.addEventListener('abort', signalAbortedListener)\n\n try {\n return await deferred.promise\n } finally {\n this.removeEventListener('provider', peerAddedToSessionListener)\n options.signal?.removeEventListener('abort', signalAbortedListener)\n queue.clear()\n this.requests.delete(cidStr)\n }\n }\n\n evict (provider: Provider): void {\n this.evictionFilter.add(this.toFilterKey(provider))\n const index = this.providers.findIndex(prov => this.equals(prov, provider))\n\n if (index === -1) {\n return\n }\n\n this.providers.splice(index, 1)\n }\n\n isEvicted (provider: Provider): boolean {\n return this.evictionFilter.has(this.toFilterKey(provider))\n }\n\n hasProvider (provider: Provider): boolean {\n // dedupe existing gateways\n if (this.providers.find(prov => this.equals(prov, provider)) != null) {\n return true\n }\n\n // dedupe failed session peers\n if (this.isEvicted(provider)) {\n return true\n }\n\n return false\n }\n\n async addPeer (peer: CID | Multiaddr | Multiaddr[], options?: AbortOptions): Promise<void> {\n const provider = await this.convertToProvider(peer, 'manually-added', options)\n\n if (provider == null || this.hasProvider(provider)) {\n return\n }\n\n this.providers.push(provider)\n\n // let the new peer join current queries\n this.safeDispatchEvent('provider', {\n detail: provider\n })\n }\n\n private async findProviders (cid: CID, count: number, options: BlockRetrievalOptions<RetrieveBlockProgressEvents>): Promise<void> {\n const deferred: DeferredPromise<void> = pDefer()\n let found = 0\n\n // run async to resolve the deferred promise when `count` providers are\n // found but continue util this.providers reaches this.maxProviders\n void Promise.resolve()\n .then(async () => {\n this.log('finding %d-%d new provider(s) for %c - %d initial providers', count, this.maxProviders, cid, this.initialProviders.length)\n\n const self = this\n\n // process any specific providers for this session\n const initialProviders = async function * (): AsyncGenerator<Provider> {\n while (self.initialProviders.length > 0) {\n const initialProvider = self.initialProviders.pop()\n\n if (initialProvider == null) {\n continue\n }\n\n const provider = await self.convertToProvider(initialProvider, 'manual', options)\n\n if (provider == null) {\n continue\n }\n\n yield provider\n }\n }\n\n const providers = async function * (): AsyncGenerator<Provider> {\n yield * initialProviders()\n yield * self.findNewProviders(cid, options)\n }\n\n // still not got enough providers, search routing for more\n for await (const provider of providers()) {\n if (this.providers.length === this.maxProviders || options.signal?.aborted === true) {\n break\n }\n\n if (this.hasProvider(provider)) {\n continue\n }\n\n this.log('found %d providers, %d in session', found, this.providers.length)\n this.providers.push(provider)\n\n // let the new peer join current queries\n this.safeDispatchEvent('provider', {\n detail: provider\n })\n\n found++\n\n if (this.providers.length === count) {\n this.log('session is ready with %d peer(s), new peers present', this.providers.length)\n deferred.resolve()\n // continue finding peers until we reach this.maxProviders\n }\n\n if (this.providers.length === this.maxProviders) {\n this.log('found max session peers %d', this.providers.length)\n break\n }\n }\n\n this.log('found %d new session peers while trying to find %d, %d in session', found, count, this.providers.length)\n\n if (this.providers.length < count) {\n throw new InsufficientProvidersError(`Found ${found} of ${count} ${this.name} providers for ${cid}, ${this.providers.length} in session after evictions`)\n }\n })\n .catch(err => {\n this.log.error('error searching routing for potential session peers for %c - %e', cid, err)\n deferred.reject(err)\n })\n\n return deferred.promise\n }\n\n /**\n * If this session was created with specific providers, convert one of them\n * into the format required or return `undefined` if the provider is not\n * compatible with this session implementation\n */\n abstract convertToProvider (provider: CID | Multiaddr | Multiaddr[], routing: string, options?: AbortOptions): Promise<Provider | undefined>\n\n /**\n * This method should search for new providers and yield them.\n */\n abstract findNewProviders (cid: CID, options: BlockRetrievalOptions<RetrieveBlockProgressEvents>): AsyncGenerator<Provider>\n\n /**\n * The subclass should contact the provider and request the block from it.\n *\n * If the provider cannot provide the block an error should be thrown.\n *\n * The provider will then be excluded from ongoing queries.\n */\n abstract queryProvider (cid: CID, provider: Provider, options: AbortOptions): Promise<Uint8Array>\n\n /**\n * Turn a provider into a concise Uint8Array representation for use in a Bloom\n * or Cuckoo filter\n */\n abstract toFilterKey (provider: Provider): Uint8Array | string\n\n /**\n * Return `true` if we consider one provider to be the same as another\n */\n abstract equals (providerA: Provider, providerB: Provider): boolean\n\n /**\n * Invoke the progress handler with the session-specific found provider event\n */\n abstract emitFoundProviderProgressEvent (cid: CID, provider: Provider, options: BlockRetrievalOptions<RetrieveBlockProgressEvents>): void\n}\n", "import { CID } from 'multiformats/cid'\n\nexport function isCID (obj?: any): obj is CID {\n if (obj == null) {\n return false\n }\n\n return CID.asCID(obj) != null\n}\n"],
4
+ "sourcesContent": ["'use strict';\n\nfunction isHighSurrogate(codePoint) {\n return codePoint >= 0xd800 && codePoint <= 0xdbff;\n}\n\nfunction isLowSurrogate(codePoint) {\n return codePoint >= 0xdc00 && codePoint <= 0xdfff;\n}\n\n// Truncate string by size in bytes\nmodule.exports = function truncate(getLength, string, byteLength) {\n if (typeof string !== \"string\") {\n throw new Error(\"Input must be string\");\n }\n\n var charLength = string.length;\n var curByteLength = 0;\n var codePoint;\n var segment;\n\n for (var i = 0; i < charLength; i += 1) {\n codePoint = string.charCodeAt(i);\n segment = string[i];\n\n if (isHighSurrogate(codePoint) && isLowSurrogate(string.charCodeAt(i + 1))) {\n i += 1;\n segment += string[i];\n }\n\n curByteLength += getLength(segment);\n\n if (curByteLength === byteLength) {\n return string.slice(0, i + 1);\n }\n else if (curByteLength > byteLength) {\n return string.slice(0, i - segment.length + 1);\n }\n }\n\n return string;\n};\n\n", "'use strict';\n\nfunction isHighSurrogate(codePoint) {\n return codePoint >= 0xd800 && codePoint <= 0xdbff;\n}\n\nfunction isLowSurrogate(codePoint) {\n return codePoint >= 0xdc00 && codePoint <= 0xdfff;\n}\n\n// Truncate string by size in bytes\nmodule.exports = function getByteLength(string) {\n if (typeof string !== \"string\") {\n throw new Error(\"Input must be string\");\n }\n\n var charLength = string.length;\n var byteLength = 0;\n var codePoint = null;\n var prevCodePoint = null;\n for (var i = 0; i < charLength; i++) {\n codePoint = string.charCodeAt(i);\n // handle 4-byte non-BMP chars\n // low surrogate\n if (isLowSurrogate(codePoint)) {\n // when parsing previous hi-surrogate, 3 is added to byteLength\n if (prevCodePoint != null && isHighSurrogate(prevCodePoint)) {\n byteLength += 1;\n }\n else {\n byteLength += 3;\n }\n }\n else if (codePoint <= 0x7f ) {\n byteLength += 1;\n }\n else if (codePoint >= 0x80 && codePoint <= 0x7ff) {\n byteLength += 2;\n }\n else if (codePoint >= 0x800 && codePoint <= 0xffff) {\n byteLength += 3;\n }\n prevCodePoint = codePoint;\n }\n\n return byteLength;\n};\n", "'use strict';\n\nvar truncate = require(\"./lib/truncate\");\nvar getLength = require(\"utf8-byte-length/browser\");\nmodule.exports = truncate.bind(null, getLength);\n", "/*jshint node:true*/\n'use strict';\n\n/**\n * Replaces characters in strings that are illegal/unsafe for filenames.\n * Unsafe characters are either removed or replaced by a substitute set\n * in the optional `options` object.\n *\n * Illegal Characters on Various Operating Systems\n * / ? < > \\ : * | \"\n * https://kb.acronis.com/content/39790\n *\n * Unicode Control codes\n * C0 0x00-0x1f & C1 (0x80-0x9f)\n * http://en.wikipedia.org/wiki/C0_and_C1_control_codes\n *\n * Reserved filenames on Unix-based systems (\".\", \"..\")\n * Reserved filenames in Windows (\"CON\", \"PRN\", \"AUX\", \"NUL\", \"COM1\",\n * \"COM2\", \"COM3\", \"COM4\", \"COM5\", \"COM6\", \"COM7\", \"COM8\", \"COM9\",\n * \"LPT1\", \"LPT2\", \"LPT3\", \"LPT4\", \"LPT5\", \"LPT6\", \"LPT7\", \"LPT8\", and\n * \"LPT9\") case-insesitively and with or without filename extensions.\n *\n * Capped at 255 characters in length.\n * http://unix.stackexchange.com/questions/32795/what-is-the-maximum-allowed-filename-and-folder-size-with-ecryptfs\n *\n * @param {String} input Original filename\n * @param {Object} options {replacement: String | Function }\n * @return {String} Sanitized filename\n */\n\nvar truncate = require(\"truncate-utf8-bytes\");\n\nvar illegalRe = /[\\/\\?<>\\\\:\\*\\|\"]/g;\nvar controlRe = /[\\x00-\\x1f\\x80-\\x9f]/g;\nvar reservedRe = /^\\.+$/;\nvar windowsReservedRe = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\\..*)?$/i;\n\n/**\n * Strip trailing spaces and dots, which are not allowed on some Windows file\n * systems. Does not use a regex to avoid a quadratic ReDoS vulnerability\n * (CWE-1333).\n */\nfunction replaceTrailingDotsAndSpaces(str, replacement) {\n var end = str.length;\n while (end > 0 && (str[end - 1] === '.' || str[end - 1] === ' ')) end--;\n return end < str.length ? str.slice(0, end) + replacement : str;\n}\n\nfunction sanitize(input, replacement) {\n if (typeof input !== 'string') {\n throw new Error('Input must be string');\n }\n var sanitized = input\n .replace(illegalRe, replacement)\n .replace(controlRe, replacement)\n .replace(reservedRe, replacement)\n .replace(windowsReservedRe, replacement);\n sanitized = replaceTrailingDotsAndSpaces(sanitized, replacement);\n return truncate(sanitized, 255);\n}\n\nmodule.exports = function (input, options) {\n var replacement = (options && options.replacement) || '';\n var output = sanitize(input, replacement);\n if (replacement === '') {\n return output;\n }\n return sanitize(output, '');\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", "module.exports = function (max) {\n\n if (!max) throw Error('hashlru must have a max value, of type number, greater than 0')\n\n var size = 0, cache = Object.create(null), _cache = Object.create(null)\n\n function update (key, value) {\n cache[key] = value\n size ++\n if(size >= max) {\n size = 0\n _cache = cache\n cache = Object.create(null)\n }\n }\n\n return {\n has: function (key) {\n return cache[key] !== undefined || _cache[key] !== undefined\n },\n remove: function (key) {\n if(cache[key] !== undefined)\n cache[key] = undefined\n if(_cache[key] !== undefined)\n _cache[key] = undefined\n },\n get: function (key) {\n var v = cache[key]\n if(v !== undefined) return v\n if((v = _cache[key]) !== undefined) {\n update(key, v)\n return v\n }\n },\n set: function (key, value) {\n if(cache[key] !== undefined) cache[key] = value\n else update(key, value)\n },\n clear: function () {\n cache = Object.create(null)\n _cache = Object.create(null)\n }\n }\n}\n\n\n\n\n\n\n\n", "/**\n * @packageDocumentation\n *\n * This module contains utility code that is shared between various Helia\n * modules such as `helia`, `@helia/http`, etc.\n */\n\nimport { keychain } from '@ipshipyard/keychain'\nimport { start, stop, TypedEventEmitter } from '@libp2p/interface'\nimport { dns } from '@multiformats/dns'\nimport { defaultLogger } from 'birnam'\nimport { MemoryBlockstore } from 'blockstore-core'\nimport { MemoryDatastore } from 'datastore-core'\nimport drain from 'it-drain'\nimport { CustomProgressEvent } from 'progress-events'\nimport { PinsImpl } from './pins.ts'\nimport { Routing as RoutingClass } from './routing.ts'\nimport { BlockStorage } from './storage.ts'\nimport { assertDatastoreVersionIsCurrent } from './utils/datastore-version.ts'\nimport { getCodec } from './utils/get-codec.ts'\nimport { getCrypto } from './utils/get-crypto.ts'\nimport { getHasher } from './utils/get-hasher.ts'\nimport { NetworkedStorage } from './utils/networked-storage.ts'\nimport type { BlockStorageInit } from './storage.ts'\nimport type { CodecLoader, GCOptions, HasherLoader, Helia as HeliaInterface, HeliaEvents, Routing, CryptoLoader, Crypto, NodeInfo, Router, HeliaMixin } from '@helia/interface'\nimport type { BlockBroker } from '@helia/interface'\nimport type { Pins } from '@helia/interface'\nimport type { Keychain, KeychainInit } from '@ipshipyard/keychain'\nimport type { ComponentLogger, Logger, Metrics } from '@libp2p/interface'\nimport type { DNS } from '@multiformats/dns'\nimport type { Blockstore } from 'interface-blockstore'\nimport type { Datastore } from 'interface-datastore'\nimport type { BlockCodec } from 'multiformats'\nimport type { CID } from 'multiformats/cid'\nimport type { MultihashHasher } from 'multiformats/hashes/interface'\n\nexport { AbstractSession } from './abstract-session.ts'\nexport type { AbstractCreateSessionOptions, BlockstoreSessionEvents, AbstractSessionComponents } from './abstract-session.ts'\n\nexport { isCID } from './utils/is-cid.ts'\n\nexport type { BlockStorage, BlockStorageInit }\n\nexport { breadthFirstWalker, depthFirstWalker, naturalOrderWalker } from './graph-walker.ts'\nexport type { GraphWalkerComponents, GraphWalkerInit, GraphNode, GraphWalker } from './graph-walker.ts'\n\n/**\n * Options used to create a Helia node.\n */\nexport interface HeliaInit {\n /**\n * By default Helia stores the node's PeerId in an encrypted form in a\n * libp2p keystore. These options control how that keystore is configured.\n */\n keychain?: KeychainInit\n\n /**\n * The blockstore is where blocks are stored\n */\n blockstore?: Blockstore\n\n /**\n * The datastore is where data is stored\n */\n datastore?: Datastore\n\n /**\n * By default sha256, sha512 and identity hashes are supported for\n * bitswap operations. To bitswap blocks with CIDs using other hashes\n * pass appropriate MultihashHashers here.\n */\n hashers?: MultihashHasher[]\n\n /**\n * An optional function that can load a MultihashHasher on demand. May return\n * a promise.\n */\n loadHasher?(code: number): MultihashHasher | Promise<MultihashHasher>\n\n /**\n * In order to pin CIDs that correspond to a DAG, it's necessary to know\n * how to traverse that DAG. DAGWalkers take a block and yield any CIDs\n * encoded within that block.\n */\n codecs?: Array<BlockCodec<any, any>>\n\n /**\n * An optional function that can load a BlockCodec on demand. May return a\n * promise.\n */\n loadCodec?(code: number): BlockCodec<any, any> | Promise<BlockCodec<any, any>>\n\n /**\n * A list of pre-supported public/private key implementations\n */\n cryptos?: Array<Crypto>\n\n /**\n * Dynamically load a cryptography implementation\n */\n loadCrypto?: CryptoLoader\n\n /**\n * Garbage collection requires preventing blockstore writes during searches\n * for unpinned blocks as DAGs are typically pinned after they've been\n * imported - without locking this could lead to the deletion of blocks while\n * they are being added to the blockstore.\n *\n * By default this lock is held on the current process and other processes\n * will contact this process for access.\n *\n * If Helia is being run in multiple processes, one process must hold the GC\n * lock so use this option to control which process that is.\n *\n * @default true\n */\n holdGcLock?: boolean\n\n /**\n * An optional logging component to pass to libp2p. If not specified the\n * default implementation from libp2p will be used.\n */\n logger?: ComponentLogger\n\n /**\n * A list of strategies used to fetch blocks when they are not present in\n * the local blockstore\n */\n blockBrokers?: Array<BlockBroker | ((components: any) => BlockBroker)>\n\n /**\n * Routers perform operations such as looking up content providers,\n * information about network peers or getting/putting records.\n */\n routers?: Array<Router | ((components: any) => Router)>\n\n /**\n * During provider lookups, peers can be returned from routing implementations\n * with no multiaddrs.\n *\n * This can happen when they've been retrieved from network peers that only\n * store multiaddrs for a limited amount of time.\n *\n * When this happens the peer's info has to be looked up with a further query.\n *\n * To not have this query block the yielding of other providers returned with\n * multiaddrs, a separate queue is used to perform this lookup.\n *\n * This config value controls the concurrency of that queue.\n *\n * @default 5\n */\n providerLookupConcurrency?: number\n\n /**\n * Components used by subclasses\n */\n components?: Record<string, any>\n\n /**\n * An optional DNS implementation used to perform queries for DNS records.\n */\n dns?: DNS\n\n /**\n * A metrics object that can be used to collected arbitrary stats about node\n * usage.\n */\n metrics?: Metrics\n\n /**\n * Limit the maximum supported size of identity hash digests to this value\n *\n * @default 128\n */\n maxIdentityHashDigestLength?: number\n}\n\ninterface Components {\n blockstore: Blockstore\n datastore: Datastore\n logger: ComponentLogger\n blockBrokers: BlockBroker[]\n routing: Routing\n dns: DNS\n keychain: Keychain\n metrics?: Metrics\n getCodec: CodecLoader\n getHasher: HasherLoader\n getCrypto: CryptoLoader\n}\n\nexport class Helia implements HeliaInterface {\n public info: NodeInfo\n public blockstore: BlockStorage\n public datastore: Datastore\n public events: TypedEventEmitter<HeliaEvents<this>>\n public pins: Pins\n public logger: ComponentLogger\n public routing: RoutingClass\n public getCodec: CodecLoader\n public getHasher: HasherLoader\n public getCrypto: CryptoLoader\n public dns: DNS\n public keychain: Keychain\n public metrics?: Metrics\n public status: 'stopped' | 'stopping' | 'starting' | 'started'\n private readonly log: Logger\n private readonly blockBrokers: BlockBroker[]\n private readonly mixins: HeliaMixin[]\n\n constructor (init: HeliaInit & { name: string, version: string }) {\n this.info = {\n name: init.name,\n version: init.version\n }\n this.logger = init.logger ?? defaultLogger()\n this.log = this.logger.forComponent('helia')\n this.getHasher = getHasher(init.hashers, init.loadHasher)\n this.getCodec = getCodec(init.codecs, init.loadCodec)\n this.getCrypto = getCrypto(init.cryptos, init.loadCrypto)\n this.dns = init.dns ?? dns()\n this.metrics = init.metrics\n this.events = new TypedEventEmitter<HeliaEvents<typeof this>>()\n this.status = 'stopped'\n this.mixins = []\n\n // @ts-expect-error routing and keychain are not set\n const components: Components = {\n blockstore: init.blockstore ?? new MemoryBlockstore(),\n datastore: init.datastore ?? new MemoryDatastore(),\n logger: this.logger,\n blockBrokers: [],\n getHasher: this.getHasher,\n getCodec: this.getCodec,\n getCrypto: this.getCrypto,\n dns: this.dns,\n metrics: this.metrics,\n ...(init.components ?? {})\n }\n\n this.keychain = components.keychain = keychain()(components)\n\n this.routing = components.routing = new RoutingClass(components, {\n routers: (init.routers ?? []).flatMap((router: Router | ((components: any) => Router)) => {\n if (typeof router === 'function') {\n router = router(components)\n }\n\n // if the router itself is a router\n const routers = [\n router\n ]\n\n return routers\n }),\n providerLookupConcurrency: init.providerLookupConcurrency\n })\n\n this.blockBrokers = components.blockBrokers = (init.blockBrokers ?? []).map((broker) => {\n if (typeof broker === 'function') {\n broker = broker(components)\n }\n\n return broker\n })\n\n const networkedStorage = new NetworkedStorage(components, init)\n this.pins = new PinsImpl(components.datastore, networkedStorage, this.getCodec)\n this.blockstore = new BlockStorage(networkedStorage, this.pins, this.routing, {\n holdGcLock: init.holdGcLock ?? true\n })\n this.datastore = components.datastore\n }\n\n hasRouter (name: string): boolean {\n return this.routing.hasRouter(name)\n }\n\n addRouter (router: Router): void {\n this.routing.addRouter(router)\n }\n\n hasBlockBroker (name: string): boolean {\n return this.blockBrokers.findIndex(b => b.name === name) !== -1\n }\n\n addBlockBroker (blockBroker: BlockBroker): void {\n this.blockBrokers.push(blockBroker)\n }\n\n addMixin (mixin: HeliaMixin): void {\n this.mixins.push(mixin)\n }\n\n async start (): Promise<this> {\n this.status = 'starting'\n\n await assertDatastoreVersionIsCurrent(this.datastore)\n await start(\n this.blockstore,\n this.datastore,\n this.routing,\n ...this.blockBrokers\n )\n\n for (const mixin of this.mixins) {\n await mixin.start?.(this)\n }\n\n this.status = 'started'\n this.events.dispatchEvent(new CustomEvent('start', { detail: this }))\n\n return this\n }\n\n async stop (): Promise<this> {\n this.status = 'stopping'\n\n for (const mixin of this.mixins) {\n await mixin.stop?.(this)\n }\n\n await stop(\n this.blockstore,\n this.datastore,\n this.routing,\n ...this.blockBrokers\n )\n\n this.status = 'stopped'\n this.events.dispatchEvent(new CustomEvent('stop', { detail: this }))\n\n return this\n }\n\n async gc (options: GCOptions = {}): Promise<void> {\n const releaseLock = await this.blockstore.lock.writeLock()\n\n try {\n const helia = this\n const blockstore = this.blockstore.unwrap()\n\n this.log('gc start')\n\n await drain(blockstore.deleteMany((async function * (): AsyncGenerator<CID> {\n for await (const { cid } of blockstore.getAll()) {\n try {\n if (await helia.pins.isPinned(cid, options)) {\n continue\n }\n\n yield cid\n\n options.onProgress?.(new CustomProgressEvent<CID>('helia:gc:deleted', cid))\n } catch (err: any) {\n helia.log.error('error during gc - %e', err)\n options.onProgress?.(new CustomProgressEvent<Error>('helia:gc:error', err))\n }\n }\n }())))\n } finally {\n releaseLock()\n }\n\n this.log('gc finished')\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<ArrayBuffer> {\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<ArrayBuffer> {\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 <T extends ArrayBufferLike> (value: number, buf: Uint8Array<T>, offset: number = 0): Uint8Array<T> {\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 <T extends ArrayBufferLike> (value: number, buf: Uint8ArrayList<T>, offset: number = 0): Uint8ArrayList<T> {\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<ArrayBuffer>\nexport function encode <T extends ArrayBufferLike> (value: number, buf: Uint8Array<T>, offset?: number): Uint8Array<T>\nexport function encode <T extends ArrayBufferLike> (value: number, buf: Uint8ArrayList<T>, offset?: number): Uint8ArrayList<T>\nexport function encode <B extends ArrayBufferLike, T extends Uint8Array<B> | Uint8ArrayList<B> = Uint8Array<B>> (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", "function isArrayBufferBacked (arr: Uint8Array): arr is Uint8Array<ArrayBuffer> {\n return arr.buffer instanceof ArrayBuffer\n}\n\n/**\n * If the passed `arr` is of type `Uint8Array<ArrayBuffer>`, it is returned\n * unchanged, otherwise a new `Uint8Array<ArrayBuffer>` is created with the\n * data being a copy of the data in the passed `arr`.\n */\nexport function withArrayBuffer (arr: Uint8Array): Uint8Array<ArrayBuffer> {\n if (isArrayBufferBacked(arr)) {\n return arr\n }\n\n return arr.slice()\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 { withArrayBuffer } from 'uint8arrays/with-array-buffer'\nimport { readFloatLE, readDoubleLE } from './float.ts'\nimport { LongBits } from './longbits.ts'\nimport * as utf8 from './utf8.ts'\nimport type { Reader } from '../index.ts'\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<ArrayBuffer>\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 = withArrayBuffer(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<ArrayBuffer> {\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.ts'\nimport type { Codec, DecodeOptions } from './codec.ts'\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.ts'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\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<ArrayBuffer> {\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\n/**\r\n * Normalize binary input to a plain `Uint8Array` backed by an `ArrayBuffer`.\r\n *\r\n * Returns the input itself when it is already a plain `Uint8Array` over an\r\n * `ArrayBuffer`, otherwise a fresh view (or, for `SharedArrayBuffer`-backed\r\n * input, a copy) over the same bytes.\r\n *\r\n * Throws if input is not a recognised binary type.\r\n */\r\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array<ArrayBuffer> {\r\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') {\n return toArrayBufferBackedArray(o)\n }\n if (o instanceof ArrayBuffer) {\n return new Uint8Array(o)\n }\n if (ArrayBuffer.isView(o)) {\n return toArrayBufferBackedArray(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<ArrayBuffer> {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n\nfunction isByteArrayWithArrayBuffer (b?: Uint8Array): b is Uint8Array<ArrayBuffer> {\n return b?.buffer instanceof ArrayBuffer\n}\n\n/**\n * Ensures `b` is backed by an ArrayBuffer - if not a new Uint8Array will be\n * created and the contents of `b` copied into it.\n */\nexport function toArrayBufferBackedArray (b: Uint8Array): Uint8Array<ArrayBuffer> {\n if (isByteArrayWithArrayBuffer(b)) {\n return b\n }\n\n return b.slice()\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.ts'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.ts'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array<ArrayBuffer> }\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<ArrayBuffer> {\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<ArrayBuffer> {\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<ArrayBuffer> {\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<ArrayBuffer> => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabetIdx: Record<string, number>, bitsPerChar: number, name: string): Uint8Array<ArrayBuffer> {\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<ArrayBuffer> {\n return decode(input, alphabetIdx, bitsPerChar, name)\n }\n })\n}\n", "import { rfc4648 } from './base.ts'\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.ts'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n", "import { from } from './base.ts'\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<ArrayBuffer> {\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.ts'\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", "import { baseX } from './base.ts'\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.ts'\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", "import { rfc4648 } from './base.ts'\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.ts'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n", "import { fromString, toString } from '../bytes.ts'\nimport { from } from './base.ts'\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.ts'\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.ts'\nimport type { ArrayBufferView, ByteView } from './interface.ts'\n\nexport const name = 'raw'\nexport const code = 0x55\n\nexport function encode (node: Uint8Array): ByteView<Uint8Array> {\n return coerce(node)\n}\n\nexport function decode (data: ByteView<Uint8Array> | ArrayBufferView<Uint8Array>): Uint8Array {\n return coerce(data)\n}\n", "import { coerce } from '../bytes.ts'\nimport * as Digest from './digest.ts'\nimport type { DigestOptions } from './hasher.ts'\nimport type { SyncMultihashHasher } from './interface.ts'\n\nconst code: 0x0 = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array<ArrayBuffer> = coerce\n\nfunction digest (input: Uint8Array, options?: DigestOptions): Digest.Digest<typeof code, number> {\n if (options?.truncate != null && options.truncate !== input.byteLength) {\n if (options.truncate < 0 || options.truncate > input.byteLength) {\n throw new Error(`Invalid truncate option, must be less than or equal to ${input.byteLength}`)\n }\n\n input = input.subarray(0, options.truncate)\n }\n\n return Digest.create(code, encode(input))\n}\n\nexport const identity: SyncMultihashHasher<0x00> = { code, name, encode, digest }\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, toArrayBufferBackedArray } from '../bytes.ts'\nimport * as varint from '../varint.ts'\nimport type { MultihashDigest } from './interface.ts'\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<ArrayBuffer>\n readonly bytes: Uint8Array<ArrayBuffer>\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 = toArrayBufferBackedArray(digest)\n this.bytes = toArrayBufferBackedArray(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 { from } from './hasher.ts'\n\nfunction sha (name: AlgorithmIdentifier): (data: Uint8Array<ArrayBuffer>) => Promise<Uint8Array<ArrayBuffer>> {\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 Digest from './digest.ts'\nimport type { MultihashHasher } from './interface.ts'\n\ntype Await<T> = Promise<T> | T\n\nconst DEFAULT_MIN_DIGEST_LENGTH = 20\n\nexport interface HasherInit <Name extends string, Code extends number> {\n name: Name\n code: Code\n encode(input: Uint8Array): Await<Uint8Array<ArrayBuffer>>\n\n /**\n * The minimum length a hash is allowed to be truncated to in bytes\n *\n * @default 20\n */\n minDigestLength?: number\n\n /**\n * The maximum length a hash is allowed to be truncated to in bytes. If not\n * specified it will be inferred from the length of the digest.\n */\n maxDigestLength?: number\n}\n\nexport function from <Name extends string, Code extends number> ({ name, code, encode, minDigestLength, maxDigestLength }: HasherInit<Name, Code>): MultihashHasher<Code> {\n return new Hasher(name, code, encode, minDigestLength, maxDigestLength)\n}\n\nexport interface DigestOptions {\n /**\n * Truncate the returned digest to this number of bytes.\n *\n * This may cause the digest method to throw/reject if the passed value is\n * greater than the digest length or below a threshold under which the risk of\n * hash collisions is significant.\n *\n * The actual value of this threshold can depend on the hashing algorithm in\n * use.\n */\n truncate?: number\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<ArrayBuffer>>\n readonly minDigestLength: number\n readonly maxDigestLength?: number\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await<Uint8Array<ArrayBuffer>>, minDigestLength?: number, maxDigestLength?: number) {\n this.name = name\n this.code = code\n this.encode = encode\n this.minDigestLength = minDigestLength ?? DEFAULT_MIN_DIGEST_LENGTH\n this.maxDigestLength = maxDigestLength\n }\n\n digest (input: Uint8Array, options?: DigestOptions): Await<Digest.Digest<Code, number>> {\n if (options?.truncate != null) {\n if (options.truncate < this.minDigestLength) {\n throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`)\n }\n\n if (this.maxDigestLength != null && options.truncate > this.maxDigestLength) {\n throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)\n }\n }\n\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n\n if (result instanceof Uint8Array) {\n return createDigest(result, this.code, options?.truncate)\n }\n\n return result.then(digest => createDigest(digest, this.code, options?.truncate))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n\n/**\n * Create a Digest from the passed uint8array and code, optionally truncating it\n * first.\n */\nfunction createDigest <Code extends number> (digest: Uint8Array, code: Code, truncate?: number): Digest.Digest<Code, number> {\n if (truncate != null && truncate !== digest.byteLength) {\n if (truncate > digest.byteLength) {\n throw new Error(`Invalid truncate option, must be less than or equal to ${digest.byteLength}`)\n }\n\n digest = digest.subarray(0, truncate)\n }\n\n return Digest.create(code, digest)\n}\n", "import { base32 } from './bases/base32.ts'\nimport { base36 } from './bases/base36.ts'\nimport { base58btc } from './bases/base58.ts'\nimport { coerce, toArrayBufferBackedArray } from './bytes.ts'\nimport * as Digest from './hashes/digest.ts'\nimport * as varint from './varint.ts'\nimport type * as API from './link/interface.ts'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.ts'\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<ArrayBuffer>\n readonly '/': Uint8Array<ArrayBuffer>\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 = toArrayBufferBackedArray(bytes)\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = 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 base10 from './bases/base10.ts'\nimport * as base16 from './bases/base16.ts'\nimport * as base2 from './bases/base2.ts'\nimport * as base256emoji from './bases/base256emoji.ts'\nimport * as base32 from './bases/base32.ts'\nimport * as base36 from './bases/base36.ts'\nimport * as base58 from './bases/base58.ts'\nimport * as base64 from './bases/base64.ts'\nimport * as base8 from './bases/base8.ts'\nimport * as identityBase from './bases/identity.ts'\nimport * as json from './codecs/json.ts'\nimport * as raw from './codecs/raw.ts'\nimport * as identity from './hashes/identity.ts'\nimport * as sha2 from './hashes/sha2.ts'\nimport { CID, hasher, digest, varint, bytes } from './index.ts'\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<ArrayBuffer>): 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 from './util/bases.ts'\nimport type { SupportedEncodings } from './util/bases.ts'\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<ArrayBuffer> {\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}`)\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<ArrayBuffer> {\n const SIZE = size ?? 8192\n const MAX = SIZE >>> 1\n let slab: Uint8Array<ArrayBuffer>\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.ts'\nimport { LongBits } from './longbits.ts'\nimport pool from './pool.ts'\nimport * as utf8 from './utf8.ts'\nimport type { Writer } from '../index.ts'\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<ArrayBuffer> {\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<ArrayBuffer> {\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.ts'\nimport type { Codec } from './codec.ts'\n\nexport function encodeMessage <T> (message: Partial<T>, codec: Pick<Codec<T>, 'encode'>): Uint8Array<ArrayBuffer> {\n const w = createWriter()\n\n codec.encode(message, w, {\n lengthDelimited: false\n })\n\n return w.finish()\n}\n", "import { createReader } from './utils/reader.ts'\nimport type { Codec } from './codec.ts'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport function * streamMessage <T> (buf: Uint8Array | Uint8ArrayList, codec: Pick<Codec<T>, 'stream'>, opts?: any): Generator<any> {\n const reader = createReader(buf)\n\n yield * codec.stream(reader, undefined, '$', opts)\n}\n", "import type { Writer, Reader } from './index.ts'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport const CODEC_TYPES = {\n VARINT: 0,\n BIT64: 1,\n LENGTH_DELIMITED: 2,\n START_GROUP: 3,\n END_GROUP: 4,\n BIT32: 5\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 StreamFunction<T> {\n (reader: Reader, length?: number, prefix?: string, opts?: DecodeOptions<T>): Generator<any>\n}\n\nexport interface Codec<T> {\n name: string\n type: number\n encode: EncodeFunction<T>\n decode: DecodeFunction<T>\n stream: StreamFunction<T>\n}\n\nexport function createCodec <T> (name: string, type: number, encode: EncodeFunction<T>, decode: DecodeFunction<T>, stream: StreamFunction<T>): Codec<T> {\n return {\n name,\n type,\n encode,\n decode,\n stream\n }\n}\n", "import { createCodec, CODEC_TYPES } from '../codec.ts'\nimport type { DecodeFunction, EncodeFunction, Codec, StreamFunction } from '../codec.ts'\n\nexport function enumeration <T> (v: any): Codec<T> {\n function findValue (val: any): 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<T> = function enumEncode (val, writer) {\n const enumValue = findValue(val)\n\n writer.int32(enumValue)\n }\n\n const decode: DecodeFunction<any> = function enumDecode (reader) {\n const val = reader.int32()\n\n return findValue(val)\n }\n\n const stream: StreamFunction<T> = function * enumStream (reader) {\n const val = reader.int32()\n\n yield findValue(val)\n }\n\n return createCodec<T>('enum', CODEC_TYPES.VARINT, encode, decode, stream)\n}\n", "import { createCodec, CODEC_TYPES } from '../codec.ts'\nimport type { EncodeFunction, DecodeFunction, Codec, StreamFunction } from '../codec.ts'\n\nexport interface Factory<A, T> {\n new (obj: A): T\n}\n\nexport function message <T> (encode: EncodeFunction<T>, decode: DecodeFunction<T>, stream: StreamFunction<T>): Codec<T> {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode, stream)\n}\n", "import { decodeMessage, encodeMessage, enumeration, message, streamMessage } from 'protons-runtime'\nimport type { Codec, DecodeOptions } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport enum KeyType {\n RSA = 'RSA',\n Ed25519 = 'Ed25519',\n secp256k1 = 'secp256k1',\n ECDSA = 'ECDSA'\n}\n\nenum __KeyTypeValues {\n RSA = 0,\n Ed25519 = 1,\n secp256k1 = 2,\n ECDSA = 3\n}\n\nexport namespace KeyType {\n export const codec = (): Codec<KeyType> => {\n return enumeration<KeyType>(__KeyTypeValues)\n }\n}\n\nexport interface PublicKeyMessage {\n Type?: number\n Data?: Uint8Array\n}\n\nexport namespace PublicKeyMessage {\n let _codec: Codec<PublicKeyMessage>\n\n export const codec = (): Codec<PublicKeyMessage> => {\n if (_codec == null) {\n _codec = message<PublicKeyMessage>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n w.int32(obj.Type)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\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.Type = reader.int32()\n break\n }\n case 2: {\n obj.Data = reader.bytes()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n }, function * (reader, length, prefix, opts = {}) {\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 yield {\n field: `${prefix}.Type`,\n value: reader.int32()\n }\n break\n }\n case 2: {\n yield {\n field: `${prefix}.Data`,\n value: reader.bytes()\n }\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n })\n }\n\n return _codec\n }\n\n export interface PublicKeyMessageTypeFieldEvent {\n field: '$.Type'\n value: number\n }\n\n export interface PublicKeyMessageDataFieldEvent {\n field: '$.Data'\n value: Uint8Array\n }\n\n export function encode (obj: Partial<PublicKeyMessage>): Uint8Array<ArrayBuffer> {\n return encodeMessage(obj, PublicKeyMessage.codec())\n }\n\n export function decode (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<PublicKeyMessage>): PublicKeyMessage {\n return decodeMessage(buf, PublicKeyMessage.codec(), opts)\n }\n\n export function stream (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<PublicKeyMessage>): Generator<PublicKeyMessageTypeFieldEvent | PublicKeyMessageDataFieldEvent> {\n return streamMessage(buf, PublicKeyMessage.codec(), opts)\n }\n}\n\nexport interface PrivateKeyMessage {\n Type?: number\n Data?: Uint8Array\n}\n\nexport namespace PrivateKeyMessage {\n let _codec: Codec<PrivateKeyMessage>\n\n export const codec = (): Codec<PrivateKeyMessage> => {\n if (_codec == null) {\n _codec = message<PrivateKeyMessage>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n w.int32(obj.Type)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\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.Type = reader.int32()\n break\n }\n case 2: {\n obj.Data = reader.bytes()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n }, function * (reader, length, prefix, opts = {}) {\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 yield {\n field: `${prefix}.Type`,\n value: reader.int32()\n }\n break\n }\n case 2: {\n yield {\n field: `${prefix}.Data`,\n value: reader.bytes()\n }\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n })\n }\n\n return _codec\n }\n\n export interface PrivateKeyMessageTypeFieldEvent {\n field: '$.Type'\n value: number\n }\n\n export interface PrivateKeyMessageDataFieldEvent {\n field: '$.Data'\n value: Uint8Array\n }\n\n export function encode (obj: Partial<PrivateKeyMessage>): Uint8Array<ArrayBuffer> {\n return encodeMessage(obj, PrivateKeyMessage.codec())\n }\n\n export function decode (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<PrivateKeyMessage>): PrivateKeyMessage {\n return decodeMessage(buf, PrivateKeyMessage.codec(), opts)\n }\n\n export function stream (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<PrivateKeyMessage>): Generator<PrivateKeyMessageTypeFieldEvent | PrivateKeyMessageDataFieldEvent> {\n return streamMessage(buf, PrivateKeyMessage.codec(), opts)\n }\n}\n", "import bases from './util/bases.ts'\nimport type { SupportedEncodings } from './util/bases.ts'\n\nexport type { SupportedEncodings }\n\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function toString (array: Uint8Array, encoding: SupportedEncodings = 'utf8'): string {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // strip multibase prefix\n return base.encoder.encode(array).substring(1)\n}\n", "import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { SupportedEncodings } from 'uint8arrays/to-string'\n\nconst pathSepS = '/'\nconst pathSepB = new TextEncoder().encode(pathSepS)\nconst pathSep = pathSepB[0]\n\n/**\n * A Key represents the unique identifier of an object.\n * Our Key scheme is inspired by file systems and Google App Engine key model.\n * Keys are meant to be unique across a system. Keys are hierarchical,\n * incorporating more and more specific namespaces. Thus keys can be deemed\n * 'children' or 'ancestors' of other keys:\n * - `new Key('/Comedy')`\n * - `new Key('/Comedy/MontyPython')`\n * Also, every namespace can be parametrized to embed relevant object\n * information. For example, the Key `name` (most specific namespace) could\n * include the object type:\n * - `new Key('/Comedy/MontyPython/Actor:JohnCleese')`\n * - `new Key('/Comedy/MontyPython/Sketch:CheeseShop')`\n * - `new Key('/Comedy/MontyPython/Sketch:CheeseShop/Character:Mousebender')`\n *\n */\nexport class Key {\n private _buf: Uint8Array\n\n /**\n * @param {string | Uint8Array} s\n * @param {boolean} [clean]\n */\n constructor (s: string | Uint8Array, clean?: boolean) {\n if (typeof s === 'string') {\n this._buf = uint8ArrayFromString(s)\n } else if (s instanceof Uint8Array) {\n this._buf = s\n } else {\n throw new Error('Invalid key, should be String of Uint8Array')\n }\n\n if (clean == null) {\n clean = true\n }\n\n if (clean) {\n this.clean()\n }\n\n if (this._buf.byteLength === 0 || this._buf[0] !== pathSep) {\n throw new Error('Invalid key')\n }\n }\n\n /**\n * Convert to the string representation\n *\n * @param {import('uint8arrays/to-string').SupportedEncodings} [encoding] - The encoding to use.\n * @returns {string}\n */\n toString (encoding: SupportedEncodings = 'utf8'): string {\n return uint8ArrayToString(this._buf, encoding)\n }\n\n /**\n * Return the Uint8Array representation of the key\n *\n * @returns {Uint8Array}\n */\n uint8Array (): Uint8Array {\n return this._buf\n }\n\n /**\n * Return string representation of the key\n *\n * @returns {string}\n */\n get [Symbol.toStringTag] (): string {\n return `Key(${this.toString()})`\n }\n\n /**\n * Constructs a key out of a namespace array.\n *\n * @param {Array<string>} list - The array of namespaces\n * @returns {Key}\n *\n * @example\n * ```js\n * Key.withNamespaces(['one', 'two'])\n * // => Key('/one/two')\n * ```\n */\n static withNamespaces (list: string[]): Key {\n return new Key(list.join(pathSepS))\n }\n\n /**\n * Returns a randomly (uuid) generated key.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * Key.random()\n * // => Key('/344502982398')\n * ```\n */\n static random (): Key {\n return new Key(Math.random().toString().substring(2))\n }\n\n /**\n * @param {*} other\n */\n static asKey (other: any): Key | null {\n if (other instanceof Uint8Array || typeof other === 'string') {\n // we can create a key from this\n return new Key(other)\n }\n\n if (typeof other.uint8Array === 'function') {\n // this is an older version or may have crossed the esm/cjs boundary\n return new Key(other.uint8Array())\n }\n\n return null\n }\n\n /**\n * Cleanup the current key\n *\n * @returns {void}\n */\n clean (): void {\n if (this._buf == null || this._buf.byteLength === 0) {\n this._buf = pathSepB\n }\n\n if (this._buf[0] !== pathSep) {\n const bytes = new Uint8Array(this._buf.byteLength + 1)\n bytes.fill(pathSep, 0, 1)\n bytes.set(this._buf, 1)\n this._buf = bytes\n }\n\n // normalize does not remove trailing slashes\n while (this._buf.byteLength > 1 && this._buf[this._buf.byteLength - 1] === pathSep) {\n this._buf = this._buf.subarray(0, -1)\n }\n }\n\n /**\n * Check if the given key is sorted lower than ourself.\n *\n * @param {Key} key - The other Key to check against\n * @returns {boolean}\n */\n less (key: Key): boolean {\n const list1 = this.list()\n const list2 = key.list()\n\n for (let i = 0; i < list1.length; i++) {\n if (list2.length < i + 1) {\n return false\n }\n\n const c1 = list1[i]\n const c2 = list2[i]\n\n if (c1 < c2) {\n return true\n } else if (c1 > c2) {\n return false\n }\n }\n\n return list1.length < list2.length\n }\n\n /**\n * Returns the key with all parts in reversed order.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').reverse()\n * // => Key('/Actor:JohnCleese/MontyPython/Comedy')\n * ```\n */\n reverse (): Key {\n return Key.withNamespaces(this.list().slice().reverse())\n }\n\n /**\n * Returns the `namespaces` making up this Key.\n *\n * @returns {Array<string>}\n */\n namespaces (): string[] {\n return this.list()\n }\n\n /**\n * Returns the \"base\" namespace of this key.\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').baseNamespace()\n * // => 'Actor:JohnCleese'\n * ```\n */\n baseNamespace (): string {\n const ns = this.namespaces()\n return ns[ns.length - 1]\n }\n\n /**\n * Returns the `list` representation of this key.\n *\n * @returns {Array<string>}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').list()\n * // => ['Comedy', 'MontyPythong', 'Actor:JohnCleese']\n * ```\n */\n list (): string[] {\n return this.toString().split(pathSepS).slice(1)\n }\n\n /**\n * Returns the \"type\" of this key (value of last namespace).\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').type()\n * // => 'Actor'\n * ```\n */\n type (): string {\n return namespaceType(this.baseNamespace())\n }\n\n /**\n * Returns the \"name\" of this key (field of last namespace).\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').name()\n * // => 'JohnCleese'\n * ```\n */\n name (): string {\n return namespaceValue(this.baseNamespace())\n }\n\n /**\n * Returns an \"instance\" of this type key (appends value to namespace).\n *\n * @param {string} s - The string to append.\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor').instance('JohnClesse')\n * // => Key('/Comedy/MontyPython/Actor:JohnCleese')\n * ```\n */\n instance (s: string): Key {\n return new Key(this.toString() + ':' + s)\n }\n\n /**\n * Returns the \"path\" of this key (parent + type).\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').path()\n * // => Key('/Comedy/MontyPython/Actor')\n * ```\n */\n path (): Key {\n let p = this.parent().toString()\n if (!p.endsWith(pathSepS)) {\n p += pathSepS\n }\n p += this.type()\n return new Key(p)\n }\n\n /**\n * Returns the `parent` Key of this Key.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key(\"/Comedy/MontyPython/Actor:JohnCleese\").parent()\n * // => Key(\"/Comedy/MontyPython\")\n * ```\n */\n parent (): Key {\n const list = this.list()\n if (list.length === 1) {\n return new Key(pathSepS)\n }\n\n return new Key(list.slice(0, -1).join(pathSepS))\n }\n\n /**\n * Returns the `child` Key of this Key.\n *\n * @param {Key} key - The child Key to add\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython').child(new Key('Actor:JohnCleese'))\n * // => Key('/Comedy/MontyPython/Actor:JohnCleese')\n * ```\n */\n child (key: Key): Key {\n if (this.toString() === pathSepS) {\n return key\n } else if (key.toString() === pathSepS) {\n return this\n }\n\n return new Key(this.toString() + key.toString(), false)\n }\n\n /**\n * Returns whether this key is a prefix of `other`\n *\n * @param {Key} other - The other key to test against\n * @returns {boolean}\n *\n * @example\n * ```js\n * new Key('/Comedy').isAncestorOf('/Comedy/MontyPython')\n * // => true\n * ```\n */\n isAncestorOf (other: Key): boolean {\n if (other.toString() === this.toString()) {\n return false\n }\n\n return other.toString().startsWith(this.toString())\n }\n\n /**\n * Returns whether this key is a contains another as prefix.\n *\n * @param {Key} other - The other Key to test against\n * @returns {boolean}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython').isDecendantOf('/Comedy')\n * // => true\n * ```\n */\n isDecendantOf (other: Key): boolean {\n if (other.toString() === this.toString()) {\n return false\n }\n\n return this.toString().startsWith(other.toString())\n }\n\n /**\n * Checks if this key has only one namespace.\n *\n * @returns {boolean}\n */\n isTopLevel (): boolean {\n return this.list().length === 1\n }\n\n /**\n * Concats one or more Keys into one new Key.\n *\n * @param {Array<Key>} keys - The array of keys to concatenate\n * @returns {Key}\n */\n concat (...keys: Key[]): Key {\n return Key.withNamespaces([...this.namespaces(), ...flatten(keys.map(key => key.namespaces()))])\n }\n}\n\n/**\n * The first component of a namespace. `foo` in `foo:bar`\n *\n * @param {string} ns\n * @returns {string}\n */\nfunction namespaceType (ns: string): string {\n const parts = ns.split(':')\n if (parts.length < 2) {\n return ''\n }\n return parts.slice(0, -1).join(':')\n}\n\n/**\n * The last component of a namespace, `baz` in `foo:bar:baz`.\n *\n * @param {string} ns\n * @returns {string}\n */\nfunction namespaceValue (ns: string): string {\n const parts = ns.split(':')\n return parts[parts.length - 1]\n}\n\n/**\n * Flatten array of arrays (only one level)\n *\n * @template T\n * @param {Array<any>} arr\n * @returns {T[]}\n */\nfunction flatten (arr: any[]): string[] {\n return ([]).concat(...arr)\n}\n", "import { PrivateKeyMessage, PublicKeyMessage } from '@ipshipyard/crypto/pb'\nimport { Key } from 'interface-datastore/key'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base64 } from 'multiformats/bases/base64'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport sanitize from 'sanitize-filename'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { withArrayBuffer } from 'uint8arrays/with-array-buffer'\nimport { DecryptionFailedError, InvalidParametersError } from './errors.ts'\nimport { privateKeyFromPEM } from './legacy.ts'\nimport type { Keychain as KeychainInterface, KeyInfo, GenerateKeyOptions, KeychainComponents, KeychainInit, Cipher, EncryptionResult, CipherOptions } from './index.ts'\nimport type { Crypto, PrivateKey, PublicKey } from '@ipshipyard/crypto'\nimport type { AbortOptions } from 'abort-error'\nimport type { Batch } from 'interface-datastore'\n\nconst keyPrefix = '/pkcs8/'\nconst infoPrefix = '/info/'\n\nconst serviceCapabilities = Symbol.for('@libp2p/service-capabilities')\n\n/**\n * Default options for key derivation for the keychain Data Encryption Key.\n *\n * Inherited from js-libp2p.\n *\n * @see https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#pbkdf2\n */\nconst KEYCHAIN_DEK_INIT = {\n iterations: 10_000,\n salt: uint8ArrayFromString('you should override this value with a crypto secure random number'),\n hash: 'SHA-512',\n algorithm: 'AES-GCM'\n}\n\n/**\n * Each private key is encrypted at rest with a Data Encryption Key created\n * from these parameters.\n *\n * Inherited from js-libp2p.\n */\nconst PRIVATE_KEY_DEK_INIT = {\n iterations: 32_767,\n saltLength: 16,\n ivLength: 12,\n hash: 'SHA-256',\n keyLength: 128,\n algorithm: 'AES-GCM'\n}\n\nconst MIN_PASS_LENGTH = 20\n\n// NIST SP 800-132\nconst NIST = {\n minKeyLength: 112 / 8,\n minSaltLength: 128 / 8,\n minIterations: 1_000\n}\n\nconst KEY_LENGTHS: Record<string, number> = {\n 'SHA-256': 128,\n 'SHA-384': 192,\n 'SHA-512': 256\n}\n\nfunction validateKeyName (name: string): boolean {\n if (name == null) {\n return false\n }\n\n if (typeof name !== 'string') {\n return false\n }\n\n return name === sanitize(name.trim()) && name.length > 0\n}\n\n/**\n * Converts a key name into a datastore name\n */\nfunction dsName (name: string): Key {\n return new Key(keyPrefix + name)\n}\n\n/**\n * Converts a key name into a datastore info name\n */\nfunction dsInfoName (name: string): Key {\n return new Key(infoPrefix + name)\n}\n\nasync function keyId (key: PrivateKey, options?: AbortOptions): Promise<string> {\n const pb = key.toProtobuf()\n const hash = await sha256.digest(pb)\n\n options?.signal?.throwIfAborted()\n\n return base58btc.encode(hash.bytes).substring(1)\n}\n\nfunction getSalt (salt?: string | Uint8Array): Uint8Array<ArrayBuffer> | undefined {\n if (typeof salt === 'string') {\n return uint8ArrayFromString(salt)\n }\n\n if (salt instanceof Uint8Array) {\n return withArrayBuffer(salt)\n }\n}\n\n/**\n * Manages the life cycle of a key. Keys are encrypted at rest using PKCS #8.\n *\n * A key in the store has two entries\n * - '/info/*key-name*', contains the KeyInfo for the key\n * - '/pkcs8/*key-name*', contains the PKCS #8 for the key\n */\nexport class Keychain implements KeychainInterface {\n private readonly components: KeychainComponents\n private readonly self: string\n private cipher: Cipher\n private salt: Uint8Array<ArrayBuffer>\n private keychainDekOptions: DeriveKeyOptions\n private privateKeyDekOptions: PrivateKeyDeriveKeyOptions\n\n /**\n * Creates a new instance of a key chain\n */\n constructor (components: KeychainComponents, init: KeychainInit = {}) {\n this.components = components\n this.self = init.selfKey ?? 'self'\n this.salt = getSalt(init.salt) ?? KEYCHAIN_DEK_INIT.salt\n\n this.keychainDekOptions = {\n iterations: init.iterations ?? KEYCHAIN_DEK_INIT.iterations,\n hash: init.hash ?? KEYCHAIN_DEK_INIT.hash,\n keyLength: KEY_LENGTHS[init.hash ?? KEYCHAIN_DEK_INIT.hash],\n algorithm: KEYCHAIN_DEK_INIT.algorithm\n }\n this.privateKeyDekOptions = {\n iterations: PRIVATE_KEY_DEK_INIT.iterations,\n hash: PRIVATE_KEY_DEK_INIT.hash,\n saltLength: PRIVATE_KEY_DEK_INIT.saltLength,\n ivLength: PRIVATE_KEY_DEK_INIT.ivLength,\n keyLength: PRIVATE_KEY_DEK_INIT.keyLength,\n algorithm: PRIVATE_KEY_DEK_INIT.algorithm\n }\n\n // Enforce NIST SP 800-132\n if (init.password != null && init.password.length < MIN_PASS_LENGTH) {\n throw new Error('password must be least 20 characters')\n }\n /*\n if (this.keyLength < NIST.minKeyLength) {\n throw new Error(`dek.keyLength must be least ${NIST.minKeyLength} bytes`)\n }\n*/\n if (this.salt.byteLength != null && this.salt.byteLength < NIST.minSaltLength) {\n throw new Error(`salt must be least ${NIST.minSaltLength} bytes`)\n }\n\n if (init.iterations != null && init.iterations < NIST.minIterations) {\n throw new Error(`iterations must be least ${NIST.minIterations}`)\n }\n\n if (KEY_LENGTHS[this.keychainDekOptions.hash] == null) {\n throw new InvalidParametersError('Unsupported hash')\n }\n\n this.cipher = createAESCipher(init.password ?? '', this.salt, this.keychainDekOptions, this.privateKeyDekOptions)\n }\n\n readonly [serviceCapabilities]: string[] = [\n '@ipshipyard/keychain'\n ]\n\n async generateKey (name: string, options?: GenerateKeyOptions): Promise<PrivateKey> {\n const crypto = await this.components.getCrypto(options?.type ?? 'Ed25519', options)\n const key = await crypto.generatePrivateKey(options)\n\n return this.importKey(name, key, options)\n }\n\n async importKey (name: string, key: PrivateKey, options?: AbortOptions): Promise<PrivateKey> {\n if (!validateKeyName(name)) {\n throw new InvalidParametersError(`Invalid key name '${name}'`)\n }\n\n if (key == null) {\n throw new InvalidParametersError('Key is required')\n }\n\n const exists = await this.components.datastore.has(dsName(name), options)\n\n if (exists) {\n throw new InvalidParametersError(`Key '${name}' already exists`)\n }\n\n const batch = this.components.datastore.batch()\n await this._importKey(name, key, this.cipher, batch, options)\n await batch.commit(options)\n\n return key\n }\n\n private async _importKey (name: string, privateKey: PrivateKey, cipher: Cipher, batch: Batch, options?: AbortOptions): Promise<void> {\n const pb = privateKey.toProtobuf()\n const result = await cipher.encrypt(pb)\n const cipherText = uint8ArrayConcat([\n result.salt,\n result.iv,\n result.cipherText\n ], result.salt.byteLength + result.iv.byteLength + result.cipherText.byteLength)\n const encodedText = base64.encode(cipherText)\n\n const keyInfo: KeyInfo = {\n name,\n id: await keyId(privateKey, options)\n }\n\n batch.put(dsName(name), uint8ArrayFromString(encodedText))\n batch.put(dsInfoName(name), uint8ArrayFromString(JSON.stringify(keyInfo)))\n }\n\n async exportKey (name: string, options?: AbortOptions): Promise<PrivateKey> {\n if (!validateKeyName(name)) {\n throw new InvalidParametersError(`Invalid key name '${name}'`)\n }\n\n return this._exportKey(name, this.cipher, options)\n }\n\n private async _exportKey (name: string, cipher: Cipher, options?: AbortOptions): Promise<PrivateKey> {\n const keyBuf = await this.components.datastore.get(dsName(name), options)\n const keyText = uint8ArrayToString(keyBuf)\n let cryptoImpl: Crypto | undefined\n\n // if the stored key is encrypted PEM it's legacy RSA, otherwise derive\n // from the protobuf data\n if (keyText.includes('BEGIN ENCRYPTED PRIVATE KEY')) {\n return privateKeyFromPEM(keyText, cipher, options)\n }\n\n try {\n const decoded = base64.decode(keyText)\n const salt = decoded.subarray(0, 16)\n const iv = decoded.subarray(16, 16 + 12)\n const cipherText = decoded.subarray(16 + 12)\n const plainText = await cipher.decrypt(salt, iv, cipherText, options)\n const pb = PrivateKeyMessage.decode(plainText)\n\n if (pb.Type == null) {\n throw new DecryptionFailedError('Unknown key type')\n }\n\n cryptoImpl = await this.components.getCrypto(pb.Type, options)\n return await cryptoImpl.privateKeyFromProtobuf(plainText)\n } catch (err: any) {\n if (err.name === 'OperationError') {\n throw new DecryptionFailedError(err.message)\n }\n\n throw err\n }\n }\n\n async removeKey (name: string, options?: AbortOptions): Promise<void> {\n if (!validateKeyName(name) || name === this.self) {\n throw new InvalidParametersError(`Invalid key name '${name}'`)\n }\n\n const batch = this.components.datastore.batch()\n batch.delete(dsName(name))\n batch.delete(dsInfoName(name))\n await batch.commit(options)\n }\n\n /**\n * List all the keys\n */\n async * listKeys (options?: AbortOptions): AsyncGenerator <KeyInfo> {\n const query = {\n prefix: infoPrefix\n }\n\n for await (const value of this.components.datastore.query(query, options)) {\n yield JSON.parse(uint8ArrayToString(value.value))\n }\n }\n\n /**\n * Rename a key\n *\n * @param {string} oldName - The old local key name; must already exist.\n * @param {string} newName - The new local key name; must not already exist.\n * @returns {Promise<KeyInfo>}\n */\n async renameKey (oldName: string, newName: string, options?: AbortOptions): Promise<void> {\n if (!validateKeyName(oldName) || oldName === this.self) {\n throw new InvalidParametersError(`Invalid old key name '${oldName}'`)\n }\n\n if (!validateKeyName(newName) || newName === this.self) {\n throw new InvalidParametersError(`Invalid new key name '${newName}'`)\n }\n\n const oldDatastoreName = dsName(oldName)\n const newDatastoreName = dsName(newName)\n const oldInfoName = dsInfoName(oldName)\n const newInfoName = dsInfoName(newName)\n\n const exists = await this.components.datastore.has(newDatastoreName, options)\n\n if (exists) {\n throw new InvalidParametersError(`Key '${newName}' already exists`)\n }\n\n const pem = await this.components.datastore.get(oldDatastoreName, options)\n const res = await this.components.datastore.get(oldInfoName, options)\n\n const keyInfo: KeyInfo = JSON.parse(uint8ArrayToString(res))\n keyInfo.name = newName\n\n const batch = this.components.datastore.batch()\n batch.put(newDatastoreName, pem)\n batch.put(newInfoName, uint8ArrayFromString(JSON.stringify(keyInfo)))\n batch.delete(oldDatastoreName)\n batch.delete(oldInfoName)\n\n await batch.commit(options)\n }\n\n /**\n * Rotate keychain password and re-encrypt all associated keys\n */\n async rotateKeychainPass (password: string, options?: AbortOptions): Promise<void> {\n if (typeof password !== 'string') {\n throw new InvalidParametersError(`Invalid new pass type '${typeof password}'`)\n }\n\n if (password.length < MIN_PASS_LENGTH) {\n throw new InvalidParametersError(`Invalid pass length ${password.length}, must be at least ${MIN_PASS_LENGTH}`)\n }\n\n const oldCipher = this.cipher\n const newCipher = this.cipher = createAESCipher(password, this.salt, this.keychainDekOptions, this.privateKeyDekOptions)\n\n const batch = this.components.datastore.batch()\n\n for await (const info of this.listKeys(options)) {\n const key = await this._exportKey(info.name, oldCipher)\n\n // Update stored key\n await this._importKey(info.name, key, newCipher, batch, options)\n }\n\n await batch.commit(options)\n }\n\n async loadPublicKeyFromProtobuf (buf: Uint8Array, options?: AbortOptions): Promise<PublicKey> {\n const pb = PublicKeyMessage.decode(buf)\n\n if (pb.Type == null) {\n throw new InvalidParametersError('Protobuf was missing Type')\n }\n\n const crypto = await this.components.getCrypto(pb.Type, options)\n\n return crypto.publicKeyFromProtobuf(buf, options)\n }\n}\n\n/**\n * WebKit on Linux does not support deriving a key from an empty PBKDF2 key.\n * So, as a workaround, we provide the generated key as a constant.\n *\n * Generated via:\n *\n * ```ts\n * const key = await crypto.subtle.importKey('raw', new Uint8Array(0), {\n * name: 'PBKDF2'\n * }, false, ['deriveKey'])\n *\n * const derivedKey = await crypto.subtle.deriveKey({\n * name: 'PBKDF2',\n * salt: new Uint8Array(16),\n * iterations: 32767,\n * hash: {\n * name: 'SHA-256'\n * }\n * }, key, {\n * name: 'AES-GCM',\n * length: 128\n * }, true, ['encrypt', 'decrypt'])\n *\n * const jwk = await crypto.subtle.exportKey('jwk', derivedKey)\n * ```\n */\nconst derivedEmptyPasswordKey = {\n alg: 'A128GCM',\n ext: true,\n /* spell-checker:disable-next-line */\n k: 'scm9jmO_4BJAgdwWGVulLg',\n key_ops: ['encrypt', 'decrypt'],\n kty: 'oct'\n}\n\ninterface DeriveKeyOptions {\n iterations: number\n hash: string\n keyLength: number\n algorithm: string\n}\n\ninterface PrivateKeyDeriveKeyOptions extends DeriveKeyOptions {\n /**\n * A random salt will be generated of this many bytes\n *\n * @default 16\n */\n saltLength: number\n\n /**\n * A random initialization vector will be generated of this many bytes\n *\n * @default 12\n */\n ivLength: number\n}\n\n// Based on code from https://github.com/luke-park/SecureCompatibleEncryptionExamples\n\nfunction createAESCipher (password: string, salt: Uint8Array<ArrayBuffer>, keychainDekOpts: DeriveKeyOptions, privateKeyDekOpts: PrivateKeyDeriveKeyOptions): Cipher {\n let keychainDek: string | undefined\n\n async function deriveKey (password: string, salt: Uint8Array, usages: KeyUsage[], opts: DeriveKeyOptions): Promise<CryptoKey> {\n let cryptoKey: CryptoKey\n const pass = uint8ArrayFromString(password)\n const rawKey = await crypto.subtle.importKey('raw', pass, {\n name: 'PBKDF2'\n }, false, ['deriveKey'])\n\n try {\n cryptoKey = await crypto.subtle.deriveKey({\n name: 'PBKDF2',\n salt: withArrayBuffer(salt),\n iterations: opts.iterations,\n hash: {\n name: opts.hash\n }\n }, rawKey, {\n name: opts.algorithm ?? 'AES-GCM',\n length: opts.keyLength\n }, true, usages)\n } catch (err) {\n if (password === '') {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, {\n name: opts.algorithm ?? 'AES-GCM'\n }, true, usages)\n } else {\n throw err\n }\n }\n\n return cryptoKey\n }\n\n async function createKeychainDek (): Promise<string> {\n if (password === '') {\n return password\n }\n\n const key = await deriveKey(password, salt, ['encrypt', 'decrypt'], keychainDekOpts)\n const jwk = await crypto.subtle.exportKey('jwk', key)\n\n return jwk.k ?? ''\n }\n\n /**\n * Encrypt data using the derived encryption key\n */\n async function encrypt (data: Uint8Array<ArrayBuffer>, opts?: AbortOptions): Promise<EncryptionResult> {\n if (keychainDek == null) {\n keychainDek = await createKeychainDek()\n }\n\n const salt = crypto.getRandomValues(new Uint8Array(privateKeyDekOpts.saltLength))\n const iv = crypto.getRandomValues(new Uint8Array(privateKeyDekOpts.ivLength))\n const cryptoKey = await deriveKey(keychainDek, salt, ['encrypt'], privateKeyDekOpts)\n const ciphertext = await crypto.subtle.encrypt({\n name: 'AES-GCM',\n iv\n }, cryptoKey, data)\n\n opts?.signal?.throwIfAborted()\n\n return {\n salt,\n iv,\n cipherText: new Uint8Array(ciphertext)\n }\n }\n\n /**\n * Decrypt data using the derived encryption key\n */\n async function decrypt (salt: Uint8Array, iv: Uint8Array, cipherText: Uint8Array, opts?: CipherOptions): Promise<Uint8Array<ArrayBuffer>> {\n if (keychainDek == null) {\n keychainDek = await createKeychainDek()\n }\n\n const cryptoKey = await deriveKey(keychainDek, salt, ['decrypt'], {\n iterations: opts?.iterations ?? privateKeyDekOpts.iterations,\n keyLength: opts?.keyLength ?? privateKeyDekOpts.keyLength,\n hash: opts?.hash ?? privateKeyDekOpts.hash,\n algorithm: opts?.algorithm ?? 'AES-GCM'\n })\n\n const plaintext = await crypto.subtle.decrypt({\n name: opts?.algorithm ?? 'AES-GCM',\n iv: withArrayBuffer(iv)\n }, cryptoKey, withArrayBuffer(cipherText))\n\n opts?.signal?.throwIfAborted()\n\n return new Uint8Array(plaintext)\n }\n\n return {\n encrypt,\n decrypt\n }\n}\n", "function isByteArrayWithArrayBuffer (b?: Uint8Array): b is Uint8Array<ArrayBuffer> {\n return b?.buffer instanceof ArrayBuffer\n}\n\n/**\n * To guarantee Uint8Array semantics, convert nodejs Buffers\n * into vanilla Uint8Arrays\n */\nexport function asUint8Array (buf: Uint8Array): Uint8Array<ArrayBuffer> {\n if (isByteArrayWithArrayBuffer(buf)) {\n return buf\n }\n\n const b = buf.slice()\n\n return new Uint8Array(b.buffer, 0, b.byteLength)\n}\n", "import { allocUnsafe } from '#alloc'\nimport { asUint8Array } from '#util/as-uint8array'\n\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nexport function concat (arrays: Uint8Array[], length?: number): Uint8Array<ArrayBuffer> {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0)\n }\n\n const output = allocUnsafe(length)\n let offset = 0\n\n for (const arr of arrays) {\n output.set(arr, offset)\n offset += arr.length\n }\n\n return asUint8Array(output)\n}\n", "export class InvalidParametersError extends Error {\n static name = 'InvalidParametersError'\n name = 'InvalidParametersError'\n}\n\nexport class DecryptionFailedError extends Error {\n static name = 'DecryptionFailedError'\n name = 'DecryptionFailedError'\n}\n", "/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n", "/**\n * @packageDocumentation\n *\n * A class that lets you do operations over a list of Uint8Arrays without\n * copying them.\n *\n * ```js\n * import { Uint8ArrayList } from 'uint8arraylist'\n *\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray()\n * // -> Uint8Array([0, 1, 2, 3, 4, 5])\n *\n * list.consume(3)\n * list.subarray()\n * // -> Uint8Array([3, 4, 5])\n *\n * // you can also iterate over the list\n * for (const buf of list) {\n * // ..do something with `buf`\n * }\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ## Converting Uint8ArrayLists to Uint8Arrays\n *\n * There are two ways to turn a `Uint8ArrayList` into a `Uint8Array` - `.slice` and `.subarray` and one way to turn a `Uint8ArrayList` into a `Uint8ArrayList` with different contents - `.sublist`.\n *\n * ### slice\n *\n * Slice follows the same semantics as [Uint8Array.slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice) in that it creates a new `Uint8Array` and copies bytes into it using an optional offset & length.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.slice(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ### subarray\n *\n * Subarray attempts to follow the same semantics as [Uint8Array.subarray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray) with one important different - this is a no-copy operation, unless the requested bytes span two internal buffers in which case it is a copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0]) - no-copy\n *\n * list.subarray(2, 5)\n * // -> Uint8Array([2, 3, 4]) - copy\n * ```\n *\n * ### sublist\n *\n * Sublist creates and returns a new `Uint8ArrayList` that shares the underlying buffers with the original so is always a no-copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.sublist(0, 1)\n * // -> Uint8ArrayList([0]) - no-copy\n *\n * list.sublist(2, 5)\n * // -> Uint8ArrayList([2], [3, 4]) - no-copy\n * ```\n *\n * ## Inspiration\n *\n * Borrows liberally from [bl](https://www.npmjs.com/package/bl) but only uses native JS types.\n */\nimport { allocUnsafe, alloc } from 'uint8arrays/alloc'\nimport { concat } from 'uint8arrays/concat'\nimport { equals } from 'uint8arrays/equals'\n\nconst symbol = Symbol.for('@achingbrain/uint8arraylist')\n\nexport type Appendable<T extends ArrayBufferLike = ArrayBuffer> = Uint8ArrayList<T> | Uint8Array<T>\n\nfunction findBufAndOffset (bufs: Uint8Array[], index: number): { buf: Uint8Array, index: number } {\n if (index == null || index < 0) {\n throw new RangeError('index is out of bounds')\n }\n\n let offset = 0\n\n for (const buf of bufs) {\n const bufEnd = offset + buf.byteLength\n\n if (index < bufEnd) {\n return {\n buf,\n index: index - offset\n }\n }\n\n offset = bufEnd\n }\n\n throw new RangeError('index is out of bounds')\n}\n\n/**\n * Check if object is a CID instance\n *\n * @example\n *\n * ```js\n * import { isUint8ArrayList, Uint8ArrayList } from 'uint8arraylist'\n *\n * isUint8ArrayList(true) // false\n * isUint8ArrayList([]) // false\n * isUint8ArrayList(new Uint8ArrayList()) // true\n * ```\n */\nexport function isUint8ArrayList (value: any): value is Uint8ArrayList {\n return Boolean(value?.[symbol])\n}\n\nexport class Uint8ArrayList <T extends ArrayBufferLike = ArrayBufferLike> implements Iterable<Uint8Array<T>> {\n private bufs: Uint8Array<T>[]\n public length: number\n public readonly [symbol] = true\n\n constructor (...data: Appendable<T>[]) {\n this.bufs = []\n this.length = 0\n\n if (data.length > 0) {\n this.appendAll(data)\n }\n }\n\n * [Symbol.iterator] (): Iterator<Uint8Array<T>> {\n yield * this.bufs\n }\n\n get byteLength (): number {\n return this.length\n }\n\n /**\n * Add one or more `bufs` to the end of this Uint8ArrayList\n */\n append (...bufs: Appendable<T>[]): void {\n this.appendAll(bufs)\n }\n\n /**\n * Add all `bufs` to the end of this Uint8ArrayList\n */\n appendAll (bufs: Appendable<T>[]): void {\n let length = 0\n\n for (const buf of bufs) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.push(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n for (const chunk of buf.bufs) {\n this.bufs.push(chunk)\n }\n } else {\n throw new Error('Could not append value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Add one or more `bufs` to the start of this Uint8ArrayList\n */\n prepend (...bufs: Appendable<T>[]): void {\n this.prependAll(bufs)\n }\n\n /**\n * Add all `bufs` to the start of this Uint8ArrayList\n */\n prependAll (bufs: Appendable<T>[]): void {\n let length = 0\n\n for (const buf of bufs.reverse()) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.unshift(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.unshift(...buf.bufs)\n } else {\n throw new Error('Could not prepend value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Read the value at `index`\n */\n get (index: number): number {\n const res = findBufAndOffset(this.bufs, index)\n\n return res.buf[res.index]\n }\n\n /**\n * Set the value at `index` to `value`\n */\n set (index: number, value: number): void {\n const res = findBufAndOffset(this.bufs, index)\n\n res.buf[res.index] = value\n }\n\n /**\n * Copy bytes from `buf` to the index specified by `offset`\n */\n write (buf: Appendable<T | ArrayBuffer>, offset: number = 0): void {\n if (buf instanceof Uint8Array) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf[i])\n }\n } else if (isUint8ArrayList(buf)) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf.get(i))\n }\n } else {\n throw new Error('Could not write value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n /**\n * Remove bytes from the front of the pool\n */\n consume (bytes: number): void {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes)\n\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) {\n return\n }\n\n // if consuming all bytes, skip iterating\n if (bytes === this.byteLength) {\n this.bufs = []\n this.length = 0\n return\n }\n\n while (this.bufs.length > 0) {\n if (bytes >= this.bufs[0].byteLength) {\n bytes -= this.bufs[0].byteLength\n this.length -= this.bufs[0].byteLength\n this.bufs.shift()\n } else {\n this.bufs[0] = this.bufs[0].subarray(bytes)\n this.length -= bytes\n break\n }\n }\n }\n\n /**\n * Extracts a section of an array and returns a new array.\n *\n * This is a copy operation as it is with Uint8Arrays and Arrays\n * - note this is different to the behaviour of Node Buffers.\n */\n slice (beginInclusive?: number, endExclusive?: number): Uint8Array<ArrayBuffer> {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n return concat(bufs, length)\n }\n\n /**\n * Returns a section of the array from the given start and end element index.\n *\n * This is a no-copy operation where the data extracted data comes from a\n * single Uint8Array internally, otherwise it is a copy operation.\n */\n subarray (beginInclusive?: number, endExclusive?: number): Uint8Array<T | ArrayBuffer> {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n if (bufs.length === 1) {\n return bufs[0]\n }\n\n return concat(bufs, length)\n }\n\n /**\n * Returns a new Uint8ArrayList from the given start and end element index.\n *\n * This is a no-copy operation.\n */\n sublist (beginInclusive?: number, endExclusive?: number): Uint8ArrayList<T> {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n const list = new Uint8ArrayList<T>()\n list.length = length\n // don't loop, just set the bufs\n list.bufs = bufs\n\n return list\n }\n\n private _subList (beginInclusive?: number, endExclusive?: number): { bufs: Uint8Array<T>[], length: number } {\n beginInclusive = beginInclusive ?? 0\n endExclusive = endExclusive ?? this.length\n\n if (beginInclusive < 0) {\n beginInclusive = this.length + beginInclusive\n }\n\n if (endExclusive < 0) {\n endExclusive = this.length + endExclusive\n }\n\n if (beginInclusive < 0 || endExclusive > this.length) {\n throw new RangeError('index is out of bounds')\n }\n\n if (beginInclusive === endExclusive) {\n return { bufs: [], length: 0 }\n }\n\n if (beginInclusive === 0 && endExclusive === this.length) {\n return { bufs: [...this.bufs], length: this.length }\n }\n\n const bufs: Uint8Array<T>[] = []\n let offset = 0\n\n for (let i = 0; i < this.bufs.length; i++) {\n const buf = this.bufs[i]\n const bufStart = offset\n const bufEnd = bufStart + buf.byteLength\n\n // for next loop\n offset = bufEnd\n\n if (beginInclusive >= bufEnd) {\n // start after this buf\n continue\n }\n\n const sliceStartInBuf = beginInclusive >= bufStart && beginInclusive < bufEnd\n const sliceEndsInBuf = endExclusive > bufStart && endExclusive <= bufEnd\n\n if (sliceStartInBuf && sliceEndsInBuf) {\n // slice is wholly contained within this buffer\n if (beginInclusive === bufStart && endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n const start = beginInclusive - bufStart\n bufs.push(buf.subarray(start, start + (endExclusive - beginInclusive)))\n break\n }\n\n if (sliceStartInBuf) {\n // slice starts in this buffer\n if (beginInclusive === 0) {\n // requested whole buffer\n bufs.push(buf)\n continue\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(beginInclusive - bufStart))\n continue\n }\n\n if (sliceEndsInBuf) {\n if (endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(0, endExclusive - bufStart))\n break\n }\n\n // slice started before this buffer and ends after it\n bufs.push(buf)\n }\n\n return { bufs, length: endExclusive - beginInclusive }\n }\n\n indexOf (search: Uint8ArrayList | Uint8Array, offset: number = 0): number {\n if (!isUint8ArrayList(search) && !(search instanceof Uint8Array)) {\n throw new TypeError('The \"value\" argument must be a Uint8ArrayList or Uint8Array')\n }\n\n const needle = search instanceof Uint8Array ? search : search.subarray()\n\n offset = Number(offset ?? 0)\n\n if (isNaN(offset)) {\n offset = 0\n }\n\n if (offset < 0) {\n offset = this.length + offset\n }\n\n if (offset < 0) {\n offset = 0\n }\n\n if (search.length === 0) {\n return offset > this.length ? this.length : offset\n }\n\n // https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm\n const M: number = needle.byteLength\n\n if (M === 0) {\n throw new TypeError('search must be at least 1 byte long')\n }\n\n // radix\n const radix: number = 256\n const rightmostPositions: Int32Array = new Int32Array(radix)\n\n // position of the rightmost occurrence of the byte c in the pattern\n for (let c: number = 0; c < radix; c++) {\n // -1 for bytes not in pattern\n rightmostPositions[c] = -1\n }\n\n for (let j = 0; j < M; j++) {\n // rightmost position for bytes in pattern\n rightmostPositions[needle[j]] = j\n }\n\n // Return offset of first match, -1 if no match\n const right = rightmostPositions\n const lastIndex = this.byteLength - needle.byteLength\n const lastPatIndex = needle.byteLength - 1\n let skip: number\n\n for (let i = offset; i <= lastIndex; i += skip) {\n skip = 0\n\n for (let j = lastPatIndex; j >= 0; j--) {\n const char: number = this.get(i + j)\n\n if (needle[j] !== char) {\n skip = Math.max(1, j - right[char])\n break\n }\n }\n\n if (skip === 0) {\n return i\n }\n }\n\n return -1\n }\n\n getInt8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt8(0)\n }\n\n setInt8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getInt16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt16(0, littleEndian)\n }\n\n setInt16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getInt32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt32(0, littleEndian)\n }\n\n setInt32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigInt64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigInt64(0, littleEndian)\n }\n\n setBigInt64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigInt64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint8(0)\n }\n\n setUint8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getUint16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint16(0, littleEndian)\n }\n\n setUint16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint32(0, littleEndian)\n }\n\n setUint32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigUint64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigUint64(0, littleEndian)\n }\n\n setBigUint64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigUint64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat32(0, littleEndian)\n }\n\n setFloat32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat64 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat64(0, littleEndian)\n }\n\n setFloat64 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n equals (other: any): other is Uint8ArrayList {\n if (other == null) {\n return false\n }\n\n if (!(other instanceof Uint8ArrayList)) {\n return false\n }\n\n if (other.bufs.length !== this.bufs.length) {\n return false\n }\n\n for (let i = 0; i < this.bufs.length; i++) {\n if (!equals(this.bufs[i], other.bufs[i])) {\n return false\n }\n }\n\n return true\n }\n\n /**\n * Create a Uint8ArrayList from a pre-existing list of Uint8Arrays. Use this\n * method if you know the total size of all the Uint8Arrays ahead of time.\n */\n static fromUint8Arrays <T extends ArrayBufferLike> (bufs: Uint8Array<T>[], length?: number): Uint8ArrayList<T> {\n const list = new Uint8ArrayList<T>()\n list.bufs = bufs\n\n if (length == null) {\n length = bufs.reduce((acc, curr) => acc + curr.byteLength, 0)\n }\n\n list.length = length\n\n return list\n }\n}\n\n/*\nfunction indexOf (needle: Uint8Array, haystack: Uint8Array, offset = 0) {\n for (let i = offset; i < haystack.byteLength; i++) {\n for (let j = 0; j < needle.length; j++) {\n if (haystack[i + j] !== needle[j]) {\n break\n }\n\n if (j === needle.byteLength -1) {\n return i\n }\n }\n\n if (haystack.byteLength - i < needle.byteLength) {\n break\n }\n }\n\n return -1\n}\n*/\n", "import { Uint8ArrayList } from 'uint8arraylist'\nimport { withArrayBuffer } from 'uint8arrays/with-array-buffer'\n\nexport interface Context {\n offset: number\n}\n\nconst TAG_MASK = parseInt('11111', 2)\nconst LONG_LENGTH_MASK = parseInt('10000000', 2)\nconst LONG_LENGTH_BYTES_MASK = parseInt('01111111', 2)\n\ninterface Decoder {\n (buf: Uint8Array, context: Context): any\n}\n\nconst decoders: Record<number, Decoder> = {\n 0x0: readSequence,\n 0x1: readSequence,\n 0x2: readInteger,\n 0x3: readBitString,\n 0x4: readOctetString,\n 0x5: readNull,\n 0x6: readObjectIdentifier,\n 0x10: readSequence,\n 0x16: readSequence,\n 0x30: readSequence\n}\n\nexport function decodeDer (buf: Uint8Array, context: Context = { offset: 0 }): any {\n const tag = buf[context.offset] & TAG_MASK\n context.offset++\n\n if (decoders[tag] != null) {\n return decoders[tag](buf, context)\n }\n\n throw new Error('No decoder for tag 0x' + tag.toString(16).padStart(2, '0'))\n}\n\nfunction readLength (buf: Uint8Array, context: Context): number {\n let length = 0\n\n if ((buf[context.offset] & LONG_LENGTH_MASK) === LONG_LENGTH_MASK) {\n // long length\n const count = buf[context.offset] & LONG_LENGTH_BYTES_MASK\n let str = '0x'\n context.offset++\n\n for (let i = 0; i < count; i++, context.offset++) {\n str += buf[context.offset].toString(16).padStart(2, '0')\n }\n\n length = parseInt(str, 16)\n } else {\n length = buf[context.offset]\n context.offset++\n }\n\n return length\n}\n\nfunction readSequence (buf: Uint8Array, context: Context): any[] {\n readLength(buf, context)\n const entries: any[] = []\n\n while (true) {\n if (context.offset >= buf.byteLength) {\n break\n }\n\n const result = decodeDer(buf, context)\n\n if (result === null) {\n break\n }\n\n entries.push(result)\n }\n\n return entries\n}\n\nfunction readInteger (buf: Uint8Array, context: Context): Uint8Array {\n const length = readLength(buf, context)\n const start = context.offset\n const end = context.offset + length\n\n const vals: number[] = []\n\n for (let i = start; i < end; i++) {\n if (i === start && buf[i] === 0) {\n continue\n }\n\n vals.push(buf[i])\n }\n\n context.offset += length\n\n return Uint8Array.from(vals)\n}\n\nfunction readObjectIdentifier (buf: Uint8Array, context: Context): string {\n const count = readLength(buf, context)\n const finalOffset = context.offset + count\n\n const byte = buf[context.offset]\n context.offset++\n\n let val1 = 0\n let val2 = 0\n\n if (byte < 40) {\n val1 = 0\n val2 = byte\n } else if (byte < 80) {\n val1 = 1\n val2 = byte - 40\n } else {\n val1 = 2\n val2 = byte - 80\n }\n\n let oid = `${val1}.${val2}`\n let num: number[] = []\n\n while (context.offset < finalOffset) {\n const byte = buf[context.offset]\n context.offset++\n\n // remove msb\n num.push(byte & 0b01111111)\n\n if (byte < 128) {\n num.reverse()\n\n // reached the end of the encoding\n let val = 0\n\n for (let i = 0; i < num.length; i++) {\n val += num[i] << (i * 7)\n }\n\n oid += `.${val}`\n num = []\n }\n }\n\n return oid\n}\n\nfunction readNull (buf: Uint8Array, context: Context): null {\n context.offset++\n\n return null\n}\n\nfunction readBitString (buf: Uint8Array, context: Context): any {\n const length = readLength(buf, context)\n const unusedBits = buf[context.offset]\n context.offset++\n const bytes = buf.subarray(context.offset, context.offset + length - 1)\n context.offset += length\n\n if (unusedBits !== 0) {\n // need to shift all bytes along by this many bits\n throw new Error('Unused bits in bit string is unimplemented')\n }\n\n return bytes\n}\n\nfunction readOctetString (buf: Uint8Array, context: Context): any {\n const length = readLength(buf, context)\n const bytes = buf.subarray(context.offset, context.offset + length)\n context.offset += length\n\n return bytes\n}\n\nfunction encodeNumber (value: number): Uint8ArrayList<ArrayBuffer> {\n let number = value.toString(16)\n\n if (number.length % 2 === 1) {\n number = '0' + number\n }\n\n const array = new Uint8ArrayList<ArrayBuffer>()\n\n for (let i = 0; i < number.length; i += 2) {\n array.append(Uint8Array.from([parseInt(`${number[i]}${number[i + 1]}`, 16)]))\n }\n\n return array\n}\n\nfunction encodeLength (bytes: { byteLength: number }): Uint8Array<ArrayBuffer> | Uint8ArrayList<ArrayBuffer> {\n if (bytes.byteLength < 128) {\n return Uint8Array.from([bytes.byteLength])\n }\n\n // long length\n const length = encodeNumber(bytes.byteLength)\n\n return new Uint8ArrayList(\n Uint8Array.from([\n length.byteLength | LONG_LENGTH_MASK\n ]),\n length\n )\n}\n\nexport function encodeInteger (value: Uint8Array | Uint8ArrayList): Uint8ArrayList {\n const contents = new Uint8ArrayList()\n\n const mask = 0b10000000\n const positive = (value.subarray()[0] & mask) === mask\n\n if (positive) {\n contents.append(Uint8Array.from([0]))\n }\n\n contents.append(value)\n\n return new Uint8ArrayList(\n Uint8Array.from([0x02]),\n encodeLength(contents),\n contents\n )\n}\n\nexport function encodeBitString (value: Uint8Array | Uint8ArrayList): Uint8ArrayList {\n // unused bits is always 0 with full-byte-only values\n const unusedBits = Uint8Array.from([0])\n\n const contents = new Uint8ArrayList(\n unusedBits,\n value\n )\n\n return new Uint8ArrayList(\n Uint8Array.from([0x03]),\n encodeLength(contents),\n contents\n )\n}\n\nexport function encodeOctetString (value: Uint8Array | Uint8ArrayList): Uint8ArrayList {\n return new Uint8ArrayList(\n Uint8Array.from([0x04]),\n encodeLength(value),\n value\n )\n}\n\nexport function encodeSequence (values: Array<Uint8Array | Uint8ArrayList>, tag = 0x30): Uint8ArrayList<ArrayBuffer> {\n const output = new Uint8ArrayList<ArrayBuffer>()\n\n for (const buf of values) {\n output.append(\n withArrayBuffer(buf.subarray())\n )\n }\n\n return new Uint8ArrayList(\n Uint8Array.from([tag]),\n encodeLength(output),\n output\n )\n}\n", "export class InvalidParametersError extends Error {\n static name = 'InvalidParametersError'\n name = 'InvalidParametersError'\n}\n", "import { CID } from 'multiformats'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base64url } from 'multiformats/bases/base64'\nimport { identity } from 'multiformats/hashes/identity'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { withArrayBuffer as uint8ArrayWithArrayBuffer } from 'uint8arrays/with-array-buffer'\nimport { decodeDer, encodeBitString, encodeInteger, encodeOctetString, encodeSequence } from './der.ts'\nimport { InvalidParametersError } from './errors.ts'\nimport { PrivateKeyMessage, PublicKeyMessage } from './pb.ts'\nimport type { Crypto, PrivateKey, PublicKey } from './index.ts'\nimport type { AbortOptions } from 'abort-error'\nimport type { MultihashDigest } from 'multiformats'\n\n// 1.2.840.10045.3.1.7 prime256v1 (ANSI X9.62 named elliptic curve)\nconst OID_256 = Uint8Array.from([0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07])\n// 1.3.132.0.34 secp384r1 (SECG (Certicom) named elliptic curve)\nconst OID_384 = Uint8Array.from([0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22])\n// 1.3.132.0.35 secp521r1 (SECG (Certicom) named elliptic curve)\nconst OID_521 = Uint8Array.from([0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23])\n\nconst P_256_KEY_JWK = {\n ext: true,\n kty: 'EC',\n crv: 'P-256'\n}\n\nconst P_384_KEY_JWK = {\n ext: true,\n kty: 'EC',\n crv: 'P-384'\n}\n\nconst P_521_KEY_JWK = {\n ext: true,\n kty: 'EC',\n crv: 'P-521'\n}\n\nconst P_256_KEY_LENGTH = 32\nconst P_384_KEY_LENGTH = 48\nconst P_521_KEY_LENGTH = 66\n\nclass ECDSAPublicKey implements PublicKey {\n public type = 'ECDSA'\n public code = 3\n public jwk: JsonWebKey\n\n constructor (jwk: JsonWebKey) {\n this.jwk = jwk\n }\n\n toMultihash (): MultihashDigest<0x00> {\n return identity.digest(this.toProtobuf())\n }\n\n toCID (): CID<unknown, 0x72, 0x00, 1> {\n return CID.createV1(0x72, this.toMultihash())\n }\n\n toString (): string {\n return base58btc.encode(this.toMultihash().bytes).substring(1)\n }\n\n toJWK (): JsonWebKey {\n return JSON.parse(JSON.stringify(this.jwk))\n }\n\n toProtobuf (): Uint8Array<ArrayBuffer> {\n return PublicKeyMessage.encode({\n Type: this.code,\n Data: publicKeyToPKIMessage(this.jwk)\n })\n }\n\n async verify (message: Uint8Array, signature: Uint8Array, options?: AbortOptions): Promise<boolean> {\n const key = await crypto.subtle.importKey('jwk', this.jwk, {\n name: 'ECDSA',\n namedCurve: this.jwk.crv ?? 'P-256'\n }, false, ['verify'])\n const isValid = await crypto.subtle.verify({\n name: 'ECDSA',\n hash: {\n name: 'SHA-256'\n }\n }, key, uint8ArrayWithArrayBuffer(signature), uint8ArrayWithArrayBuffer(message))\n options?.signal?.throwIfAborted()\n\n return isValid\n }\n}\n\nclass ECDSAPrivateKey implements PrivateKey {\n public type = 'ECDSA'\n public code = 3\n public jwk: JsonWebKey\n public publicKey: ECDSAPublicKey\n\n constructor (jwk: JsonWebKey, publicKey: ECDSAPublicKey) {\n this.jwk = jwk\n this.publicKey = publicKey\n }\n\n toProtobuf (): Uint8Array<ArrayBuffer> {\n return PrivateKeyMessage.encode({\n Type: this.code,\n Data: privateKeyToPKIMessage(this.jwk)\n })\n }\n\n toJWK (): JsonWebKey {\n return JSON.parse(JSON.stringify(this.jwk))\n }\n\n async sign (message: Uint8Array, options?: AbortOptions): Promise<Uint8Array<ArrayBuffer>> {\n const key = await crypto.subtle.importKey('jwk', this.jwk, {\n name: 'ECDSA',\n namedCurve: this.jwk.crv ?? 'P-256'\n }, true, ['sign'])\n const sig = await crypto.subtle.sign({\n name: 'ECDSA',\n hash: {\n name: 'SHA-256'\n }\n }, key, uint8ArrayWithArrayBuffer(message))\n options?.signal?.throwIfAborted()\n\n return new Uint8Array(sig, 0, sig.byteLength)\n }\n}\n\nexport interface CreateECDSAPrivateKeyOptions extends AbortOptions, Record<string, any> {\n /**\n * @default 'P-256'\n */\n curve?: 'P-256' | 'P-384' | 'P-521'\n}\n\nclass ECDSACrypto implements Crypto {\n type = 'ECDSA'\n code = 3\n\n async generatePrivateKey (options?: CreateECDSAPrivateKeyOptions): Promise<PrivateKey> {\n const curve = options?.curve ?? 'P-256'\n const keyPair = await crypto.subtle.generateKey({\n name: 'ECDSA',\n namedCurve: curve\n }, true, ['sign', 'verify'])\n\n const privateKeyJwk = await crypto.subtle.exportKey('jwk', keyPair.privateKey)\n const publicKeyJwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey)\n\n options?.signal?.throwIfAborted()\n\n return new ECDSAPrivateKey(privateKeyJwk, new ECDSAPublicKey(publicKeyJwk))\n }\n\n async publicKeyFromProtobuf (buf: Uint8Array, options?: AbortOptions): Promise<PublicKey> {\n const message = PublicKeyMessage.decode(buf)\n\n if (message.Data == null) {\n throw new InvalidParametersError('Data field was missing from protobuf')\n }\n\n if (message.Type !== this.code) {\n throw new InvalidParametersError('Incorrect Type field in protobuf')\n }\n\n options?.signal?.throwIfAborted()\n\n const publicKeyJwk = pkiToPublicJWK(message.Data)\n\n return new ECDSAPublicKey(publicKeyJwk)\n }\n\n async privateKeyFromProtobuf (buf: Uint8Array, options?: AbortOptions): Promise<PrivateKey> {\n const message = PrivateKeyMessage.decode(buf)\n\n if (message.Data == null) {\n throw new InvalidParametersError('Data field was missing from protobuf')\n }\n\n if (message.Type !== this.code) {\n throw new InvalidParametersError('Incorrect Type field in protobuf')\n }\n\n const privateKeyJwk = pkiMessageToPrivateJWK(message.Data)\n const publicKeyJwk = privateJWKToPublicJWK(privateKeyJwk)\n\n options?.signal?.throwIfAborted()\n\n return new ECDSAPrivateKey(privateKeyJwk, new ECDSAPublicKey(publicKeyJwk))\n }\n}\n\nexport function ecdsaCrypto (): Crypto {\n return new ECDSACrypto()\n}\n\nfunction privateJWKToPublicJWK (jwk: JsonWebKey): JsonWebKey {\n return {\n crv: jwk.crv,\n ext: true,\n key_ops: ['verify'],\n kty: 'EC',\n x: jwk.x,\n y: jwk.y\n }\n}\n\nfunction pkiMessageToPrivateJWK (buf: Uint8Array): JsonWebKey {\n const message = decodeDer(buf)\n const privateKey = message[1]\n const d = base64url.baseEncode(privateKey)\n const coordinates: Uint8Array = message[2][1][0]\n const offset = 1\n let x: string\n let y: string\n\n if (privateKey.byteLength === P_256_KEY_LENGTH) {\n x = base64url.baseEncode(coordinates.subarray(offset, offset + P_256_KEY_LENGTH))\n y = base64url.baseEncode(coordinates.subarray(offset + P_256_KEY_LENGTH))\n\n return {\n ...P_256_KEY_JWK,\n key_ops: ['sign'],\n d,\n x,\n y\n }\n }\n\n if (privateKey.byteLength === P_384_KEY_LENGTH) {\n x = base64url.baseEncode(coordinates.subarray(offset, offset + P_384_KEY_LENGTH))\n y = base64url.baseEncode(coordinates.subarray(offset + P_384_KEY_LENGTH))\n\n return {\n ...P_384_KEY_JWK,\n key_ops: ['sign'],\n d,\n x,\n y\n }\n }\n\n if (privateKey.byteLength === P_521_KEY_LENGTH) {\n x = base64url.baseEncode(coordinates.subarray(offset, offset + P_521_KEY_LENGTH))\n y = base64url.baseEncode(coordinates.subarray(offset + P_521_KEY_LENGTH))\n\n return {\n ...P_521_KEY_JWK,\n key_ops: ['sign'],\n d,\n x,\n y\n }\n }\n\n throw new InvalidParametersError(`Private key length was wrong length, got ${privateKey.byteLength}, expected 32, 48 or 66`)\n}\n\nfunction pkiToPublicJWK (buf: Uint8Array): JsonWebKey {\n const message = decodeDer(buf)\n\n const coordinates = message[1][1][0]\n const offset = 1\n let x: string\n let y: string\n\n if (coordinates.byteLength === ((P_256_KEY_LENGTH * 2) + 1)) {\n x = base64url.baseEncode(coordinates.subarray(offset, offset + P_256_KEY_LENGTH))\n y = base64url.baseEncode(coordinates.subarray(offset + P_256_KEY_LENGTH))\n\n return {\n ...P_256_KEY_JWK,\n key_ops: ['verify'],\n x,\n y\n }\n }\n\n if (coordinates.byteLength === ((P_384_KEY_LENGTH * 2) + 1)) {\n x = base64url.baseEncode(coordinates.subarray(offset, offset + P_384_KEY_LENGTH))\n y = base64url.baseEncode(coordinates.subarray(offset + P_384_KEY_LENGTH))\n\n return {\n ...P_384_KEY_JWK,\n key_ops: ['verify'],\n x,\n y\n }\n }\n\n if (coordinates.byteLength === ((P_521_KEY_LENGTH * 2) + 1)) {\n x = base64url.baseEncode(coordinates.subarray(offset, offset + P_521_KEY_LENGTH))\n y = base64url.baseEncode(coordinates.subarray(offset + P_521_KEY_LENGTH))\n\n return {\n ...P_521_KEY_JWK,\n key_ops: ['verify'],\n x,\n y\n }\n }\n\n throw new InvalidParametersError(`coordinates were wrong length, got ${coordinates.byteLength}, expected 65, 97 or 133`)\n}\n\nfunction publicKeyToPKIMessage (publicKey: JsonWebKey): Uint8Array {\n return encodeSequence([\n encodeInteger(Uint8Array.from([1])), // header\n encodeSequence([ // PKIProtection\n getOID(publicKey.crv)\n ], 0xA0),\n encodeSequence([ // extraCerts\n encodeBitString(\n new Uint8ArrayList(\n Uint8Array.from([0x04]),\n base64url.baseDecode(publicKey.x ?? ''),\n base64url.baseDecode(publicKey.y ?? '')\n )\n )\n ], 0xA1)\n ]).subarray()\n}\n\nfunction privateKeyToPKIMessage (privateKey: JsonWebKey): Uint8Array<ArrayBuffer> {\n return encodeSequence([\n encodeInteger(Uint8Array.from([1])), // header\n encodeOctetString(base64url.baseDecode(privateKey.d ?? '')), // body\n encodeSequence([ // PKIProtection\n getOID(privateKey.crv)\n ], 0xA0),\n encodeSequence([ // extraCerts\n encodeBitString(\n new Uint8ArrayList(\n Uint8Array.from([0x04]),\n base64url.baseDecode(privateKey.x ?? ''),\n base64url.baseDecode(privateKey.y ?? '')\n )\n )\n ], 0xA1)\n ]).subarray()\n}\n\nfunction getOID (curve?: string): Uint8Array<ArrayBuffer> {\n if (curve === 'P-256') {\n return OID_256\n }\n\n if (curve === 'P-384') {\n return OID_384\n }\n\n if (curve === 'P-521') {\n return OID_521\n }\n\n throw new InvalidParametersError(`Invalid curve ${curve}`)\n}\n", "import { CID } from 'multiformats'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base64url } from 'multiformats/bases/base64'\nimport { identity } from 'multiformats/hashes/identity'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { withArrayBuffer as uint8ArrayWithArrayBuffer } from 'uint8arrays/with-array-buffer'\nimport { InvalidParametersError } from './errors.ts'\nimport { PrivateKeyMessage, PublicKeyMessage } from './pb.ts'\nimport type { Crypto, PrivateKey, PublicKey } from './index.ts'\nimport type { AbortOptions } from 'abort-error'\nimport type { MultihashDigest } from 'multiformats'\n\nconst PRIVATE_KEY_LENGTH = 32\n\nclass Ed25519PublicKey implements PublicKey {\n public type = 'Ed25519'\n public code = 1\n public jwk: JsonWebKey\n\n constructor (jwk: JsonWebKey) {\n this.jwk = jwk\n }\n\n toMultihash (): MultihashDigest<0x00> {\n return identity.digest(this.toProtobuf())\n }\n\n toCID (): CID<unknown, 0x72, 0x00, 1> {\n return CID.createV1(0x72, this.toMultihash())\n }\n\n toString (): string {\n return base58btc.encode(this.toMultihash().bytes).substring(1)\n }\n\n toJWK (): JsonWebKey {\n return JSON.parse(JSON.stringify(this.jwk))\n }\n\n toProtobuf (): Uint8Array<ArrayBuffer> {\n return PublicKeyMessage.encode({\n Type: this.code,\n Data: base64url.baseDecode(this.jwk.x ?? '')\n })\n }\n\n async verify (message: Uint8Array, signature: Uint8Array, options?: AbortOptions): Promise<boolean> {\n const key = await crypto.subtle.importKey('jwk', this.jwk, {\n name: 'Ed25519'\n }, false, ['verify'])\n const isValid = await crypto.subtle.verify({\n name: 'Ed25519'\n }, key, uint8ArrayWithArrayBuffer(signature), uint8ArrayWithArrayBuffer(message))\n options?.signal?.throwIfAborted()\n\n return isValid\n }\n}\n\nclass Ed25519PrivateKey implements PrivateKey {\n public type = 'Ed25519'\n public code = 1\n public jwk: JsonWebKey\n public publicKey: Ed25519PublicKey\n\n constructor (jwk: JsonWebKey, publicKey: Ed25519PublicKey) {\n this.jwk = jwk\n this.publicKey = publicKey\n }\n\n toProtobuf (): Uint8Array<ArrayBuffer> {\n return PrivateKeyMessage.encode({\n Type: this.code,\n Data: uint8ArrayConcat([\n base64url.baseDecode(this.jwk.d ?? ''),\n base64url.baseDecode(this.jwk.x ?? '')\n ], 64)\n })\n }\n\n toJWK (): JsonWebKey {\n return JSON.parse(JSON.stringify(this.jwk))\n }\n\n async sign (message: Uint8Array, options?: AbortOptions): Promise<Uint8Array<ArrayBuffer>> {\n const key = await crypto.subtle.importKey('jwk', this.jwk, {\n name: 'Ed25519'\n }, true, ['sign'])\n const sig = await crypto.subtle.sign({\n name: 'Ed25519'\n }, key, uint8ArrayWithArrayBuffer(message))\n options?.signal?.throwIfAborted()\n\n return new Uint8Array(sig, 0, sig.byteLength)\n }\n}\n\nclass Ed25519Crypto implements Crypto {\n type = 'Ed25519'\n code = 1\n\n async generatePrivateKey (options?: AbortOptions & Record<string, any>): Promise<PrivateKey> {\n const keyPair = await crypto.subtle.generateKey('Ed25519', true, ['sign', 'verify'])\n const privateKeyJwk = await crypto.subtle.exportKey('jwk', keyPair.privateKey)\n const publicKeyJwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey)\n\n options?.signal?.throwIfAborted()\n\n return new Ed25519PrivateKey(privateKeyJwk, new Ed25519PublicKey(publicKeyJwk))\n }\n\n async publicKeyFromProtobuf (buf: Uint8Array, options?: AbortOptions): Promise<PublicKey> {\n const message = PublicKeyMessage.decode(buf)\n\n if (message.Data == null) {\n throw new InvalidParametersError('Data field was missing from protobuf')\n }\n\n if (message.Type !== this.code) {\n throw new InvalidParametersError('Incorrect Type field in protobuf')\n }\n\n options?.signal?.throwIfAborted()\n\n const publicKeyJwk = x5519ToPublicJWK(message.Data)\n\n return new Ed25519PublicKey(publicKeyJwk)\n }\n\n async privateKeyFromProtobuf (buf: Uint8Array, options?: AbortOptions): Promise<PrivateKey> {\n const message = PrivateKeyMessage.decode(buf)\n\n if (message.Data == null) {\n throw new InvalidParametersError('Data field was missing from protobuf')\n }\n\n if (message.Type !== this.code) {\n throw new InvalidParametersError('Incorrect Type field in protobuf')\n }\n\n const privateKeyJwk = await derivePrivateJWK(message.Data, options)\n const publicKeyJwk = privateJWKToPublicJWK(privateKeyJwk)\n\n return new Ed25519PrivateKey(privateKeyJwk, new Ed25519PublicKey(publicKeyJwk))\n }\n}\n\nexport function ed25519Crypto (): Crypto {\n return new Ed25519Crypto()\n}\n\nasync function derivePrivateJWK (raw: Uint8Array, options?: AbortOptions): Promise<JsonWebKey> {\n const privateKey = raw.subarray(0, PRIVATE_KEY_LENGTH)\n const pkcs8 = convertRawX25519KeyToPKCS(privateKey)\n const key = await crypto.subtle.importKey('pkcs8', pkcs8, {\n name: 'Ed25519'\n }, true, ['sign'])\n\n const jwk = await crypto.subtle.exportKey('jwk', key)\n\n options?.signal?.throwIfAborted()\n\n return jwk\n}\n\nconst PKCS8_HEADER = Uint8Array.from([\n 48, 46, 2, 1, 0, 48, 5, 6, 3, 43, 101, 112, 4, 34, 4\n])\n\nfunction convertRawX25519KeyToPKCS (privateKey: Uint8Array): Uint8Array<ArrayBuffer> {\n return uint8ArrayConcat([\n PKCS8_HEADER,\n Uint8Array.from([privateKey.byteLength]),\n privateKey\n ], PKCS8_HEADER.byteLength + 1 + privateKey.byteLength)\n}\n\nfunction privateJWKToPublicJWK (jwk: JsonWebKey): JsonWebKey {\n return {\n alg: 'Ed25519',\n crv: 'Ed25519',\n ext: true,\n key_ops: ['verify'],\n kty: 'OKP',\n x: jwk.x\n }\n}\n\nfunction x5519ToPublicJWK (buf: Uint8Array): JsonWebKey {\n return {\n alg: 'Ed25519',\n crv: 'Ed25519',\n ext: true,\n key_ops: ['verify'],\n kty: 'OKP',\n x: base64url.baseEncode(buf)\n }\n}\n", "import { CID } from 'multiformats'\nimport { base36 } from 'multiformats/bases/base36'\nimport { base64url } from 'multiformats/bases/base64'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { withArrayBuffer as uint8ArrayWithArrayBuffer } from 'uint8arrays/with-array-buffer'\nimport { decodeDer, encodeBitString, encodeInteger, encodeSequence } from './der.ts'\nimport { InvalidParametersError } from './errors.ts'\nimport { PrivateKeyMessage, PublicKeyMessage } from './pb.ts'\nimport type { Crypto, PrivateKey, PublicKey } from './index.ts'\nimport type { AbortOptions } from 'abort-error'\nimport type { MultihashDigest } from 'multiformats'\n\nexport const MAX_RSA_KEY_SIZE = 8192\n\nclass RSAPublicKey implements PublicKey {\n public type = 'RSA'\n public code = 0\n public _raw?: Uint8Array<ArrayBuffer>\n private digest: MultihashDigest<0x012>\n private jwk: JsonWebKey\n\n constructor (jwk: JsonWebKey, digest: MultihashDigest<0x012>) {\n if (rsaKeySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new InvalidParametersError('Key size is too large')\n }\n\n this.jwk = jwk\n this.digest = digest\n }\n\n toMultihash (): MultihashDigest<0x012> {\n return this.digest\n }\n\n toCID (): CID<unknown, 0x72, 0x12, 1> {\n return CID.createV1(0x72, this.toMultihash())\n }\n\n toString (): string {\n return this.toCID().toString(base36)\n }\n\n toProtobuf (): Uint8Array<ArrayBuffer> {\n return publicKeyToProtobuf(this.code, this.jwk)\n }\n\n toJWK (): JsonWebKey {\n return JSON.parse(JSON.stringify(this.jwk))\n }\n\n async verify (message: Uint8Array, signature: Uint8Array, options?: AbortOptions): Promise<boolean> {\n const key = await crypto.subtle.importKey('jwk', this.jwk, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: {\n name: 'SHA-256'\n }\n }, false, ['verify'])\n const result = await crypto.subtle.verify({\n name: 'RSASSA-PKCS1-v1_5'\n }, key, uint8ArrayWithArrayBuffer(signature), uint8ArrayWithArrayBuffer(message))\n options?.signal?.throwIfAborted()\n\n return result\n }\n}\n\nclass RSAPrivateKey implements PrivateKey {\n public type = 'RSA'\n public code = 0\n public publicKey: PublicKey\n private readonly jwk: JsonWebKey\n\n constructor (jwk: JsonWebKey, publicKey: PublicKey) {\n if (rsaKeySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new InvalidParametersError('Key size is too large')\n }\n\n this.jwk = jwk\n this.publicKey = publicKey\n }\n\n toProtobuf (): Uint8Array<ArrayBuffer> {\n return privateKeyToProtobuf(this.code, this.jwk)\n }\n\n toJWK (): JsonWebKey {\n return JSON.parse(JSON.stringify(this.jwk))\n }\n\n async sign (message: Uint8Array, options?: AbortOptions): Promise<Uint8Array<ArrayBuffer>> {\n const key = await crypto.subtle.importKey('jwk', this.jwk, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: {\n name: 'SHA-256'\n }\n }, false, ['sign'])\n const sig = await crypto.subtle.sign({\n name: 'RSASSA-PKCS1-v1_5'\n }, key, uint8ArrayWithArrayBuffer(message))\n\n options?.signal?.throwIfAborted()\n\n return new Uint8Array(sig, 0, sig.byteLength)\n }\n}\n\nexport interface CreateRSAPrivateKeyOptions extends AbortOptions, Record<string, any> {\n /**\n * The key size\n *\n * @default 2048\n */\n bits?: number\n}\n\nclass RSACrypto implements Crypto {\n public type = 'RSA'\n public code = 0\n\n async generatePrivateKey (options?: CreateRSAPrivateKeyOptions): Promise<PrivateKey> {\n const modulusLength = options?.bits ?? 2048\n\n if (modulusLength > MAX_RSA_KEY_SIZE) {\n throw new InvalidParametersError('Key size is too large')\n }\n\n const keypair = await crypto.subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: {\n name: 'SHA-256'\n }\n }, true, ['sign', 'verify'])\n\n const jwkPrivateKey = await crypto.subtle.exportKey('jwk', keypair.privateKey)\n const jwkPublicKey = await crypto.subtle.exportKey('jwk', keypair.publicKey)\n const digest = await publicKeyId(jwkPrivateKey)\n\n options?.signal?.throwIfAborted()\n\n return new RSAPrivateKey(jwkPrivateKey, new RSAPublicKey(jwkPublicKey, digest))\n }\n\n async publicKeyFromProtobuf (buf: Uint8Array, options?: AbortOptions): Promise<PublicKey> {\n const message = PublicKeyMessage.decode(buf)\n\n if (message.Data == null) {\n throw new InvalidParametersError('Data field was missing from protobuf')\n }\n\n if (message.Type !== this.code) {\n throw new InvalidParametersError('Incorrect Type field in protobuf')\n }\n\n const publicKeyJwk = pkixMessageToJwk(message.Data)\n const digest = await publicKeyId(publicKeyJwk)\n\n options?.signal?.throwIfAborted()\n\n return new RSAPublicKey(publicKeyJwk, digest)\n }\n\n async privateKeyFromProtobuf (buf: Uint8Array, options?: AbortOptions): Promise<PrivateKey> {\n const message = PrivateKeyMessage.decode(buf)\n\n if (message.Data == null) {\n throw new InvalidParametersError('Data field was missing from protobuf')\n }\n\n if (message.Type !== this.code) {\n throw new InvalidParametersError('Incorrect Type field in protobuf')\n }\n\n const pkcs1 = decodeDer(message.Data)\n const privateKeyJwk = pkcs1MessageToJwk(pkcs1)\n const publicKeyJwk = privateJWKToPublicJWK(privateKeyJwk)\n const digest = await publicKeyId(publicKeyJwk)\n\n options?.signal?.throwIfAborted()\n\n return new RSAPrivateKey(privateKeyJwk, new RSAPublicKey(publicKeyJwk, digest))\n }\n}\n\nexport function rsaCrypto (): Crypto {\n return new RSACrypto()\n}\n\n/**\n * Convert private key PKCS#1 in ASN1 DER format to JWK\n */\nfunction pkcs1MessageToJwk (message: Uint8Array[]): JsonWebKey {\n return {\n alg: 'RS256',\n kty: 'RSA',\n n: base64url.baseEncode(message[1]),\n e: base64url.baseEncode(message[2]),\n ext: true,\n key_ops: [\n 'sign'\n ],\n d: base64url.baseEncode(message[3]),\n p: base64url.baseEncode(message[4]),\n q: base64url.baseEncode(message[5]),\n dp: base64url.baseEncode(message[6]),\n dq: base64url.baseEncode(message[7]),\n qi: base64url.baseEncode(message[8])\n }\n}\n\n/**\n * Convert a JWK private key into PKCS#1 in ASN1 DER format\n */\nfunction jwkToPkcs1 (jwk: JsonWebKey): Uint8Array<ArrayBuffer> {\n if (jwk.n == null || jwk.e == null || jwk.d == null || jwk.p == null || jwk.q == null || jwk.dp == null || jwk.dq == null || jwk.qi == null) {\n throw new InvalidParametersError('JWK was missing components')\n }\n\n return encodeSequence([\n encodeInteger(Uint8Array.from([0])),\n encodeInteger(base64url.baseDecode(jwk.n)),\n encodeInteger(base64url.baseDecode(jwk.e)),\n encodeInteger(base64url.baseDecode(jwk.d)),\n encodeInteger(base64url.baseDecode(jwk.p)),\n encodeInteger(base64url.baseDecode(jwk.q)),\n encodeInteger(base64url.baseDecode(jwk.dp)),\n encodeInteger(base64url.baseDecode(jwk.dq)),\n encodeInteger(base64url.baseDecode(jwk.qi))\n ]).subarray()\n}\n\nconst RSA_ALGORITHM_IDENTIFIER = Uint8Array.from([\n 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00\n])\n\nfunction jwkToPkix (jwk: JsonWebKey): Uint8Array<ArrayBuffer> {\n if (jwk.n == null || jwk.e == null) {\n throw new InvalidParametersError('JWK public key was missing components')\n }\n\n const subjectPublicKeyInfo = encodeSequence([\n RSA_ALGORITHM_IDENTIFIER,\n encodeBitString(\n encodeSequence([\n encodeInteger(base64url.baseDecode(jwk.n)),\n encodeInteger(base64url.baseDecode(jwk.e))\n ])\n )\n ])\n\n return subjectPublicKeyInfo.subarray()\n}\n\nfunction pkixMessageToJwk (message: Uint8Array): JsonWebKey {\n const cert = decodeDer(message)\n\n if (cert.length < 2 || cert[0]?.[0] !== '1.2.840.113549.1.1.1') {\n throw new Error('PKIX certificate was invalid')\n }\n\n const keys = decodeDer(cert[1])\n\n return {\n kty: 'RSA',\n n: base64url.baseEncode(keys[0]),\n e: base64url.baseEncode(keys[1])\n }\n}\n\nfunction privateJWKToPublicJWK (jwk: JsonWebKey): JsonWebKey {\n return {\n key_ops: ['verify'],\n ext: true,\n alg: 'RS256',\n kty: 'RSA',\n n: jwk.n,\n // cspell:ignore AQAB\n e: 'AQAB'\n }\n}\n\nfunction rsaKeySize (jwk: JsonWebKey): number {\n if (jwk.kty !== 'RSA') {\n throw new InvalidParametersError('Invalid key type')\n } else if (jwk.n == null) {\n throw new InvalidParametersError('Invalid key modulus')\n }\n\n const modulus = base64url.baseDecode(jwk.n)\n return modulus.length * 8\n}\n\nasync function publicKeyId (jwk: JsonWebKey): Promise<MultihashDigest<0x12>> {\n const data = PublicKeyMessage.encode({\n Type: 0,\n Data: jwkToPkix(jwk)\n })\n\n return sha256.digest(data)\n}\n\nfunction publicKeyToProtobuf (code: number, jwk: JsonWebKey): Uint8Array<ArrayBuffer> {\n return PublicKeyMessage.encode({\n Type: code,\n Data: jwkToPkix(jwk)\n })\n}\n\nfunction privateKeyToProtobuf (code: number, jwk: JsonWebKey): Uint8Array<ArrayBuffer> {\n return PrivateKeyMessage.encode({\n Type: code,\n Data: jwkToPkcs1(jwk)\n })\n}\n", "import { rsaCrypto } from '@ipshipyard/crypto'\nimport { decodeDer } from '@ipshipyard/crypto/der'\nimport { PrivateKeyMessage } from '@ipshipyard/crypto/pb'\nimport { base64 } from 'multiformats/bases/base64'\nimport type { PrivateKey } from '@ipshipyard/crypto'\nimport type { AbortOptions } from 'abort-error'\n\n/**\n * Decode legacy RSA key stored as encrypted PEM files\n */\nexport async function privateKeyFromPEM (pem: string, cipher: any, options?: AbortOptions): Promise<PrivateKey> {\n pem = pem.replaceAll('-----BEGIN ENCRYPTED PRIVATE KEY-----', '')\n pem = pem.replaceAll('-----END ENCRYPTED PRIVATE KEY-----', '')\n pem = pem.replaceAll('\\r', '')\n pem = pem.replaceAll('\\n', '')\n\n const decoded = base64.decode(`m${pem}`)\n const der = decodeDer(decoded)\n\n // this looks fragile but DER is a canonical format so we are safe to have\n // deep property chains like this\n const salt = der[0][1][0][1][0]\n const iterations = toNumber(der[0][1][0][1][1])\n const keyLength = toNumber(der[0][1][0][1][2])\n const iv = der[0][1][0][1][4][1]\n const keyData = der[0][1][0][1][4][2]\n\n const plainText = await cipher.decrypt(salt, iv, keyData, {\n iterations,\n keyLength: keyLength * 8,\n hash: 'SHA-512',\n algorithm: 'AES-CBC',\n signal: options?.signal\n })\n\n const keyWrapper = decodeDer(plainText)\n const pkcs1 = keyWrapper[2]\n\n const pb = PrivateKeyMessage.encode({\n Type: 0,\n Data: pkcs1\n })\n\n return rsaCrypto().privateKeyFromProtobuf(pb)\n}\n\nfunction toNumber (buf: Uint8Array): number {\n if (buf.length === 0) {\n return 0\n }\n\n const str = [...buf]\n .map(n => n.toString(16).padStart(2, '0'))\n .join('')\n\n return parseInt(str, 16)\n}\n", "/**\n * @packageDocumentation\n *\n * A WebCrypto-first keychain implementation for use with Helia and libp2p.\n *\n * ## Configuring additional implementations\n *\n * ECDSA, Ed25519 and RSA keys are supported out of the box but other schemes\n * are configurable by passing a `CryptoLoader` that can return `Crypto`\n * instances.\n */\nimport { Keychain as KeychainClass } from './keychain.ts'\nimport type { Crypto, PrivateKey, PublicKey } from '@ipshipyard/crypto'\nimport type { AbortOptions } from 'abort-error'\nimport type { Datastore } from 'interface-datastore'\n\nexport interface CryptoLoader {\n (codeOrName: number | string, options?: AbortOptions): Crypto | Promise<Crypto>\n}\n\nexport interface CipherOptions extends AbortOptions {\n iterations?: number\n hash?: string\n keyLength?: number\n algorithm?: string\n}\n\nexport interface EncryptionResult {\n salt: Uint8Array<ArrayBuffer>\n iv: Uint8Array<ArrayBuffer>\n cipherText: Uint8Array<ArrayBuffer>\n}\n\nexport interface Cipher {\n encrypt(data: Uint8Array, options?: AbortOptions): Promise<EncryptionResult>\n decrypt(salt: Uint8Array, iv: Uint8Array, cipherText: Uint8Array, options?: CipherOptions): Promise<Uint8Array<ArrayBuffer>>\n}\n\nexport interface KeyInfo {\n /**\n * The hash of the key\n */\n id: string\n\n /**\n * The key name\n */\n name: string\n}\n\nexport interface GenerateKeyOptions extends AbortOptions, Record<string, any> {\n /**\n * The type of key to generate\n *\n * @default 'Ed25519'\n */\n type?: 'ECDSA' | 'Ed25519' | 'RSA' | string\n}\n\nexport interface KeychainInit {\n /**\n * The password is used to derive a key which encrypts the keychain at rest\n */\n password?: string\n\n /**\n * Specify a non-default PBK2 function salt\n */\n salt?: string\n\n /**\n * How many iterations to use when deriving a key from the password\n *\n * @default 10_000\n */\n iterations?: number\n\n /**\n * The hash type\n *\n * @default SHA2-512\n */\n hash?: 'SHA-256' | 'SHA-384' | 'SHA-512'\n\n /**\n * The 'self' key is the private key of the node from which the peer id is\n * derived.\n *\n * It cannot be renamed or removed.\n *\n * By default it is stored under the 'self' key, to use a different name, pass\n * this option.\n *\n * @default 'self'\n */\n selfKey?: string\n}\n\nexport interface KeychainComponents {\n datastore: Datastore\n getCrypto: CryptoLoader\n}\n\nexport interface Keychain {\n /**\n * Create a key of the passed type and store it under the specified name. A\n * cryptography implementation must be configured for the key type (defaults\n * to Ed25519).\n */\n generateKey (name: string, options?: AbortOptions & Record<string, any>): Promise<PrivateKey>\n\n /**\n * Import a new private key.\n *\n * The `type` parameter must match a supported cryptography implementation.\n *\n * The default supported key types are `Ed25519` and `RSA`, others may be\n * added through configuration.\n *\n * @example\n *\n * ```TypeScript\n * const key = await crypto.subtle.generateKey('Ed25519', true, ['sign', 'verify'])\n * const raw = await crypto.subtle.exportKey('raw', key)\n * await helia.keychain.importKey('my-key', 'Ed25519', raw)\n * ```\n */\n importKey(name: string, key: PrivateKey, options?: AbortOptions): Promise<PrivateKey>\n\n /**\n * Export an existing private key.\n *\n * @example\n *\n * ```TypeScript\n * const raw = await helia.exportKey('my-key')\n * const key = await crypto.subtle.importKey('raw', raw, {\n * name: 'Ed25519'\n * }, true, ['sign', 'verify'])\n * ```\n */\n exportKey(name: string, options?: AbortOptions): Promise<PrivateKey>\n\n /**\n * Removes a key from the keychain.\n *\n * @example\n *\n * ```TypeScript\n * await helia.keychain.removeKey('keyTest')\n * ```\n */\n removeKey(name: string, options?: AbortOptions): Promise<void>\n\n /**\n * Rename a key in the keychain. This is done in a batch commit with rollback\n * so errors thrown during the operation will not cause key loss.\n *\n * @example\n *\n * ```TypeScript\n * await helia.keychain.renameKey('oldName', 'newName')\n * ```\n */\n renameKey(oldName: string, newName: string, options?: AbortOptions): Promise<void>\n\n /**\n * List all the keys.\n *\n * @example\n *\n * ```TypeScript\n * for await (const name of helia.keychain.listKeys()) {\n * // ...\n * }\n * ```\n */\n listKeys(options?: AbortOptions): AsyncGenerator<KeyInfo>\n\n /**\n * Re-encrypt all keys in the keychain using a crypto graphic key derived\n * from the password\n *\n * @example\n *\n * ```TypeScript\n * await helia.keychain.rotateKeychainPass('newPassword')\n * ```\n */\n rotateKeychainPass(password: string, options?: AbortOptions): Promise<void>\n\n /**\n * Attempts to load a public key from a serialized protobuf message conforming\n * to the `PublicKey` message.\n */\n loadPublicKeyFromProtobuf (buf: Uint8Array, options?: AbortOptions): Promise<PublicKey>\n}\n\nexport function keychain (init?: KeychainInit): (components: KeychainComponents) => Keychain {\n return (components) => new KeychainClass(components, init)\n}\n", "/**\n * When this error is thrown it means an operation was aborted,\n * usually in response to the `abort` event being emitted by an\n * AbortSignal.\n */\nexport class AbortError extends Error {\n static name = 'AbortError'\n\n constructor (message: string = 'The operation was aborted') {\n super(message)\n this.name = 'AbortError'\n }\n}\n\n/**\n * Thrown when a remote Peer ID does not match the expected one\n */\nexport class UnexpectedPeerError extends Error {\n static name = 'UnexpectedPeerError'\n\n constructor (message = 'Unexpected Peer') {\n super(message)\n this.name = 'UnexpectedPeerError'\n }\n}\n\n/**\n * Thrown when a crypto exchange fails\n */\nexport class InvalidCryptoExchangeError extends Error {\n static name = 'InvalidCryptoExchangeError'\n\n constructor (message = 'Invalid crypto exchange') {\n super(message)\n this.name = 'InvalidCryptoExchangeError'\n }\n}\n\n/**\n * Thrown when invalid parameters are passed to a function or method call\n */\nexport class InvalidParametersError extends Error {\n static name = 'InvalidParametersError'\n\n constructor (message = 'Invalid parameters') {\n super(message)\n this.name = 'InvalidParametersError'\n }\n}\n\n/**\n * Thrown when a public key is invalid\n */\nexport class InvalidPublicKeyError extends Error {\n static name = 'InvalidPublicKeyError'\n\n constructor (message = 'Invalid public key') {\n super(message)\n this.name = 'InvalidPublicKeyError'\n }\n}\n\n/**\n * Thrown when a private key is invalid\n */\nexport class InvalidPrivateKeyError extends Error {\n static name = 'InvalidPrivateKeyError'\n\n constructor (message = 'Invalid private key') {\n super(message)\n this.name = 'InvalidPrivateKeyError'\n }\n}\n\n/**\n * Thrown when a operation is unsupported\n */\nexport class UnsupportedOperationError extends Error {\n static name = 'UnsupportedOperationError'\n\n constructor (message = 'Unsupported operation') {\n super(message)\n this.name = 'UnsupportedOperationError'\n }\n}\n\n/**\n * Thrown when a connection is closing\n */\nexport class ConnectionClosingError extends Error {\n static name = 'ConnectionClosingError'\n\n constructor (message = 'The connection is closing') {\n super(message)\n this.name = 'ConnectionClosingError'\n }\n}\n\n/**\n * Thrown when a connection is closed\n */\nexport class ConnectionClosedError extends Error {\n static name = 'ConnectionClosedError'\n\n constructor (message = 'The connection is closed') {\n super(message)\n this.name = 'ConnectionClosedError'\n }\n}\n\n/**\n * Thrown when a connection fails\n */\nexport class ConnectionFailedError extends Error {\n static name = 'ConnectionFailedError'\n\n constructor (message = 'Connection failed') {\n super(message)\n this.name = 'ConnectionFailedError'\n }\n}\n\n/**\n * Thrown when the muxer is closed and an attempt to open a stream occurs\n */\nexport class MuxerClosedError extends Error {\n static name = 'MuxerClosedError'\n\n constructor (message = 'The muxer is closed') {\n super(message)\n this.name = 'MuxerClosedError'\n }\n}\n\n/**\n * Thrown when a protocol stream is reset by the remote muxer\n */\nexport class StreamResetError extends Error {\n static name = 'StreamResetError'\n\n constructor (message = 'The stream has been reset') {\n super(message)\n this.name = 'StreamResetError'\n }\n}\n\n/**\n * Thrown when a protocol stream is aborted locally\n */\nexport class StreamAbortedError extends Error {\n static name = 'StreamAbortedError'\n\n constructor (message = 'The stream has been aborted') {\n super(message)\n this.name = 'StreamAbortedError'\n }\n}\n\n/**\n * Thrown when a stream is in an invalid state\n */\nexport class StreamStateError extends Error {\n static name = 'StreamStateError'\n\n constructor (message = 'The stream is in an invalid state') {\n super(message)\n this.name = 'StreamStateError'\n }\n}\n\n/**\n * Thrown when a stream buffer is full\n */\nexport class StreamBufferError extends Error {\n static name = 'StreamBufferError'\n\n constructor (message = 'The stream buffer was full') {\n super(message)\n this.name = 'StreamBufferError'\n }\n}\n\n/**\n * Thrown when a value could not be found\n */\nexport class NotFoundError extends Error {\n static name = 'NotFoundError'\n\n constructor (message = 'Not found') {\n super(message)\n this.name = 'NotFoundError'\n }\n}\n\n/**\n * Thrown when an invalid peer ID is encountered\n */\nexport class InvalidPeerIdError extends Error {\n static name = 'InvalidPeerIdError'\n\n constructor (message = 'Invalid PeerID') {\n super(message)\n this.name = 'InvalidPeerIdError'\n }\n}\n\n/**\n * Thrown when an invalid multiaddr is encountered\n */\nexport class InvalidMultiaddrError extends Error {\n static name = 'InvalidMultiaddrError'\n\n constructor (message = 'Invalid multiaddr') {\n super(message)\n this.name = 'InvalidMultiaddrError'\n }\n}\n\n/**\n * Thrown when an invalid CID is encountered\n */\nexport class InvalidCIDError extends Error {\n static name = 'InvalidCIDError'\n\n constructor (message = 'Invalid CID') {\n super(message)\n this.name = 'InvalidCIDError'\n }\n}\n\n/**\n * Thrown when an invalid multihash is encountered\n */\nexport class InvalidMultihashError extends Error {\n static name = 'InvalidMultihashError'\n\n constructor (message = 'Invalid Multihash') {\n super(message)\n this.name = 'InvalidMultihashError'\n }\n}\n\n/**\n * Thrown when a protocol is not supported\n */\nexport class UnsupportedProtocolError extends Error {\n static name = 'UnsupportedProtocolError'\n\n constructor (message = 'Unsupported protocol error') {\n super(message)\n this.name = 'UnsupportedProtocolError'\n }\n}\n\n/**\n * An invalid or malformed message was encountered during a protocol exchange\n */\nexport class InvalidMessageError extends Error {\n static name = 'InvalidMessageError'\n\n constructor (message = 'Invalid message') {\n super(message)\n this.name = 'InvalidMessageError'\n }\n}\n\n/**\n * Thrown when a remote peer sends a structurally valid message that does not\n * comply with the protocol\n */\nexport class ProtocolError extends Error {\n static name = 'ProtocolError'\n\n constructor (message = 'Protocol error') {\n super(message)\n this.name = 'ProtocolError'\n }\n}\n\n/**\n * Throw when an operation times out\n */\nexport class TimeoutError extends Error {\n static name = 'TimeoutError'\n\n constructor (message = 'Timed out') {\n super(message)\n this.name = 'TimeoutError'\n }\n}\n\n/**\n * Thrown when a startable component is interacted with but it has not been\n * started yet\n */\nexport class NotStartedError extends Error {\n static name = 'NotStartedError'\n\n constructor (message = 'Not started') {\n super(message)\n this.name = 'NotStartedError'\n }\n}\n\n/**\n * Thrown when a component is started that has already been started\n */\nexport class AlreadyStartedError extends Error {\n static name = 'AlreadyStartedError'\n\n constructor (message = 'Already started') {\n super(message)\n this.name = 'AlreadyStartedError'\n }\n}\n\n/**\n * Thrown when dialing an address failed\n */\nexport class DialError extends Error {\n static name = 'DialError'\n\n constructor (message = 'Dial error') {\n super(message)\n this.name = 'DialError'\n }\n}\n\n/**\n * Thrown when listening on an address failed\n */\nexport class ListenError extends Error {\n static name = 'ListenError'\n\n constructor (message = 'Listen error') {\n super(message)\n this.name = 'ListenError'\n }\n}\n\n/**\n * This error is thrown when a limited connection is encountered, i.e. if the\n * user tried to open a stream on a connection for a protocol that is not\n * configured to run over limited connections.\n */\nexport class LimitedConnectionError extends Error {\n static name = 'LimitedConnectionError'\n\n constructor (message = 'Limited connection') {\n super(message)\n this.name = 'LimitedConnectionError'\n }\n}\n\n/**\n * This error is thrown where there are too many inbound protocols streams open\n */\nexport class TooManyInboundProtocolStreamsError extends Error {\n static name = 'TooManyInboundProtocolStreamsError'\n\n constructor (message = 'Too many inbound protocol streams') {\n super(message)\n this.name = 'TooManyInboundProtocolStreamsError'\n }\n}\n\n/**\n * This error is thrown where there are too many outbound protocols streams open\n */\nexport class TooManyOutboundProtocolStreamsError extends Error {\n static name = 'TooManyOutboundProtocolStreamsError'\n\n constructor (message = 'Too many outbound protocol streams') {\n super(message)\n this.name = 'TooManyOutboundProtocolStreamsError'\n }\n}\n\n/**\n * Thrown when an attempt to operate on an unsupported key was made\n */\nexport class UnsupportedKeyTypeError extends Error {\n static name = 'UnsupportedKeyTypeError'\n\n constructor (message = 'Unsupported key type') {\n super(message)\n this.name = 'UnsupportedKeyTypeError'\n }\n}\n\n/**\n * Thrown when an operation has not been implemented\n */\nexport class NotImplementedError extends Error {\n static name = 'NotImplementedError'\n\n constructor (message = 'Not implemented') {\n super(message)\n this.name = 'NotImplementedError'\n }\n}\n", "/**\n * Implemented by components that have a life cycle\n */\nexport interface Startable {\n /**\n * If implemented, this method will be invoked before the start method.\n *\n * It should not assume any other components have been started.\n */\n beforeStart?(): void | Promise<void>\n\n /**\n * This method will be invoked to start the component.\n *\n * It should not assume that any other components have been started.\n */\n start(): void | Promise<void>\n\n /**\n * If implemented, this method will be invoked after the start method.\n *\n * All other components will have had their start method invoked before this method is called.\n */\n afterStart?(): void | Promise<void>\n\n /**\n * If implemented, this method will be invoked before the stop method.\n *\n * Any other components will still be running when this method is called.\n */\n beforeStop?(): void | Promise<void>\n\n /**\n * This method will be invoked to stop the component.\n *\n * It should not assume any other components are running when it is called.\n */\n stop(): void | Promise<void>\n\n /**\n * If implemented, this method will be invoked after the stop method.\n *\n * All other components will have had their stop method invoked before this method is called.\n */\n afterStop?(): void | Promise<void>\n}\n\n/**\n * Returns `true` if the object has type overlap with `Startable`\n */\nexport function isStartable (obj?: any): obj is Startable {\n return obj != null && typeof obj.start === 'function' && typeof obj.stop === 'function'\n}\n\n/**\n * A function that can be used to start and objects passed to it. This checks\n * that an object is startable before invoking its lifecycle methods so it is\n * safe to pass non-`Startable`s in.\n *\n * @example\n *\n * ```TypeScript\n * import { start } from '@libp2p/interface'\n * import type { Startable } from '@libp2p/interface'\n *\n * const startable: Startable = {\n * start: () => {},\n * stop: () => {}\n * }\n *\n * const notStartable = 5\n *\n * await start(\n * startable,\n * notStartable\n * )\n * ```\n */\nexport async function start (...objs: any[]): Promise<void> {\n const startables: Startable[] = []\n\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj)\n }\n }\n\n await Promise.all(\n startables.map(async s => {\n if (s.beforeStart != null) {\n await s.beforeStart()\n }\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n await s.start()\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n if (s.afterStart != null) {\n await s.afterStart()\n }\n })\n )\n}\n\n/**\n * A function that can be used to stop and objects passed to it. This checks\n * that an object is startable before invoking its lifecycle methods so it is\n * safe to pass non-`Startable`s in.\n *\n * @example\n *\n * ```TypeScript\n * import { stop } from '@libp2p/interface'\n * import type { Startable } from '@libp2p/interface'\n *\n * const startable: Startable = {\n * start: () => {},\n * stop: () => {}\n * }\n *\n * const notStartable = 5\n *\n * await stop(\n * startable,\n * notStartable\n * )\n * ```\n */\nexport async function stop (...objs: any[]): Promise<void> {\n const startables: Startable[] = []\n\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj)\n }\n }\n\n await Promise.all(\n startables.map(async s => {\n if (s.beforeStop != null) {\n await s.beforeStop()\n }\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n await s.stop()\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n if (s.afterStop != null) {\n await s.afterStop()\n }\n })\n )\n}\n", "/**\n * @packageDocumentation\n *\n * Adds types to the EventTarget class.\n *\n * Hopefully this won't be necessary\n * forever:\n *\n * - https://github.com/microsoft/TypeScript/issues/28357\n * - https://github.com/microsoft/TypeScript/issues/43477\n * - https://github.com/microsoft/TypeScript/issues/299\n * - https://www.npmjs.com/package/typed-events\n * - https://www.npmjs.com/package/typed-event-emitter\n * - https://www.npmjs.com/package/typed-event-target\n * - etc\n *\n * In addition to types, a `safeDispatchEvent` method is available which\n * prevents dispatching events that aren't in the event map, and a\n * `listenerCount` method which reports the number of listeners that are\n * currently registered for a given event.\n *\n * @example\n *\n * ```ts\n * import { TypedEventEmitter } from 'main-event'\n * import type { TypedEventTarget } from 'main-event'\n *\n * interface EventTypes {\n * 'test': CustomEvent<string>\n * }\n *\n * const target = new TypedEventEmitter<EventTypes>()\n *\n * // it's a regular EventTarget\n * console.info(target instanceof EventTarget) // true\n *\n * // register listeners normally\n * target.addEventListener('test', (evt) => {\n * // evt is CustomEvent<string>\n * })\n *\n * // @ts-expect-error 'derp' is not in the event map\n * target.addEventListener('derp', () => {})\n *\n * // use normal dispatchEvent method\n * target.dispatchEvent(new CustomEvent('test', {\n * detail: 'hello'\n * }))\n *\n * // use type safe dispatch method\n * target.safeDispatchEvent('test', {\n * detail: 'world'\n * })\n *\n * // report listener count\n * console.info(target.listenerCount('test')) // 0\n *\n * // event emitters can be used purely as interfaces too\n * function acceptTarget (target: TypedEventTarget<EventTypes>) {\n * // ...\n * }\n * ```\n */\n\nimport { setMaxListeners } from './events.ts'\n\nexport interface EventCallback<EventType> { (evt: EventType): void }\nexport interface EventObject<EventType> { handleEvent: EventCallback<EventType> }\nexport type EventHandler<EventType> = EventCallback<EventType> | EventObject<EventType>\n\ninterface Listener {\n once: boolean\n callback: any\n}\n\n/**\n *\n */\nexport interface TypedEventTarget <EventMap extends Record<string, any>> extends EventTarget {\n addEventListener<K extends keyof EventMap>(type: K, listener: EventHandler<EventMap[K]> | null, options?: boolean | AddEventListenerOptions): void\n\n listenerCount (type: string): number\n\n removeEventListener<K extends keyof EventMap>(type: K, listener?: EventHandler<EventMap[K]> | null, options?: boolean | EventListenerOptions): void\n\n removeEventListener (type: string, listener?: EventHandler<Event>, options?: boolean | EventListenerOptions): void\n\n safeDispatchEvent<Detail>(type: keyof EventMap, detail?: CustomEventInit<Detail>): boolean\n}\n\nfunction isEventObject <EventType> (obj?: any): obj is EventObject<EventType> {\n return typeof obj?.handleEvent === 'function'\n}\n\nfunction isOnce (options?: boolean | AddEventListenerOptions): boolean {\n return (options !== true && options !== false && options?.once) ?? false\n}\n\n/**\n * An implementation of a typed event target\n */\nexport class TypedEventEmitter<EventMap extends Record<string, any>> extends EventTarget implements TypedEventTarget<EventMap> {\n readonly #listeners = new Map<any, Listener[]>()\n\n constructor () {\n super()\n\n // silence MaxListenersExceededWarning warning on Node.js, this is a red\n // herring almost all of the time\n setMaxListeners(Infinity, this)\n }\n\n listenerCount (type: string): number {\n const listeners = this.#listeners.get(type)\n\n if (listeners == null) {\n return 0\n }\n\n return listeners.length\n }\n\n addEventListener<K extends keyof EventMap>(type: K, listener: EventHandler<EventMap[K]> | null, options?: boolean | AddEventListenerOptions): void\n addEventListener (type: string, listener: EventHandler<Event>, options?: boolean | AddEventListenerOptions): void {\n const once = isOnce(options)\n\n super.addEventListener(type, (evt) => {\n if (once) {\n let list = this.#listeners.get(evt.type)\n\n if (list != null) {\n list = list.filter(({ callback }) => callback !== listener)\n this.#listeners.set(evt.type, list)\n }\n }\n\n if (isEventObject<Event>(listener)) {\n listener.handleEvent(evt)\n } else {\n listener(evt)\n }\n }, options)\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n list = []\n this.#listeners.set(type, list)\n }\n\n list.push({\n callback: listener,\n once\n })\n }\n\n removeEventListener<K extends keyof EventMap>(type: K, listener?: EventHandler<EventMap[K]> | null, options?: boolean | EventListenerOptions): void\n removeEventListener (type: string, listener?: EventHandler<Event>, options?: boolean | EventListenerOptions): void {\n super.removeEventListener(type.toString(), listener ?? null, options)\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n return\n }\n\n list = list.filter(({ callback }) => callback !== listener)\n this.#listeners.set(type, list)\n }\n\n safeDispatchEvent<Detail>(type: keyof EventMap, detail: CustomEventInit<Detail> = {}): boolean {\n return this.dispatchEvent(new CustomEvent<Detail>(type as string, detail))\n }\n}\n\nexport { setMaxListeners }\n", "/**\n * Progress events are emitted during long running operations\n */\nexport interface ProgressEvent<T extends string = any, D = unknown> {\n /**\n * The event type\n */\n type: T\n\n /**\n * Context-specific event information\n */\n detail: D\n}\n\n/**\n * A callback function that receives progress events\n */\nexport interface ProgressEventListener<E extends ProgressEvent = any> {\n (evt: E): void\n}\n\n/**\n * An implementation of the ProgressEvent interface, this is essentially\n * a typed `CustomEvent` with a `type` property that lets us disambiguate\n * events passed to `progress` callbacks.\n */\nexport class CustomProgressEvent<D = unknown, T extends string = any> extends Event implements ProgressEvent<T, D> {\n public type: T\n public detail: D\n\n constructor (type: T, detail?: D) {\n super(type)\n\n this.type = type\n // @ts-expect-error detail may be undefined\n this.detail = detail\n }\n}\n\n/**\n * Define an `onProgress` callback that can be invoked with `ProgressEvent`s\n *\n * @example\n *\n * ```typescript\n * type MyOperationProgressEvents =\n * ProgressEvent<'operation:start'> |\n * ProgressEvent<'operation:success', Result> |\n * ProgressEvent<'operation:error', Error>\n *\n * export interface MyOperationOptions extends ProgressOptions<MyOperationProgressEvents> {\n * // define options here\n * }\n * ```\n */\nexport interface ProgressOptions<Event extends ProgressEvent = any> {\n onProgress?: ProgressEventListener<Event>\n}\n", "export class DNSQueryFailedError extends AggregateError {\n static name = 'DNSQueryFailedError'\n name = 'DNSQueryFailedError'\n}\n", "import EventEmitter from './index.js'\n\nexport { EventEmitter }\nexport default EventEmitter\n", "export class TimeoutError extends Error {\n\tname = 'TimeoutError';\n\n\tconstructor(message, options) {\n\t\tsuper(message, options);\n\t\tError.captureStackTrace?.(this, TimeoutError);\n\t}\n}\n\nconst getAbortedReason = signal => signal.reason ?? new DOMException('This operation was aborted.', 'AbortError');\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\tsignal,\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 (signal?.aborted) {\n\t\t\treject(getAbortedReason(signal));\n\t\t\treturn;\n\t\t}\n\n\t\tif (signal) {\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\t// Use .then() instead of async IIFE to preserve stack traces\n\t\t// eslint-disable-next-line promise/prefer-await-to-then, promise/prefer-catch\n\t\tpromise.then(resolve, reject);\n\n\t\tif (milliseconds === Number.POSITIVE_INFINITY) {\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\t// `.call(undefined, ...)` is needed for custom timers to avoid context issues\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\t});\n\n\t// eslint-disable-next-line promise/prefer-await-to-then\n\tconst cancelablePromise = wrappedPromise.finally(() => {\n\t\tcancelablePromise.clear();\n\t\tif (abortHandler && signal) {\n\t\t\tsignal.removeEventListener('abort', abortHandler);\n\t\t}\n\t});\n\n\tcancelablePromise.clear = () => {\n\t\t// `.call(undefined, ...)` is needed for custom timers to avoid context issues\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';\nconst compactionThreshold = 100;\nexport default class PriorityQueue {\n #queue = [];\n // The queue is stored as a sorted array, but dequeued items are left before `#head` until compaction. Only items from `#head` onward are live, which keeps repeated dequeues amortized O(1).\n #head = 0;\n enqueue(run, options) {\n const { priority = 0, id, } = options ?? {};\n const { size } = this;\n const element = {\n priority,\n id,\n run,\n };\n if (size === 0) {\n // When the queue is logically empty, discard any consumed prefix before accepting new work.\n this.#queue.length = 0;\n this.#head = 0;\n this.#queue.push(element);\n return;\n }\n if (this.#queue.at(-1).priority >= priority) {\n // Same-priority and lower-priority items belong after the current tail. Appending preserves FIFO order for equal priorities.\n this.#queue.push(element);\n return;\n }\n // Binary insertion must run on the live sorted range only.\n this.#compact();\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 // A dequeued item with the same id is no longer part of the queue.\n const index = this.#queue.findIndex((element, index) => index >= this.#head && 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 remove(idOrRun) {\n const index = this.#queue.findIndex((element, index) => {\n // The consumed prefix may still contain references that should not be removable.\n if (index < this.#head) {\n return false;\n }\n if (typeof idOrRun === 'string') {\n return element.id === idOrRun;\n }\n return element.run === idOrRun;\n });\n if (index !== -1) {\n this.#queue.splice(index, 1);\n }\n }\n dequeue() {\n if (this.#head === this.#queue.length) {\n return undefined;\n }\n const item = this.#queue[this.#head];\n this.#head++;\n if (this.#head === this.#queue.length) {\n // Fully drained queues are reset immediately so the next enqueue starts from a clean array.\n this.#queue.length = 0;\n this.#head = 0;\n }\n else if (this.#head > compactionThreshold && this.#head > this.#queue.length / 2) {\n // Keep repeated dequeues cheap, but stop the consumed prefix from growing without bound.\n this.#compact();\n }\n return item?.run;\n }\n filter(options) {\n const result = [];\n for (let index = this.#head; index < this.#queue.length; index++) {\n const element = this.#queue[index];\n if (element.priority === options.priority) {\n result.push(element.run);\n }\n }\n return result;\n }\n get size() {\n return this.#queue.length - this.#head;\n }\n #compact() {\n // Compaction restores the invariant that the whole array is the live sorted range.\n if (this.#head === 0) {\n return;\n }\n this.#queue.splice(0, this.#head);\n this.#head = 0;\n }\n}\n", "import { EventEmitter } from 'eventemitter3';\nimport pTimeout from 'p-timeout';\nimport PriorityQueue from './priority-queue.js';\n/**\nPromise queue with concurrency control.\n*/\nexport default class PQueue extends EventEmitter {\n #carryoverIntervalCount;\n #isIntervalIgnored;\n #intervalCount = 0;\n #intervalCap;\n #rateLimitedInInterval = false;\n #rateLimitFlushScheduled = false;\n #interval;\n #intervalEnd = 0;\n #lastExecutionTime = 0;\n #intervalId;\n #timeoutId;\n #strict;\n // Circular buffer implementation for better performance\n #strictTicks = [];\n #strictTicksStartIndex = 0;\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 // Use to assign a unique identifier to a promise function, if not explicitly specified\n #idAssigner = 1n;\n // Track currently running tasks for debugging\n #runningTasks = new Map();\n #queueAbortListenerCleanupFunctions = new Set();\n /**\n Get or set the default timeout for all tasks. Can be changed at runtime.\n\n Operations will throw a `TimeoutError` if they don't complete within the specified time.\n\n The timeout begins when the operation is dequeued and starts execution, not while it's waiting in the queue.\n\n @example\n ```\n const queue = new PQueue({timeout: 5000});\n\n // Change timeout for all future tasks\n queue.timeout = 10000;\n ```\n */\n timeout;\n constructor(options) {\n super();\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n options = {\n carryoverIntervalCount: false,\n intervalCap: Number.POSITIVE_INFINITY,\n interval: 0,\n concurrency: Number.POSITIVE_INFINITY,\n autoStart: true,\n queueClass: PriorityQueue,\n strict: false,\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 if (options.strict && options.interval === 0) {\n throw new TypeError('The `strict` option requires a non-zero `interval`');\n }\n if (options.strict && options.intervalCap === Number.POSITIVE_INFINITY) {\n throw new TypeError('The `strict` option requires a finite `intervalCap`');\n }\n // TODO: Remove this fallback in the next major version\n // eslint-disable-next-line @typescript-eslint/no-deprecated\n this.#carryoverIntervalCount = options.carryoverIntervalCount ?? options.carryoverConcurrencyCount ?? false;\n this.#isIntervalIgnored = options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0;\n this.#intervalCap = options.intervalCap;\n this.#interval = options.interval;\n this.#strict = options.strict;\n this.#queue = new options.queueClass();\n this.#queueClass = options.queueClass;\n this.concurrency = options.concurrency;\n if (options.timeout !== undefined && !(Number.isFinite(options.timeout) && options.timeout > 0)) {\n throw new TypeError(`Expected \\`timeout\\` to be a positive finite number, got \\`${options.timeout}\\` (${typeof options.timeout})`);\n }\n this.timeout = options.timeout;\n this.#isPaused = options.autoStart === false;\n this.#setupRateLimitTracking();\n }\n #cleanupStrictTicks(now) {\n // Remove ticks outside the current interval window using circular buffer approach\n while (this.#strictTicksStartIndex < this.#strictTicks.length) {\n const oldestTick = this.#strictTicks[this.#strictTicksStartIndex];\n if (oldestTick !== undefined && now - oldestTick >= this.#interval) {\n this.#strictTicksStartIndex++;\n }\n else {\n break;\n }\n }\n // Compact the array when it becomes inefficient or fully consumed\n // Compact when: (start index is large AND more than half wasted) OR all ticks expired\n const shouldCompact = (this.#strictTicksStartIndex > 100 && this.#strictTicksStartIndex > this.#strictTicks.length / 2)\n || this.#strictTicksStartIndex === this.#strictTicks.length;\n if (shouldCompact) {\n this.#strictTicks = this.#strictTicks.slice(this.#strictTicksStartIndex);\n this.#strictTicksStartIndex = 0;\n }\n }\n // Helper methods for interval consumption\n #consumeIntervalSlot(now) {\n if (this.#strict) {\n this.#strictTicks.push(now);\n }\n else {\n this.#intervalCount++;\n }\n }\n #rollbackIntervalSlot() {\n if (this.#strict) {\n // Pop from the end of the actual data (not from start index)\n if (this.#strictTicks.length > this.#strictTicksStartIndex) {\n this.#strictTicks.pop();\n }\n }\n else if (this.#intervalCount > 0) {\n this.#intervalCount--;\n }\n }\n #getActiveTicksCount() {\n return this.#strictTicks.length - this.#strictTicksStartIndex;\n }\n get #doesIntervalAllowAnother() {\n if (this.#isIntervalIgnored) {\n return true;\n }\n if (this.#strict) {\n // Cleanup already done by #isIntervalPausedAt before this is called\n return this.#getActiveTicksCount() < this.#intervalCap;\n }\n return this.#intervalCount < this.#intervalCap;\n }\n get #doesConcurrentAllowAnother() {\n return this.#pending < this.#concurrency;\n }\n #next() {\n this.#pending--;\n if (this.#pending === 0) {\n this.emit('pendingZero');\n }\n this.#tryToStartAnother();\n this.emit('next');\n }\n #onResumeInterval() {\n // Clear timeout ID before processing to prevent race condition\n // Must clear before #onInterval to allow new timeouts to be scheduled\n this.#timeoutId = undefined;\n this.#onInterval();\n this.#initializeIntervalIfNeeded();\n }\n #isIntervalPausedAt(now) {\n // Strict mode: check if we need to wait for oldest tick to age out\n if (this.#strict) {\n this.#cleanupStrictTicks(now);\n // If at capacity, need to wait for oldest tick to age out\n const activeTicksCount = this.#getActiveTicksCount();\n if (activeTicksCount >= this.#intervalCap) {\n const oldestTick = this.#strictTicks[this.#strictTicksStartIndex];\n // After cleanup, remaining ticks are within interval, so delay is always > 0\n const delay = this.#interval - (now - oldestTick);\n this.#createIntervalTimeout(delay);\n return true;\n }\n return false;\n }\n // Fixed window mode (original logic)\n if (this.#intervalId === undefined) {\n const delay = this.#intervalEnd - now;\n if (delay < 0) {\n // If the interval has expired while idle, check if we should enforce the interval\n // from the last task execution. This ensures proper spacing between tasks even\n // when the queue becomes empty and then new tasks are added.\n if (this.#lastExecutionTime > 0) {\n const timeSinceLastExecution = now - this.#lastExecutionTime;\n if (timeSinceLastExecution < this.#interval) {\n // Not enough time has passed since the last task execution\n this.#createIntervalTimeout(this.#interval - timeSinceLastExecution);\n return true;\n }\n }\n // Enough time has passed or no previous execution, allow execution\n this.#intervalCount = (this.#carryoverIntervalCount) ? this.#pending : 0;\n }\n else {\n // Act as the interval is pending\n this.#createIntervalTimeout(delay);\n return true;\n }\n }\n return false;\n }\n #createIntervalTimeout(delay) {\n if (this.#timeoutId !== undefined) {\n return;\n }\n this.#timeoutId = setTimeout(() => {\n this.#onResumeInterval();\n }, delay);\n }\n #clearIntervalTimer() {\n if (this.#intervalId) {\n clearInterval(this.#intervalId);\n this.#intervalId = undefined;\n }\n }\n #clearTimeoutTimer() {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId);\n this.#timeoutId = undefined;\n }\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 this.#clearIntervalTimer();\n this.emit('empty');\n if (this.#pending === 0) {\n // Clear timeout as well when completely idle\n this.#clearTimeoutTimer();\n // Compact strict ticks when idle to free memory\n if (this.#strict && this.#strictTicksStartIndex > 0) {\n const now = Date.now();\n this.#cleanupStrictTicks(now);\n }\n this.emit('idle');\n }\n return false;\n }\n let taskStarted = false;\n if (!this.#isPaused) {\n const now = Date.now();\n const canInitializeInterval = !this.#isIntervalPausedAt(now);\n if (this.#doesIntervalAllowAnother && this.#doesConcurrentAllowAnother) {\n const job = this.#queue.dequeue();\n if (!this.#isIntervalIgnored) {\n this.#consumeIntervalSlot(now);\n this.#scheduleRateLimitUpdate();\n }\n this.emit('active');\n job();\n if (canInitializeInterval) {\n this.#initializeIntervalIfNeeded();\n }\n taskStarted = true;\n }\n }\n return taskStarted;\n }\n #initializeIntervalIfNeeded() {\n if (this.#isIntervalIgnored || this.#intervalId !== undefined) {\n return;\n }\n // Strict mode uses timeouts instead of interval timers\n if (this.#strict) {\n return;\n }\n this.#intervalId = setInterval(() => {\n this.#onInterval();\n }, this.#interval);\n this.#intervalEnd = Date.now() + this.#interval;\n }\n #onInterval() {\n // Non-strict mode uses interval timers and intervalCount\n if (!this.#strict) {\n if (this.#intervalCount === 0 && this.#pending === 0 && this.#intervalId) {\n this.#clearIntervalTimer();\n }\n this.#intervalCount = this.#carryoverIntervalCount ? this.#pending : 0;\n }\n this.#processQueue();\n this.#scheduleRateLimitUpdate();\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 /**\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 if (typeof priority !== 'number' || !Number.isFinite(priority)) {\n throw new TypeError(`Expected \\`priority\\` to be a finite number, got \\`${priority}\\` (${typeof priority})`);\n }\n this.#queue.setPriority(id, priority);\n }\n async add(function_, options = {}) {\n // Create a copy to avoid mutating the original options object\n options = {\n timeout: this.timeout,\n ...options,\n // Assign unique ID if not provided\n id: options.id ?? (this.#idAssigner++).toString(),\n };\n return new Promise((resolve, reject) => {\n // Create a unique symbol for tracking this task\n const taskSymbol = Symbol(`task-${options.id}`);\n let cleanupQueueAbortHandler = () => undefined;\n const run = async () => {\n // Task is now running \u2014 remove the queued-state abort listener\n cleanupQueueAbortHandler();\n this.#pending++;\n // Track this running task\n this.#runningTasks.set(taskSymbol, {\n id: options.id,\n priority: options.priority ?? 0, // Match priority-queue default\n startTime: Date.now(),\n timeout: options.timeout,\n });\n let eventListener;\n try {\n // Check abort signal - if aborted, need to decrement the counter\n // that was incremented in tryToStartAnother\n try {\n options.signal?.throwIfAborted();\n }\n catch (error) {\n this.#rollbackIntervalConsumption();\n // Clean up tracking before throwing\n this.#runningTasks.delete(taskSymbol);\n throw error;\n }\n this.#lastExecutionTime = Date.now();\n let operation = function_({ signal: options.signal });\n if (options.timeout) {\n operation = pTimeout(Promise.resolve(operation), {\n milliseconds: options.timeout,\n message: `Task timed out after ${options.timeout}ms (queue has ${this.#pending} running, ${this.#queue.size} waiting)`,\n });\n }\n if (options.signal) {\n const { signal } = options;\n operation = Promise.race([operation, new Promise((_resolve, reject) => {\n eventListener = () => {\n reject(signal.reason);\n };\n signal.addEventListener('abort', eventListener, { once: true });\n })]);\n }\n const result = await operation;\n resolve(result);\n this.emit('completed', result);\n }\n catch (error) {\n reject(error);\n this.emit('error', error);\n }\n finally {\n // Clean up abort event listener\n if (eventListener) {\n options.signal?.removeEventListener('abort', eventListener);\n }\n // Remove from running tasks\n this.#runningTasks.delete(taskSymbol);\n // Use queueMicrotask to prevent deep recursion while maintaining timing\n queueMicrotask(() => {\n this.#next();\n });\n }\n };\n this.#queue.enqueue(run, options);\n const removeQueuedTask = () => {\n if (this.#queue instanceof PriorityQueue) {\n this.#queue.remove(run);\n return;\n }\n this.#queue.remove?.(options.id); // Intentionally best-effort: queued abort removal is only supported for queue classes that implement `.remove()`.\n };\n // Handle abort while task is waiting in the queue\n if (options.signal) {\n const { signal } = options;\n const queueAbortHandler = () => {\n cleanupQueueAbortHandler();\n removeQueuedTask();\n reject(signal.reason);\n this.#tryToStartAnother();\n this.emit('next');\n };\n cleanupQueueAbortHandler = () => {\n signal.removeEventListener('abort', queueAbortHandler);\n this.#queueAbortListenerCleanupFunctions.delete(cleanupQueueAbortHandler);\n };\n if (signal.aborted) {\n queueAbortHandler();\n return;\n }\n signal.addEventListener('abort', queueAbortHandler, { once: true });\n this.#queueAbortListenerCleanupFunctions.add(cleanupQueueAbortHandler);\n }\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 for (const cleanupQueueAbortHandler of this.#queueAbortListenerCleanupFunctions) {\n cleanupQueueAbortHandler();\n }\n this.#queue = new this.#queueClass();\n // Clear interval timer since queue is now empty (consistent with #tryToStartAnother)\n this.#clearIntervalTimer();\n // Note: We preserve strict mode rate-limiting state (ticks and timeout)\n // because clear() only clears queued tasks, not rate limit history.\n // This ensures that rate limits are still enforced after clearing the queue.\n // Note: We don't clear #runningTasks as those tasks are still running\n // They will be removed when they complete in the finally block\n // Force synchronous update since clear() should have immediate effect\n this.#updateRateLimitState();\n // Emit events so waiters (onEmpty, onIdle, onSizeLessThan) can resolve\n this.emit('empty');\n if (this.#pending === 0) {\n this.#clearTimeoutTimer();\n this.emit('idle');\n }\n this.emit('next');\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 /**\n The difference with `.onIdle` is that `.onPendingZero` only waits for currently running tasks to finish, ignoring queued tasks.\n\n @returns A promise that settles when all currently running tasks have completed; `queue.pending === 0`.\n */\n async onPendingZero() {\n if (this.#pending === 0) {\n return;\n }\n await this.#onEvent('pendingZero');\n }\n /**\n @returns A promise that settles when the queue becomes rate-limited due to intervalCap.\n */\n async onRateLimit() {\n if (this.isRateLimited) {\n return;\n }\n await this.#onEvent('rateLimit');\n }\n /**\n @returns A promise that settles when the queue is no longer rate-limited.\n */\n async onRateLimitCleared() {\n if (!this.isRateLimited) {\n return;\n }\n await this.#onEvent('rateLimitCleared');\n }\n /**\n @returns A promise that rejects when any task in the queue errors.\n\n Use with `Promise.race([queue.onError(), queue.onIdle()])` to fail fast on the first error while still resolving normally when the queue goes idle.\n\n Important: The promise returned by `add()` still rejects. You must handle each `add()` promise (for example, `.catch(() => {})`) to avoid unhandled rejections.\n\n @example\n ```\n import PQueue from 'p-queue';\n\n const queue = new PQueue({concurrency: 2});\n\n queue.add(() => fetchData(1)).catch(() => {});\n queue.add(() => fetchData(2)).catch(() => {});\n queue.add(() => fetchData(3)).catch(() => {});\n\n // Stop processing on first error\n try {\n await Promise.race([\n queue.onError(),\n queue.onIdle()\n ]);\n } catch (error) {\n queue.pause(); // Stop processing remaining tasks\n console.error('Queue failed:', error);\n }\n ```\n */\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n onError() {\n return new Promise((_resolve, reject) => {\n const handleError = (error) => {\n this.off('error', handleError);\n reject(error);\n };\n this.on('error', handleError);\n });\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 #setupRateLimitTracking() {\n // Only schedule updates when rate limiting is enabled\n if (this.#isIntervalIgnored) {\n return;\n }\n // Wire up to lifecycle events that affect rate limit state\n // Only 'add' and 'next' can actually change rate limit state\n this.on('add', () => {\n if (this.#queue.size > 0) {\n this.#scheduleRateLimitUpdate();\n }\n });\n this.on('next', () => {\n this.#scheduleRateLimitUpdate();\n });\n }\n #scheduleRateLimitUpdate() {\n // Skip if rate limiting is not enabled or already scheduled\n if (this.#isIntervalIgnored || this.#rateLimitFlushScheduled) {\n return;\n }\n this.#rateLimitFlushScheduled = true;\n queueMicrotask(() => {\n this.#rateLimitFlushScheduled = false;\n this.#updateRateLimitState();\n });\n }\n #rollbackIntervalConsumption() {\n if (this.#isIntervalIgnored) {\n return;\n }\n this.#rollbackIntervalSlot();\n this.#scheduleRateLimitUpdate();\n }\n #updateRateLimitState() {\n const previous = this.#rateLimitedInInterval;\n // Early exit if rate limiting is disabled or queue is empty\n if (this.#isIntervalIgnored || this.#queue.size === 0) {\n if (previous) {\n this.#rateLimitedInInterval = false;\n this.emit('rateLimitCleared');\n }\n return;\n }\n // Get the current count based on mode\n let count;\n if (this.#strict) {\n const now = Date.now();\n this.#cleanupStrictTicks(now);\n count = this.#getActiveTicksCount();\n }\n else {\n count = this.#intervalCount;\n }\n const shouldBeRateLimited = count >= this.#intervalCap;\n if (shouldBeRateLimited !== previous) {\n this.#rateLimitedInInterval = shouldBeRateLimited;\n this.emit(shouldBeRateLimited ? 'rateLimit' : 'rateLimitCleared');\n }\n }\n /**\n Whether the queue is currently rate-limited due to intervalCap.\n */\n get isRateLimited() {\n return this.#rateLimitedInInterval;\n }\n /**\n Whether the queue is saturated. Returns `true` when:\n - All concurrency slots are occupied and tasks are waiting, OR\n - The queue is rate-limited and tasks are waiting\n\n Useful for detecting backpressure and potential hanging tasks.\n\n ```js\n import PQueue from 'p-queue';\n\n const queue = new PQueue({concurrency: 2});\n\n // Backpressure handling\n if (queue.isSaturated) {\n console.log('Queue is saturated, waiting for capacity...');\n await queue.onSizeLessThan(queue.concurrency);\n }\n\n // Monitoring for stuck tasks\n setInterval(() => {\n if (queue.isSaturated) {\n console.warn(`Queue saturated: ${queue.pending} running, ${queue.size} waiting`);\n }\n }, 60000);\n ```\n */\n get isSaturated() {\n return (this.#pending === this.#concurrency && this.#queue.size > 0)\n || (this.isRateLimited && this.#queue.size > 0);\n }\n /**\n The tasks currently being executed. Each task includes its `id`, `priority`, `startTime`, `timeout` (if set), and `timeoutRemaining` (milliseconds until the task times out, or `undefined` if no timeout is set).\n\n Returns an array of task info objects.\n\n ```js\n import PQueue from 'p-queue';\n\n const queue = new PQueue({concurrency: 2, timeout: 10000});\n\n // Add tasks with IDs for better debugging\n queue.add(() => fetchUser(123), {id: 'user-123'});\n queue.add(() => fetchPosts(456), {id: 'posts-456', priority: 1});\n\n // Check what's running\n console.log(queue.runningTasks);\n // => [{\n // id: 'user-123',\n // priority: 0,\n // startTime: 1759253001716,\n // timeout: 10000,\n // timeoutRemaining: 9700\n // }, {\n // id: 'posts-456',\n // priority: 1,\n // startTime: 1759253001916,\n // timeout: 10000,\n // timeoutRemaining: 9900\n // }]\n ```\n */\n get runningTasks() {\n // Return fresh array with fresh objects to prevent mutations\n return [...this.#runningTasks.values()].map(task => ({\n ...task,\n timeoutRemaining: task.timeout ? Math.max(0, task.startTime + task.timeout - Date.now()) : undefined,\n }));\n }\n}\nexport { default as PriorityQueue } from './priority-queue.js';\n/**\nError thrown when a task times out.\n\n@example\n```\nimport PQueue, {TimeoutError} from 'p-queue';\n\nconst queue = new PQueue({timeout: 1000});\n\ntry {\n await queue.add(() => someTask());\n} catch (error) {\n if (error instanceof TimeoutError) {\n console.log('Task timed out');\n }\n}\n```\n*/\nexport { TimeoutError } from 'p-timeout';\n", "import { RecordType } from '../index.js'\n\nexport function getTypes (types?: RecordType | RecordType[]): RecordType[] {\n const DEFAULT_TYPES = [\n RecordType.A\n ]\n\n if (types == null) {\n return DEFAULT_TYPES\n }\n\n if (Array.isArray(types)) {\n if (types.length === 0) {\n return DEFAULT_TYPES\n }\n\n return types\n }\n\n return [\n types\n ]\n}\n", "import { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { RecordType } from '../index.js'\nimport type { DNSResponse } from '../index.js'\n\n/**\n * This TTL will be used if the remote service does not return one\n */\nexport const DEFAULT_TTL = 60\n\nexport function toDNSResponse (obj: any): DNSResponse {\n return {\n Status: obj.Status ?? 0,\n TC: obj.TC ?? obj.flag_tc ?? false,\n RD: obj.RD ?? obj.flag_rd ?? false,\n RA: obj.RA ?? obj.flag_ra ?? false,\n AD: obj.AD ?? obj.flag_ad ?? false,\n CD: obj.CD ?? obj.flag_cd ?? false,\n Question: (obj.Question ?? obj.questions ?? []).map((question: any) => {\n return {\n name: question.name,\n type: RecordType[question.type]\n }\n }),\n Answer: (obj.Answer ?? obj.answers ?? []).map((answer: any) => {\n return {\n name: answer.name,\n type: RecordType[answer.type],\n TTL: (answer.TTL ?? answer.ttl ?? DEFAULT_TTL),\n data: answer.data instanceof Uint8Array ? uint8ArrayToString(answer.data) : answer.data\n }\n })\n }\n}\n", "import PQueue from 'p-queue'\nimport { CustomProgressEvent } from 'progress-events'\nimport { RecordType } from '../index.js'\nimport { getTypes } from '../utils/get-types.js'\nimport { toDNSResponse } from '../utils/to-dns-response.js'\nimport type { DNSResponse } from '../index.js'\nimport type { DNSResolver } from './index.js'\n\n/**\n * Browsers limit concurrent connections per host (~6), we don't want to exhaust\n * the limit so this value controls how many DNS queries can be in flight at\n * once.\n */\nexport const DEFAULT_QUERY_CONCURRENCY = 4\n\nexport interface DNSJSONOverHTTPSOptions {\n queryConcurrency?: number\n}\n\n/**\n * Uses the RFC 8427 'application/dns-json' content-type to resolve DNS queries.\n *\n * Supports and server that uses the same schema as Google's DNS over HTTPS\n * resolver.\n *\n * This resolver needs fewer dependencies than the regular DNS-over-HTTPS\n * resolver so can result in a smaller bundle size and consequently is preferred\n * for browser use.\n *\n * @see https://developers.cloudflare.com/1.1.1.1/encryption/dns-over-https/make-api-requests/dns-json/\n * @see https://github.com/curl/curl/wiki/DNS-over-HTTPS#publicly-available-servers\n * @see https://dnsprivacy.org/public_resolvers/\n * @see https://datatracker.ietf.org/doc/html/rfc8427\n */\nexport function dnsJsonOverHttps (url: string, init: DNSJSONOverHTTPSOptions = {}): DNSResolver {\n const httpQueue = new PQueue({\n concurrency: init.queryConcurrency ?? DEFAULT_QUERY_CONCURRENCY\n })\n\n return async (fqdn, options = {}) => {\n const log = options?.logger?.forComponent('dns:dns-json-over-https')\n const searchParams = new URLSearchParams()\n searchParams.set('name', fqdn)\n\n getTypes(options.types).forEach(type => {\n // We pass record type as a string to the server because cloudflare DNS bug. see https://github.com/ipfs/helia/issues/474\n searchParams.append('type', RecordType[type])\n })\n\n options.onProgress?.(new CustomProgressEvent<string>('dns:query', fqdn))\n\n log?.('GET %s', `${url}?${searchParams}`)\n\n // query DNS-JSON over HTTPS server\n const response = await httpQueue.add(async () => {\n const res = await fetch(`${url}?${searchParams}`, {\n headers: {\n accept: 'application/dns-json'\n },\n signal: options?.signal\n })\n\n log?.('GET %s %d', res.url, res.status)\n\n if (res.status !== 200) {\n throw new Error(`Unexpected HTTP status: ${res.status} - ${res.statusText}`)\n }\n\n const response = toDNSResponse(await res.json())\n\n options.onProgress?.(new CustomProgressEvent<DNSResponse>('dns:response', response))\n\n return response\n }, {\n signal: options.signal\n })\n\n if (response == null) {\n throw new Error('No DNS response received')\n }\n\n return response\n }\n}\n", "import { dnsJsonOverHttps } from './dns-json-over-https.js'\nimport type { DNSResolver } from './index.js'\n\nexport function defaultResolver (): DNSResolver[] {\n return [\n dnsJsonOverHttps('https://cloudflare-dns.com/dns-query'),\n dnsJsonOverHttps('https://dns.google/resolve')\n ]\n}\n", "import hashlru from 'hashlru'\nimport { RecordType } from '../index.js'\nimport { DEFAULT_TTL, toDNSResponse } from './to-dns-response.js'\nimport type { Answer, DNSResponse } from '../index.js'\n\ninterface CachedAnswer {\n expires: number\n value: Answer\n}\n\nexport interface AnswerCache {\n get (fqdn: string, types: RecordType[]): DNSResponse | undefined\n add (domain: string, answer: Answer): void\n remove (domain: string, type: ResponseType): void\n clear (): void\n}\n\n/**\n * Time Aware Least Recent Used Cache\n *\n * @see https://arxiv.org/pdf/1801.00390\n */\nclass CachedAnswers {\n private readonly lru: any\n\n constructor (maxSize: number) {\n // @ts-expect-error types are broken - https://github.com/dominictarr/hashlru/pull/24\n this.lru = hashlru(maxSize)\n }\n\n get (fqdn: string, types: RecordType[]): DNSResponse | undefined {\n let foundAllAnswers = true\n const answers: Answer[] = []\n\n for (const type of types) {\n const cached = this.getAnswers(fqdn, type)\n\n if (cached.length === 0) {\n foundAllAnswers = false\n break\n }\n\n answers.push(...cached)\n }\n\n if (foundAllAnswers) {\n return toDNSResponse({ answers })\n }\n }\n\n private getAnswers (domain: string, type: RecordType): Answer[] {\n const key = `${domain.toLowerCase()}-${type}`\n const answers: CachedAnswer[] = this.lru.get(key)\n\n if (answers != null) {\n const cachedAnswers = answers\n .filter((entry) => {\n return entry.expires > Date.now()\n })\n .map(({ expires, value }) => ({\n ...value,\n TTL: Math.round((expires - Date.now()) / 1000),\n type: RecordType[value.type]\n }))\n\n if (cachedAnswers.length === 0) {\n this.lru.remove(key)\n }\n\n // @ts-expect-error hashlru stringifies stored types which turns enums\n // into strings, we convert back into enums above but tsc doesn't know\n return cachedAnswers\n }\n\n return []\n }\n\n add (domain: string, answer: Answer): void {\n const key = `${domain.toLowerCase()}-${answer.type}`\n\n const answers: CachedAnswer[] = this.lru.get(key) ?? []\n answers.push({\n expires: Date.now() + ((answer.TTL ?? DEFAULT_TTL) * 1000),\n value: answer\n })\n\n this.lru.set(key, answers)\n }\n\n remove (domain: string, type: ResponseType): void {\n const key = `${domain.toLowerCase()}-${type}`\n\n this.lru.remove(key)\n }\n\n clear (): void {\n this.lru.clear()\n }\n}\n\n/**\n * Avoid sending multiple queries for the same hostname by caching results\n */\nexport function cache (size: number): AnswerCache {\n return new CachedAnswers(size)\n}\n", "import { CustomProgressEvent } from 'progress-events'\nimport { DNSQueryFailedError } from './errors.ts'\nimport { defaultResolver } from './resolvers/default.js'\nimport { cache } from './utils/cache.js'\nimport { getTypes } from './utils/get-types.js'\nimport type { DNS as DNSInterface, DNSInit, DNSResponse, QueryOptions } from './index.js'\nimport type { DNSResolver } from './resolvers/index.js'\nimport type { AnswerCache } from './utils/cache.js'\nimport type { ComponentLogger } from '@libp2p/interface'\n\nconst DEFAULT_ANSWER_CACHE_SIZE = 1000\n\nexport class DNS implements DNSInterface {\n private readonly resolvers: Record<string, DNSResolver[]>\n private readonly cache: AnswerCache\n private readonly logger?: ComponentLogger\n\n constructor (init: DNSInit) {\n this.resolvers = {}\n this.cache = cache(init.cacheSize ?? DEFAULT_ANSWER_CACHE_SIZE)\n this.logger = init.logger\n\n Object.entries(init.resolvers ?? {}).forEach(([tld, resolver]) => {\n if (!Array.isArray(resolver)) {\n resolver = [resolver]\n }\n\n // convert `com` -> `com.`\n if (!tld.endsWith('.')) {\n tld = `${tld}.`\n }\n\n this.resolvers[tld] = resolver\n })\n\n // configure default resolver if none specified\n if (this.resolvers['.'] == null) {\n this.resolvers['.'] = defaultResolver()\n }\n }\n\n /**\n * Queries DNS resolvers for the passed record types for the passed domain.\n *\n * If cached records exist for all desired types they will be returned\n * instead.\n *\n * Any new responses will be added to the cache for subsequent requests.\n */\n async query (domain: string, options: QueryOptions = {}): Promise<DNSResponse> {\n const types = getTypes(options.types)\n const cached = options.cached !== false ? this.cache.get(domain, types) : undefined\n\n if (cached != null) {\n options.onProgress?.(new CustomProgressEvent<DNSResponse>('dns:cache', cached))\n\n return cached\n }\n\n const tld = `${domain.split('.').pop()}.`\n const resolvers = (this.resolvers[tld] ?? this.resolvers['.']).sort(() => {\n return (Math.random() > 0.5) ? -1 : 1\n })\n\n const errors: Error[] = []\n\n for (const resolver of resolvers) {\n // skip further resolutions if the user aborted the signal\n if (options.signal?.aborted === true) {\n break\n }\n\n try {\n const result = await resolver(domain, {\n ...options,\n logger: this.logger,\n types\n })\n\n for (const answer of result.Answer) {\n this.cache.add(domain, answer)\n }\n\n return result\n } catch (err: any) {\n errors.push(err)\n options.onProgress?.(new CustomProgressEvent<Error>('dns:error', err))\n }\n }\n\n throw new DNSQueryFailedError(errors, `DNS lookup of ${domain} ${types} failed`)\n }\n}\n", "/**\n * @packageDocumentation\n *\n * Query DNS records using `node:dns`, DNS over HTTP and/or DNSJSON over HTTP.\n *\n * A list of publicly accessible servers can be found [here](https://github.com/curl/curl/wiki/DNS-over-HTTPS#publicly-available-servers).\n *\n * @example Using the default resolver\n *\n * ```TypeScript\n * import { dns } from '@multiformats/dns'\n *\n * const resolver = dns()\n *\n * // resolve A records with a 5s timeout\n * const result = await dns.query('google.com', {\n * signal: AbortSignal.timeout(5000)\n * })\n * ```\n *\n * @example Using per-TLD resolvers\n *\n * ```TypeScript\n * import { dns } from '@multiformats/dns'\n * import { dnsJsonOverHttps } from '@multiformats/dns/resolvers'\n *\n * const resolver = dns({\n * resolvers: {\n * // will only be used to resolve `.com` addresses\n * 'com.': dnsJsonOverHttps('https://cloudflare-dns.com/dns-query'),\n *\n * // this can also be an array, resolvers will be shuffled and tried in\n * // series\n * 'net.': [\n * dnsJsonOverHttps('https://dns.google/resolve'),\n * dnsJsonOverHttps('https://dns.pub/dns-query')\n * ],\n *\n * // will only be used to resolve all other addresses\n * '.': dnsJsonOverHttps('https://dnsforge.de/dns-query'),\n * }\n * })\n * ```\n *\n * @example Query for specific record types\n *\n * ```TypeScript\n * import { dns, RecordType } from '@multiformats/dns'\n *\n * const resolver = dns()\n *\n * // resolve only TXT records\n * const result = await dns.query('google.com', {\n * types: [\n * RecordType.TXT\n * ]\n * })\n * ```\n *\n * ## Caching\n *\n * Individual Aanswers are cached so. If you make a request, for which all\n * record types are cached, all values will be pulled from the cache.\n *\n * If any of the record types are not cached, a new request will be resolved as\n * if none of the records were cached, and the cache will be updated to include\n * the new results.\n *\n * @example Ignoring the cache\n *\n * ```TypeScript\n * import { dns, RecordType } from '@multiformats/dns'\n *\n * const resolver = dns()\n *\n * // do not used cached results, always resolve a new query\n * const result = await dns.query('google.com', {\n * cached: false\n * })\n * ```\n */\n\nimport { DNS as DNSClass } from './dns.js'\nimport type { DNSResolver } from './resolvers/index.js'\nimport type { ComponentLogger } from '@libp2p/interface'\nimport type { ProgressEvent, ProgressOptions } from 'progress-events'\n\n/**\n * A subset of DNS Record Types\n *\n * @see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4.\n */\nexport enum RecordType {\n A = 1,\n CNAME = 5,\n TXT = 16,\n AAAA = 28\n}\n\nexport interface Question {\n /**\n * The record name requested.\n */\n name: string\n\n /**\n * The type of DNS record requested.\n *\n * @see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4.\n */\n type: RecordType\n}\n\nexport interface Answer {\n /**\n * The record owner.\n */\n name: string\n\n /**\n * The type of DNS record.\n *\n * @see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4\n */\n type: RecordType\n\n /**\n * The number of seconds the answer can be stored in cache before it is\n * considered stale.\n */\n TTL: number\n\n /**\n * The value of the DNS record for the given name and type. The data will be\n * in text for standardized record types and in hex for unknown types.\n */\n data: string\n}\n\nexport interface DNSResponse {\n /**\n * The Response Code of the DNS Query.\n *\n * @see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-6\n */\n Status: number\n\n /**\n * If true, it means the truncated bit was set. This happens when the DNS\n * answer is larger than a single UDP or TCP packet.\n */\n TC: boolean\n\n /**\n * If true, it means the Recursive Desired bit was set.\n */\n RD: boolean\n\n /**\n * If true, it means the Recursion Available bit was set.\n */\n RA: boolean\n\n /**\n * If true, it means that every record in the answer was verified with DNSSEC.\n */\n AD: boolean\n\n /**\n * If true, the client asked to disable DNSSEC validation.\n */\n CD: boolean\n\n /**\n * The records that were requested.\n */\n Question: Question[]\n\n /**\n * Values for the records that were requested.\n */\n Answer: Answer[]\n}\n\n/**\n * The default maximum amount of recursion allowed during a query\n */\nexport const MAX_RECURSIVE_DEPTH = 32\n\nexport interface QueryOptions extends ProgressOptions<ResolveDnsProgressEvents> {\n signal?: AbortSignal\n\n /**\n * Do not use cached DNS entries\n *\n * @default false\n */\n cached?: boolean\n\n /**\n * The type or types of DNS records to resolve\n *\n * @default [RecordType.A, RecordType.AAAA]\n */\n types?: RecordType | RecordType[]\n\n /**\n * An optional logger\n */\n logger?: ComponentLogger\n}\n\nexport interface DNS {\n query(fqdn: string, options?: QueryOptions): Promise<DNSResponse>\n}\n\nexport type ResolveDnsProgressEvents =\n ProgressEvent<'dns:cache', string> |\n ProgressEvent<'dns:query', string> |\n ProgressEvent<'dns:response', DNSResponse> |\n ProgressEvent<'dns:error', Error>\n\nexport type DNSResolvers = Record<string, DNSResolver | DNSResolver[]>\n\nexport interface DNSInit {\n /**\n * A set of resolvers used to answer DNS queries\n *\n * String keys control which resolvers are used for which TLDs.\n *\n * @example\n *\n * ```TypeScript\n * import { dns } from '@multiformats/dns'\n * import { dnsOverHttps } from '@multiformats/dns'\n *\n * const resolver = dns({\n * resolvers: {\n * // only used for .com domains\n * 'com.': dnsOverHttps('https://example-1.com'),\n *\n * // only used for .net domains, can be an array\n * 'net.': [\n * dnsOverHttps('https://example-2.com'),\n * dnsOverHttps('https://example-3.com'),\n * ],\n *\n * // used for everything else (can be an array)\n * '.': dnsOverHttps('https://example-4.com')\n * }\n * })\n * ```\n */\n resolvers?: DNSResolvers\n\n /**\n * To avoid repeating DNS lookups, successful answers are cached according to\n * their TTL. To avoid exhausting memory, this option controls how many\n * answers to cache.\n *\n * @default 1000\n */\n cacheSize?: number\n\n /**\n * An optional logger\n */\n logger?: ComponentLogger\n}\n\nexport function dns (init: DNSInit = {}): DNS {\n return new DNSClass(init)\n}\n", "//#region src/index.ts\nconst s = 1e3;\nconst m = s * 60;\nconst h = m * 60;\nconst d = h * 24;\nconst w = d * 7;\nconst y = d * 365.25;\nconst mo = y / 12;\nfunction ms(value, options) {\n\tif (typeof value === \"string\") return parse(value);\n\telse if (typeof value === \"number\") return format(value, options);\n\tthrow new Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(value)}`);\n}\n/**\n* Parse the given string and return milliseconds.\n*\n* @param str - A string to parse to milliseconds\n* @returns The parsed value in milliseconds, or `NaN` if the string can't be\n* parsed\n*/\nfunction parse(str) {\n\tif (typeof str !== \"string\" || str.length === 0 || str.length > 100) throw new Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(str)}`);\n\tconst match = /^(?<value>-?\\d*\\.?\\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(str);\n\tif (!match?.groups) return NaN;\n\tconst { value, unit = \"ms\" } = match.groups;\n\tconst n = parseFloat(value);\n\tconst matchUnit = unit.toLowerCase();\n\t/* istanbul ignore next - istanbul doesn't understand, but thankfully the TypeScript the exhaustiveness check in the default case keeps us type safe here */\n\tswitch (matchUnit) {\n\t\tcase \"years\":\n\t\tcase \"year\":\n\t\tcase \"yrs\":\n\t\tcase \"yr\":\n\t\tcase \"y\": return n * y;\n\t\tcase \"months\":\n\t\tcase \"month\":\n\t\tcase \"mo\": return n * mo;\n\t\tcase \"weeks\":\n\t\tcase \"week\":\n\t\tcase \"w\": return n * w;\n\t\tcase \"days\":\n\t\tcase \"day\":\n\t\tcase \"d\": return n * d;\n\t\tcase \"hours\":\n\t\tcase \"hour\":\n\t\tcase \"hrs\":\n\t\tcase \"hr\":\n\t\tcase \"h\": return n * h;\n\t\tcase \"minutes\":\n\t\tcase \"minute\":\n\t\tcase \"mins\":\n\t\tcase \"min\":\n\t\tcase \"m\": return n * m;\n\t\tcase \"seconds\":\n\t\tcase \"second\":\n\t\tcase \"secs\":\n\t\tcase \"sec\":\n\t\tcase \"s\": return n * s;\n\t\tcase \"milliseconds\":\n\t\tcase \"millisecond\":\n\t\tcase \"msecs\":\n\t\tcase \"msec\":\n\t\tcase \"ms\": return n;\n\t\tdefault: throw new Error(`Unknown unit \"${matchUnit}\" provided to ms.parse(). value=${JSON.stringify(str)}`);\n\t}\n}\n/**\n* Parse the given StringValue and return milliseconds.\n*\n* @param value - A typesafe StringValue to parse to milliseconds\n* @returns The parsed value in milliseconds, or `NaN` if the string can't be\n* parsed\n*/\nfunction parseStrict(value) {\n\treturn parse(value);\n}\n/**\n* Short format for `ms`.\n*/\nfunction fmtShort(ms$1) {\n\tconst msAbs = Math.abs(ms$1);\n\tif (msAbs >= y) return `${Math.round(ms$1 / y)}y`;\n\tif (msAbs >= mo) return `${Math.round(ms$1 / mo)}mo`;\n\tif (msAbs >= w) return `${Math.round(ms$1 / w)}w`;\n\tif (msAbs >= d) return `${Math.round(ms$1 / d)}d`;\n\tif (msAbs >= h) return `${Math.round(ms$1 / h)}h`;\n\tif (msAbs >= m) return `${Math.round(ms$1 / m)}m`;\n\tif (msAbs >= s) return `${Math.round(ms$1 / s)}s`;\n\treturn `${ms$1}ms`;\n}\n/**\n* Long format for `ms`.\n*/\nfunction fmtLong(ms$1) {\n\tconst msAbs = Math.abs(ms$1);\n\tif (msAbs >= y) return plural(ms$1, msAbs, y, \"year\");\n\tif (msAbs >= mo) return plural(ms$1, msAbs, mo, \"month\");\n\tif (msAbs >= w) return plural(ms$1, msAbs, w, \"week\");\n\tif (msAbs >= d) return plural(ms$1, msAbs, d, \"day\");\n\tif (msAbs >= h) return plural(ms$1, msAbs, h, \"hour\");\n\tif (msAbs >= m) return plural(ms$1, msAbs, m, \"minute\");\n\tif (msAbs >= s) return plural(ms$1, msAbs, s, \"second\");\n\treturn `${ms$1} ms`;\n}\n/**\n* Format the given integer as a string.\n*\n* @param ms - milliseconds\n* @param options - Options for the conversion\n* @returns The formatted string\n*/\nfunction format(ms$1, options) {\n\tif (typeof ms$1 !== \"number\" || !Number.isFinite(ms$1)) throw new Error(\"Value provided to ms.format() must be of type number.\");\n\treturn options?.long ? fmtLong(ms$1) : fmtShort(ms$1);\n}\n/**\n* Pluralization helper.\n*/\nfunction plural(ms$1, msAbs, n, name) {\n\tconst isPlural = msAbs >= n * 1.5;\n\treturn `${Math.round(ms$1 / n)} ${name}${isPlural ? \"s\" : \"\"}`;\n}\n\n//#endregion\nexport { format, ms, parse, parseStrict };", "/* eslint-disable no-console */\n\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\nimport { ms as humanize } from 'ms'\nimport type { Debug, Debugger, Options } from './index.ts'\n\nexport default function setup (env: any): Debug {\n createDebug.debug = createDebug\n createDebug.default = createDebug\n createDebug.coerce = coerce\n createDebug.disable = disable\n createDebug.enable = enable\n createDebug.enabled = enabled\n createDebug.humanize = humanize\n createDebug.destroy = destroy\n\n Object.keys(env).forEach(key => {\n // @ts-expect-error cannot use string to index type\n createDebug[key] = env[key]\n })\n\n /**\n * The currently active debug mode names, and names to skip.\n */\n\n createDebug.names = [] as any[]\n createDebug.skips = [] as any[]\n\n /**\n * Map of special \"%n\" handling functions, for the debug \"format\" argument.\n *\n * Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n */\n createDebug.formatters = {} satisfies Record<string, any>\n\n /**\n * Selects a color for a debug namespace\n *\n * @param {string} namespace - The namespace string for the debug instance to be colored\n * @returns {number | string} An ANSI color code for the given namespace\n */\n function selectColor (namespace: string): number | string {\n let hash = 0\n\n for (let i = 0; i < namespace.length; i++) {\n hash = ((hash << 5) - hash) + namespace.charCodeAt(i)\n hash |= 0 // Convert to 32bit integer\n }\n\n // @ts-expect-error colors is not in the types\n return createDebug.colors[Math.abs(hash) % createDebug.colors.length]\n }\n createDebug.selectColor = selectColor\n\n /**\n * Create a debugger with the given `namespace`.\n *\n * @param {string} namespace\n * @returns {Function}\n */\n function createDebug (namespace: string, options?: Options): Debugger {\n let prevTime: any\n let enableOverride: any = null\n let namespacesCache: any\n let enabledCache: any\n\n function debug (...args: any[]): void {\n // Disabled?\n // @ts-expect-error enabled is not in the types\n if (!debug.enabled) {\n return\n }\n\n const self: any = debug\n\n // Set `diff` timestamp\n const curr = Number(new Date())\n const ms = curr - (prevTime || curr)\n self.diff = ms\n self.prev = prevTime\n self.curr = curr\n prevTime = curr\n\n args[0] = createDebug.coerce(args[0])\n\n if (typeof args[0] !== 'string') {\n // Anything else let's inspect with %O\n args.unshift('%O')\n }\n\n // Apply any `formatters` transformations\n let index = 0\n args[0] = args[0].replace(/%([a-zA-Z%])/g, (match: any, format: any): any => {\n // If we encounter an escaped % then don't increase the array index\n if (match === '%%') {\n return '%'\n }\n index++\n // @ts-expect-error formatters is not in the types\n const formatter = createDebug.formatters[format]\n if (typeof formatter === 'function') {\n const val = args[index]\n match = formatter.call(self, val)\n\n // Now we need to remove `args[index]` since it's inlined in the `format`\n args.splice(index, 1)\n index--\n }\n return match\n })\n\n // Apply env-specific formatting (colors, etc.)\n // @ts-expect-error formatArgs is not in the types\n createDebug.formatArgs.call(self, args)\n\n if (options?.onLog != null) {\n options.onLog(...args)\n }\n\n // @ts-expect-error log is not in the types\n const logFn = self.log || createDebug.log\n logFn.apply(self, args)\n }\n\n debug.namespace = namespace\n // @ts-expect-error useColors is not in the types\n debug.useColors = createDebug.useColors()\n debug.color = createDebug.selectColor(namespace)\n debug.extend = extend\n debug.destroy = createDebug.destroy // XXX Temporary. Will be removed in the next major release.\n\n Object.defineProperty(debug, 'enabled', {\n enumerable: true,\n configurable: false,\n get: () => {\n if (enableOverride !== null) {\n return enableOverride\n }\n // @ts-expect-error namespaces is not in the types\n if (namespacesCache !== createDebug.namespaces) {\n // @ts-expect-error namespaces is not in the types\n namespacesCache = createDebug.namespaces\n enabledCache = createDebug.enabled(namespace)\n }\n\n return enabledCache\n },\n set: v => {\n enableOverride = v\n }\n })\n\n // Env-specific initialization logic for debug instances\n // @ts-expect-error init is not in the types\n if (typeof createDebug.init === 'function') {\n // @ts-expect-error init is not in the types\n createDebug.init(debug)\n }\n\n // @ts-expect-error some properties are added dynamically\n return debug\n }\n\n function extend (this: any, namespace: string, delimiter: string): any {\n const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace)\n newDebug.log = this.log\n return newDebug\n }\n\n /**\n * Enables a debug mode by namespaces. This can include modes\n * separated by a colon and wildcards.\n *\n * @param {string} namespaces\n */\n function enable (namespaces: string): void {\n // @ts-expect-error save is not in the types\n createDebug.save(namespaces)\n // @ts-expect-error namespaces is not in the types\n createDebug.namespaces = namespaces\n\n createDebug.names = []\n createDebug.skips = []\n\n let i\n const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/)\n const len = split.length\n\n for (i = 0; i < len; i++) {\n if (!split[i]) {\n // ignore empty strings\n continue\n }\n\n namespaces = split[i].replace(/\\*/g, '.*?')\n\n if (namespaces[0] === '-') {\n createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'))\n } else {\n createDebug.names.push(new RegExp('^' + namespaces + '$'))\n }\n }\n }\n\n /**\n * Disable debug output.\n *\n * @returns {string} namespaces\n */\n function disable (): string {\n const namespaces = [\n ...createDebug.names.map(toNamespace),\n ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n ].join(',')\n createDebug.enable('')\n return namespaces\n }\n\n /**\n * Returns true if the given mode name is enabled, false otherwise.\n *\n * @param {string} name\n * @returns {boolean}\n */\n function enabled (name: string): boolean {\n if (name[name.length - 1] === '*') {\n return true\n }\n\n let i\n let len\n\n for (i = 0, len = createDebug.skips.length; i < len; i++) {\n if (createDebug.skips[i].test(name)) {\n return false\n }\n }\n\n for (i = 0, len = createDebug.names.length; i < len; i++) {\n if (createDebug.names[i].test(name)) {\n return true\n }\n }\n\n return false\n }\n\n /**\n * Convert regexp to namespace\n */\n function toNamespace (regexp: RegExp): string {\n return regexp.toString()\n .substring(2, regexp.toString().length - 2)\n .replace(/\\.\\*\\?$/, '*')\n }\n\n /**\n * Coerce `val`.\n */\n function coerce (val: any): any {\n if (val instanceof Error) {\n return val.stack ?? val.message\n }\n return val\n }\n\n /**\n * XXX DO NOT USE. This is a temporary stub function.\n * XXX It WILL be removed in the next major release.\n */\n function destroy (): void {\n console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.')\n }\n\n // @ts-expect-error setupFormatters is not in the types\n createDebug.setupFormatters(createDebug.formatters)\n\n // @ts-expect-error load is not in the types\n createDebug.enable(createDebug.load())\n\n // @ts-expect-error some properties are added dynamically\n return createDebug\n}\n", "/* eslint-disable no-console */\n\n/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\nimport { ms as humanize } from 'ms'\nimport setup from './common.ts'\n\nconst storage = localstorage()\n\n/**\n * Colors.\n */\nconst colors = [\n '#0000CC',\n '#0000FF',\n '#0033CC',\n '#0033FF',\n '#0066CC',\n '#0066FF',\n '#0099CC',\n '#0099FF',\n '#00CC00',\n '#00CC33',\n '#00CC66',\n '#00CC99',\n '#00CCCC',\n '#00CCFF',\n '#3300CC',\n '#3300FF',\n '#3333CC',\n '#3333FF',\n '#3366CC',\n '#3366FF',\n '#3399CC',\n '#3399FF',\n '#33CC00',\n '#33CC33',\n '#33CC66',\n '#33CC99',\n '#33CCCC',\n '#33CCFF',\n '#6600CC',\n '#6600FF',\n '#6633CC',\n '#6633FF',\n '#66CC00',\n '#66CC33',\n '#9900CC',\n '#9900FF',\n '#9933CC',\n '#9933FF',\n '#99CC00',\n '#99CC33',\n '#CC0000',\n '#CC0033',\n '#CC0066',\n '#CC0099',\n '#CC00CC',\n '#CC00FF',\n '#CC3300',\n '#CC3333',\n '#CC3366',\n '#CC3399',\n '#CC33CC',\n '#CC33FF',\n '#CC6600',\n '#CC6633',\n '#CC9900',\n '#CC9933',\n '#CCCC00',\n '#CCCC33',\n '#FF0000',\n '#FF0033',\n '#FF0066',\n '#FF0099',\n '#FF00CC',\n '#FF00FF',\n '#FF3300',\n '#FF3333',\n '#FF3366',\n '#FF3399',\n '#FF33CC',\n '#FF33FF',\n '#FF6600',\n '#FF6633',\n '#FF9900',\n '#FF9933',\n '#FFCC00',\n '#FFCC33'\n]\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors (): boolean {\n // NB: In an Electron preload script, document will be defined but not fully\n // initialized. Since we know we're in Chrome, we'll just detect this case\n // explicitly\n // @ts-expect-error window.process.type and window.process.__nwjs are not in the types\n if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n return true\n }\n\n // Internet Explorer and Edge do not support colors.\n if (typeof navigator !== 'undefined' && (navigator.userAgent?.toLowerCase().match(/(edge|trident)\\/(\\d+)/) != null)) {\n return false\n }\n\n // Is webkit? http://stackoverflow.com/a/16459606/376773\n // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n // @ts-expect-error document.documentElement.style.WebkitAppearance is not in the types\n return (typeof document !== 'undefined' && document.documentElement?.style?.WebkitAppearance) ||\n // Is firebug? http://stackoverflow.com/a/398120/376773\n // @ts-expect-error window.console.firebug and window.console.exception are not in the types\n (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n // Is firefox >= v31?\n // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n (typeof navigator !== 'undefined' && (navigator.userAgent?.toLowerCase().match(/firefox\\/(\\d+)/) != null) && parseInt(RegExp.$1, 10) >= 31) ||\n // Double check webkit in userAgent just in case we are in a worker\n (typeof navigator !== 'undefined' && navigator.userAgent?.toLowerCase().match(/applewebkit\\/(\\d+)/))\n}\n\n/**\n * Colorize log arguments if enabled.\n */\nfunction formatArgs (this: any, args: any[]): void {\n args[0] = (this.useColors ? '%c' : '') +\n this.namespace +\n (this.useColors ? ' %c' : ' ') +\n args[0] +\n (this.useColors ? '%c ' : ' ') +\n '+' + humanize(this.diff)\n\n if (!this.useColors) {\n return\n }\n\n const c = 'color: ' + this.color\n args.splice(1, 0, c, 'color: inherit')\n\n // The final \"%c\" is somewhat tricky, because there could be other\n // arguments passed either before or after the %c, so we need to\n // figure out the correct index to insert the CSS into\n let index = 0\n let lastC = 0\n args[0].replace(/%[a-zA-Z%]/g, (match: string) => {\n if (match === '%%') {\n return\n }\n index++\n if (match === '%c') {\n // We only are interested in the *last* %c\n // (the user may have provided their own)\n lastC = index\n }\n })\n\n args.splice(lastC, 0, c)\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n */\nconst log = console.debug ?? console.log ?? (() => { })\n\n/**\n * Save `namespaces`.\n *\n * @param {string} namespaces\n */\nfunction save (namespaces: string): void {\n try {\n if (namespaces) {\n storage?.setItem('debug', namespaces)\n } else {\n storage?.removeItem('debug')\n }\n } catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n}\n\n/**\n * Load `namespaces`.\n *\n * @returns {string} returns the previously persisted debug modes\n */\nfunction load (): string | null | undefined {\n let r\n try {\n r = storage?.getItem('debug')\n } catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n\n // If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n if (!r && typeof globalThis.process !== 'undefined' && 'env' in globalThis.process) {\n r = globalThis.process.env.DEBUG\n }\n\n return r\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n */\nfunction localstorage (): Storage | undefined {\n try {\n // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n // The Browser also has localStorage in the global context.\n return localStorage\n } catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n}\n\nfunction setupFormatters (formatters: any): void {\n /**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n formatters.j = function (v: any) {\n try {\n return JSON.stringify(v)\n } catch (error: any) {\n return '[UnexpectedJSONParseError]: ' + error.message\n }\n }\n}\n\nexport default setup({ formatArgs, save, load, useColors, setupFormatters, colors, storage, log })\n", "/**\n * @packageDocumentation\n *\n * This module is a fork of the [debug](https://www.npmjs.com/package/debug) module. It has been converted to TypeScript and the output is ESM.\n *\n * It is API compatible with no extra features or bug fixes, it should only be used if you want a 100% ESM application.\n *\n * ESM should be arriving in `debug@5.x.x` so this module can be retired after that.\n *\n * Please see [debug](https://www.npmjs.com/package/debug) for API details.\n */\n\n/**\n * Module dependencies.\n */\nimport weald from './node.ts'\nimport type { ms } from 'ms'\n\nexport interface Options {\n /**\n * Receives log lines. The default transport writes the log line to\n * `process.stderr`, `console.debug` or `console.log` depending on what is\n * available in the environment.\n *\n * The args are not formatted - they can be passed to `util.format` from\n * Node.js or to `format` exported from this module as `weald/format`.\n *\n * @example Receiving log lines\n *\n * ```ts\n * import debug from 'weald'\n * import { format } from 'weald/format'\n *\n * const logger = debug('my-namespace', {\n * onLog (...args: any[]) {\n * const line = format(...args)\n * // do something with `line`\n * }\n * })\n * ```\n */\n onLog?(...args: any[]): void\n}\n\nexport interface Debug {\n (namespace: string, options?: Options): Debugger\n coerce(val: any): any\n disable(...args: string[]): string\n enable(namespaces: string | boolean): void\n enabled(namespaces: string): boolean\n formatArgs(this: Debugger, args: any[]): void\n log(fmt: string, ...args: any[]): unknown\n selectColor(namespace: string): string | number\n humanize: typeof ms\n useColors(): boolean\n\n names: RegExp[]\n skips: RegExp[]\n\n formatters: Formatters\n\n inspectOpts?: {\n hideDate?: boolean | number | null\n colors?: boolean | number | null\n depth?: boolean | number | null\n showHidden?: boolean | number | null\n }\n}\n\nexport type Formatters = Record<string, (v: any) => string>\n\nexport interface Debugger {\n (formatter: any, ...args: any[]): void\n\n color: string\n diff: number\n enabled: boolean\n log(fmt: string, ...args: any[]): unknown\n namespace: string\n destroy(): boolean\n extend(namespace: string, delimiter?: string): Debugger\n useColors(): boolean\n}\n\nexport default weald\n", "/**\n * @packageDocumentation\n *\n * A logger based on [weald](https://www.npmjs.com/package/weald) that contains custom formatters binary data in common multibase formats - base58btc, base32, base36 and base64 - all other logged objects ([CID](https://docs.ipfs.tech/concepts/content-addressing/)s, [Multiaddrs](https://multiformats.io/multiaddr/), etc) should contain a suitable `toString()` method.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from 'birnam'\n *\n * const log = logger('helia:my:component:name')\n *\n * try {\n * // an operation\n * log('something happened: %s', 'it was ok')\n * } catch (err) {\n * log.error('something bad happened: %e', err)\n * }\n *\n * log('with this peer: %s', {\n * toString () {\n * return '12D3Foo'\n * }\n * })\n * log('and this base58btc: %z', Uint8Array.from([0, 1, 2, 3]))\n * log('and this base32: %b', Uint8Array.from([4, 5, 6, 7]))\n * ```\n *\n * ```console\n * $ DEBUG=helia:* node index.js\n * something happened: it was ok\n * something bad happened: <stack trace>\n * with this peer: 12D3Foo\n * with this base58btc: zQmfoo\n * with this base32: bafyfoo\n * ```\n *\n * ## What's in a name?\n *\n * Great Birnam Wood is referenced in Shakespeare's [Scottish play](https://en.wikipedia.org/wiki/The_Scottish_Play)\n * as part of the prophecy told by the three witches. The woods themselves have\n * largely been cut down since, and the trees (presumably) turned into logs.\n */\n\nimport { base32 } from 'multiformats/bases/base32'\nimport { base36 } from 'multiformats/bases/base36'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base64 } from 'multiformats/bases/base64'\nimport debug from 'weald'\nimport type { Options as LoggerOptions, Debugger } from 'weald'\n\n/**\n * Logger component for interplanetary applications\n */\nexport interface Logger {\n /**\n * Log a message\n */\n (formatter: any, ...args: any[]): void\n\n /**\n * Log an error message\n */\n error(formatter: any, ...args: any[]): void\n\n /**\n * Log a trace message\n */\n trace(formatter: any, ...args: any[]): void\n\n /**\n * `true` if this logger is enabled\n */\n enabled: boolean\n\n /**\n * Create a logger scoped below this one\n *\n * @example\n *\n * ```ts\n * import { defaultLogger } from 'birnam'\n *\n * const log = defaultLogger().forComponent('foo')\n *\n * log('hello')\n * // foo hello\n *\n * const subLog = log.newScope('bar')\n *\n * subLog('hello')\n * // foo:bar hello\n * ```\n */\n newScope(name: string): Logger\n}\n\n/**\n * Component based logger. This can be used to create loggers that are scoped to\n * individual system components or services.\n *\n * To see logs, run your app with `DEBUG` set as an env var or for browsers, in\n * `localStorage`:\n *\n * ```console\n * $ DEBUG=helia* node index.js\n * helia:my-service hello +0ms\n * ```\n */\nexport interface ComponentLogger {\n /**\n * Returns a logger for the specified component.\n *\n * @example\n *\n * ```TypeScript\n * import type { ComponentLogger, Logger } from 'birnam'\n *\n * interface MyServiceComponents {\n * logger: ComponentLogger\n * }\n *\n * class MyService {\n * private readonly log: Logger\n *\n * constructor (components) {\n * this.log = components.logger.forComponent('my-app:my-service')\n *\n * this.log('hello')\n * // logs:\n * // my-app:my-service hello +0ms\n * }\n * }\n * ```\n */\n forComponent(name: string): Logger\n}\n\nexport type { LoggerOptions }\n\n// Add a formatter for converting to a base58 string\ndebug.formatters.z = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base58btc.baseEncode(v)\n}\n\n// Add a formatter for converting to a base32 string\ndebug.formatters.b = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base32.baseEncode(v)\n}\n\n// Add a formatter for converting to a base36 string\ndebug.formatters.k = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base36.baseEncode(v)\n}\n\n// Add a formatter for converting to a base64 string\ndebug.formatters.m = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base64.baseEncode(v)\n}\n\n// Add a formatter for stringifying Errors\ndebug.formatters.e = (v?: Error): string => {\n if (v == null) {\n return 'undefined'\n }\n\n return printError(v)\n}\n\nfunction formatError (v: Error, indent = ''): string {\n const message = notEmpty(v.message)\n const stack = notEmpty(v.stack)\n\n // some browser errors (mostly from Firefox) have no message or no stack,\n // sometimes both, sometimes neither. Sometimes the message is in the stack,\n // sometimes is isn't so try to do *something* useful\n if (message != null && stack != null) {\n if (stack.includes(message)) {\n return `${stack.split('\\n').join(`\\n${indent}`)}`\n }\n\n return `${message}\\n${indent}${stack.split('\\n').join(`\\n${indent}`)}`\n }\n\n if (stack != null) {\n return `${stack.split('\\n').join(`\\n${indent}`)}`\n }\n\n if (message != null) {\n return `${message}`\n }\n\n return `${v.toString()}`\n}\n\nfunction isAggregateError (err?: any): err is AggregateError {\n return err instanceof AggregateError || (err?.name === 'AggregateError' && Array.isArray(err.errors))\n}\n\nfunction printError (err: Error, indent = ''): string {\n if (isAggregateError(err)) {\n let output = formatError(err, indent)\n\n if (err.errors.length > 0) {\n indent = `${indent} `\n\n output += `\\n${indent}${\n err.errors\n .map(err => `${printError(err, `${indent}`)}`)\n .join(`\\n${indent}`)\n }`\n } else {\n output += `\\n${indent}[Error list was empty]`\n }\n\n return output.trim()\n }\n\n return formatError(err, indent)\n}\n\nfunction createDisabledLogger (namespace: string): Debugger {\n const logger = (): void => {}\n logger.enabled = false\n logger.color = ''\n logger.diff = 0\n logger.log = (): void => {}\n logger.namespace = namespace\n logger.destroy = () => true\n logger.extend = () => logger\n logger.useColors = () => false\n\n return logger\n}\n\n/**\n * Create a component logger that will prefix any log messages with the passed\n * string.\n *\n * @example\n *\n * ```TypeScript\n * import { prefixLogger } from 'birnam'\n *\n * const logger = prefixLogger('my-node')\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-node:my-component hello world\"\n * ```\n */\nexport function prefixLogger (prefix: string, options?: LoggerOptions): ComponentLogger {\n return {\n forComponent (name: string) {\n return logger(`${prefix}:${name}`, options)\n }\n }\n}\n\n/**\n * Create a component logger\n *\n * @example\n *\n * ```TypeScript\n * import { defaultLogger } from 'birnam'\n *\n * const logger = defaultLogger()\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nexport function defaultLogger (options?: LoggerOptions): ComponentLogger {\n return {\n forComponent (name: string) {\n return logger(name, options)\n }\n }\n}\n\n/**\n * Creates a logger for the passed component name.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from 'birnam'\n *\n * const log = logger('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nexport function logger (name: string, options?: LoggerOptions): Logger {\n // trace logging is a no-op by default\n let trace = createDisabledLogger(`${name}:trace`)\n\n // look at all the debug names and see if trace logging has explicitly been enabled\n if (debug.enabled(`${name}:trace`) && debug.names.map((r: any) => r.toString()).find((n: string) => n.includes(':trace')) != null) {\n trace = debug(`${name}:trace`, options)\n }\n\n return Object.assign(debug(name, options), {\n error: debug(`${name}:error`, options),\n trace,\n newScope: (scope: string) => logger(`${name}:${scope}`, options)\n })\n}\n\nexport function disable (): void {\n debug.disable()\n}\n\nexport function enable (namespaces: string): void {\n debug.enable(namespaces)\n}\n\nexport function enabled (namespaces: string): boolean {\n return debug.enabled(namespaces)\n}\n\nfunction notEmpty (str?: string): string | undefined {\n if (str == null) {\n return\n }\n\n str = str.trim()\n\n if (str.length === 0) {\n return\n }\n\n return str\n}\n", "import type { AbortOptions } from 'abort-error'\nimport type { Blockstore, InputPair, Pair } from 'interface-blockstore'\nimport type { CID } from 'multiformats/cid'\n\nexport class BaseBlockstore implements Blockstore {\n has (key: CID, options?: AbortOptions): boolean | Promise<boolean> {\n return Promise.reject(new Error('.has is not implemented'))\n }\n\n put (key: CID, val: Uint8Array | Iterable<Uint8Array> | AsyncIterable<Uint8Array>, options?: AbortOptions): CID | Promise<CID> {\n return Promise.reject(new Error('.put is not implemented'))\n }\n\n async * putMany (source: Iterable<InputPair> | AsyncIterable<InputPair>, options?: AbortOptions): Generator<CID> | AsyncGenerator<CID> {\n for await (const { cid, bytes } of source) {\n await this.put(cid, bytes, options)\n yield cid\n }\n }\n\n get (key: CID, options?: AbortOptions): Generator<Uint8Array> | AsyncGenerator<Uint8Array> {\n throw new Error('.get is not implemented')\n }\n\n async * getMany (source: Iterable<CID> | AsyncIterable<CID>, options?: AbortOptions): Generator<Pair> | AsyncGenerator<Pair> {\n for await (const key of source) {\n yield {\n cid: key,\n bytes: this.get(key, options)\n }\n }\n }\n\n delete (key: CID, options?: AbortOptions): void | Promise<void> {\n return Promise.reject(new Error('.delete is not implemented'))\n }\n\n async * deleteMany (source: Iterable<CID> | AsyncIterable<CID>, options?: AbortOptions): Generator<CID> | AsyncGenerator<CID> {\n for await (const key of source) {\n await this.delete(key, options)\n yield key\n }\n }\n\n /**\n * Extending classes should override `query` or implement this method\n */\n async * getAll (options?: AbortOptions): Generator<Pair> | AsyncGenerator<Pair> { // eslint-disable-line require-yield\n throw new Error('.getAll is not implemented')\n }\n}\n", "export class OpenFailedError extends Error {\n static name = 'OpenFailedError'\n name = OpenFailedError.name\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n static code = 'ERR_OPEN_FAILED'\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n code = OpenFailedError.code\n\n constructor (message = 'Open failed') {\n super(message)\n }\n}\n\nexport class CloseFailedError extends Error {\n static name = 'CloseFailedError'\n name = CloseFailedError.name\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n static code = 'ERR_CLOSE_FAILED'\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n code = CloseFailedError.code\n\n constructor (message = 'Close failed') {\n super(message)\n }\n}\n\nexport class PutFailedError extends Error {\n static name = 'PutFailedError'\n name = PutFailedError.name\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n static code = 'ERR_PUT_FAILED'\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n code = PutFailedError.code\n\n constructor (message = 'Put failed') {\n super(message)\n }\n}\n\nexport class GetFailedError extends Error {\n static name = 'GetFailedError'\n name = GetFailedError.name\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n static code = 'ERR_GET_FAILED'\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n code = GetFailedError.code\n\n constructor (message = 'Get failed') {\n super(message)\n }\n}\n\nexport class DeleteFailedError extends Error {\n static name = 'DeleteFailedError'\n name = DeleteFailedError.name\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n static code = 'ERR_DELETE_FAILED'\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n code = DeleteFailedError.code\n\n constructor (message = 'Delete failed') {\n super(message)\n }\n}\n\nexport class HasFailedError extends Error {\n static name = 'HasFailedError'\n name = HasFailedError.name\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n static code = 'ERR_HAS_FAILED'\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n code = HasFailedError.code\n\n constructor (message = 'Has failed') {\n super(message)\n }\n}\n\nexport class NotFoundError extends Error {\n static name = 'NotFoundError'\n name = NotFoundError.name\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n static code = 'ERR_NOT_FOUND'\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n code = NotFoundError.code\n\n constructor (message = 'Not Found') {\n super(message)\n }\n}\n\n/**\n * @deprecated import from 'abort-error' module instead - this will be removed in a future release\n */\nexport class AbortError extends Error {\n static name = 'AbortError'\n name = AbortError.name\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n static code = 'ERR_ABORTED'\n\n /**\n * @deprecated use `.name` instead - this will be removed in a future release\n */\n code = AbortError.code\n\n constructor (message = 'Aborted') {\n super(message)\n }\n}\n", "/**\n * @packageDocumentation\n *\n * For when you need a one-liner to collect iterable values.\n *\n * @example\n *\n * ```javascript\n * import all from 'it-all'\n *\n * // This can also be an iterator, etc\n * const values = function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const arr = all(values)\n *\n * console.info(arr) // 0, 1, 2, 3, 4\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const arr = await all(values())\n *\n * console.info(arr) // 0, 1, 2, 3, 4\n * ```\n */\n\nfunction isAsyncIterable <T> (thing: any): thing is AsyncIterable<T> {\n return thing[Symbol.asyncIterator] != null\n}\n\n/**\n * Collects all values from an (async) iterable and returns them as an array\n */\nfunction all <T> (source: Iterable<T>): T[]\nfunction all <T> (source: Iterable<T> | AsyncIterable<T>): Promise<T[]>\nfunction all <T> (source: Iterable<T> | AsyncIterable<T>): Promise<T[]> | T[] {\n if (isAsyncIterable(source)) {\n return (async () => {\n const arr = []\n\n for await (const entry of source) {\n arr.push(entry)\n }\n\n return arr\n })()\n }\n\n const arr = []\n\n for (const entry of source) {\n arr.push(entry)\n }\n\n return arr\n}\n\nexport default all\n", "import { NotFoundError } from 'interface-store'\nimport all from 'it-all'\nimport { base32 } from 'multiformats/bases/base32'\nimport { CID } from 'multiformats/cid'\nimport * as raw from 'multiformats/codecs/raw'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { BaseBlockstore } from './base.ts'\nimport type { AbortOptions } from 'abort-error'\nimport type { Pair } from 'interface-blockstore'\n\nfunction isPromise <T> (p?: any): p is Promise<T> {\n return typeof p?.then === 'function'\n}\n\nexport class MemoryBlockstore extends BaseBlockstore {\n private readonly data: Map<string, Uint8Array[]>\n\n constructor () {\n super()\n\n this.data = new Map()\n }\n\n put (key: CID, val: Uint8Array | Iterable<Uint8Array> | AsyncIterable<Uint8Array>, options?: AbortOptions): CID | Promise<CID> {\n options?.signal?.throwIfAborted()\n\n let buf: Uint8Array[]\n\n if (val instanceof Uint8Array) {\n buf = [val]\n } else {\n const result = all(val)\n\n if (isPromise<Uint8Array[]>(result)) {\n return result.then(val => {\n return this._put(key, val, options)\n })\n } else {\n buf = result\n }\n }\n\n return this._put(key, buf, options)\n }\n\n private _put (key: CID, val: Uint8Array[], options?: AbortOptions): CID | Promise<CID> {\n options?.signal?.throwIfAborted()\n\n this.data.set(base32.encode(key.multihash.bytes), val)\n\n return key\n }\n\n * get (key: CID, options?: AbortOptions): Generator<Uint8Array> | AsyncGenerator<Uint8Array> {\n options?.signal?.throwIfAborted()\n const buf = this.data.get(base32.encode(key.multihash.bytes))\n\n if (buf == null) {\n throw new NotFoundError()\n }\n\n yield * buf\n }\n\n has (key: CID, options?: AbortOptions): boolean | Promise<boolean> {\n options?.signal?.throwIfAborted()\n return this.data.has(base32.encode(key.multihash.bytes))\n }\n\n async delete (key: CID, options?: AbortOptions): Promise<void> {\n options?.signal?.throwIfAborted()\n this.data.delete(base32.encode(key.multihash.bytes))\n }\n\n * getAll (options?: AbortOptions): Generator<Pair> | AsyncGenerator<Pair> {\n options?.signal?.throwIfAborted()\n\n for (const [key, value] of this.data.entries()) {\n yield {\n cid: CID.createV1(raw.code, Digest.decode(base32.decode(key))),\n bytes: (async function * () {\n yield * value\n })()\n }\n options?.signal?.throwIfAborted()\n }\n }\n}\n", "/**\n * @packageDocumentation\n *\n * A logger for libp2p based on [weald](https://www.npmjs.com/package/weald), a TypeScript port of the venerable [debug](https://www.npmjs.com/package/debug) module.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('libp2p:my:component:name')\n *\n * try {\n * // an operation\n * log('something happened: %s', 'it was ok')\n * } catch (err) {\n * log.error('something bad happened: %e', err)\n * }\n *\n * log('with this peer: %p', {})\n * log('and this base58btc: %b', Uint8Array.from([0, 1, 2, 3]))\n * log('and this base32: %t', Uint8Array.from([4, 5, 6, 7]))\n * ```\n *\n * ```console\n * $ DEBUG=libp2p:* node index.js\n * something happened: it was ok\n * something bad happened: <stack trace>\n * with this peer: 12D3Foo\n * with this base58btc: Qmfoo\n * with this base32: bafyfoo\n * ```\n */\n\nimport { base32 } from 'multiformats/bases/base32'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base64 } from 'multiformats/bases/base64'\nimport debug from 'weald'\nimport { truncatePeerId } from './utils.ts'\nimport type { PeerId, Logger, ComponentLogger } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Key } from 'interface-datastore'\nimport type { CID } from 'multiformats/cid'\nimport type { Debugger, Options as LoggerOptions } from 'weald'\n\nexport type { LoggerOptions }\n\n// Add a formatter for converting to a base58 string\ndebug.formatters.b = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base58btc.baseEncode(v)\n}\n\n// Add a formatter for converting to a base32 string\ndebug.formatters.t = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base32.baseEncode(v)\n}\n\n// Add a formatter for converting to a base64 string\ndebug.formatters.m = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base64.baseEncode(v)\n}\n\n// Add a formatter for stringifying peer ids\ndebug.formatters.p = (v?: PeerId): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying CIDs\ndebug.formatters.c = (v?: CID): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Datastore keys\ndebug.formatters.k = (v: Key): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Multiaddrs\ndebug.formatters.a = (v?: Multiaddr): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\nfunction formatError (v: Error, indent = ''): string {\n const message = notEmpty(v.message)\n const stack = notEmpty(v.stack)\n\n // some browser errors (mostly from Firefox) have no message or no stack,\n // sometimes both, sometimes neither. Sometimes the message is in the stack,\n // sometimes is isn't so try to do *something* useful\n if (message != null && stack != null) {\n if (stack.includes(message)) {\n return `${stack.split('\\n').join(`\\n${indent}`)}`\n }\n\n return `${message}\\n${indent}${stack.split('\\n').join(`\\n${indent}`)}`\n }\n\n if (stack != null) {\n return `${stack.split('\\n').join(`\\n${indent}`)}`\n }\n\n if (message != null) {\n return `${message}`\n }\n\n return `${v.toString()}`\n}\n\nfunction isAggregateError (err?: any): err is AggregateError {\n return err instanceof AggregateError || (err?.name === 'AggregateError' && Array.isArray(err.errors))\n}\n\nfunction printError (err: Error, indent = ''): string {\n if (isAggregateError(err)) {\n let output = formatError(err, indent)\n\n if (err.errors.length > 0) {\n indent = `${indent} `\n\n output += `\\n${indent}${\n err.errors\n .map(err => `${printError(err, `${indent}`)}`)\n .join(`\\n${indent}`)\n }`\n } else {\n output += `\\n${indent}[Error list was empty]`\n }\n\n return output.trim()\n }\n\n return formatError(err, indent)\n}\n\n// Add a formatter for stringifying Errors\ndebug.formatters.e = (v?: Error): string => {\n if (v == null) {\n return 'undefined'\n }\n\n return printError(v)\n}\n\nexport type { Logger, ComponentLogger }\n\nfunction createDisabledLogger (namespace: string): Debugger {\n const logger = (): void => {}\n logger.enabled = false\n logger.color = ''\n logger.diff = 0\n logger.log = (): void => {}\n logger.namespace = namespace\n logger.destroy = () => true\n logger.extend = () => logger\n logger.useColors = () => false\n\n return logger\n}\n\nexport interface PeerLoggerOptions extends LoggerOptions {\n prefixLength?: number\n suffixLength?: number\n}\n\n/**\n * Create a component logger that will prefix any log messages with a truncated\n * peer id.\n *\n * @example\n *\n * ```TypeScript\n * import { peerLogger } from '@libp2p/logger'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const peerId = peerIdFromString('12D3FooBar')\n * const logger = peerLogger(peerId)\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"12\u2026oBar:my-component hello world\"\n * ```\n */\nexport function peerLogger (peerId: PeerId, options: PeerLoggerOptions = {}): ComponentLogger {\n return prefixLogger(truncatePeerId(peerId, options), options)\n}\n\n/**\n * Create a component logger that will prefix any log messages with the passed\n * string.\n *\n * @example\n *\n * ```TypeScript\n * import { prefixLogger } from '@libp2p/logger'\n *\n * const logger = prefixLogger('my-node')\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-node:my-component hello world\"\n * ```\n */\nexport function prefixLogger (prefix: string, options?: LoggerOptions): ComponentLogger {\n return {\n forComponent (name: string) {\n return logger(`${prefix}:${name}`, options)\n }\n }\n}\n\n/**\n * Create a component logger\n *\n * @example\n *\n * ```TypeScript\n * import { defaultLogger } from '@libp2p/logger'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const logger = defaultLogger()\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nexport function defaultLogger (options?: LoggerOptions): ComponentLogger {\n return {\n forComponent (name: string) {\n return logger(name, options)\n }\n }\n}\n\n/**\n * Creates a logger for the passed component name.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nexport function logger (name: string, options?: LoggerOptions): Logger {\n // trace logging is a no-op by default\n let trace: Debugger = createDisabledLogger(`${name}:trace`)\n\n // look at all the debug names and see if trace logging has explicitly been enabled\n if (debug.enabled(`${name}:trace`) && debug.names.map((r: any) => r.toString()).find((n: string) => n.includes(':trace')) != null) {\n trace = debug(`${name}:trace`, options)\n }\n\n return Object.assign(debug(name, options), {\n error: debug(`${name}:error`, options),\n trace,\n newScope: (scope: string) => logger(`${name}:${scope}`, options)\n })\n}\n\nexport function disable (): void {\n debug.disable()\n}\n\nexport function enable (namespaces: string): void {\n debug.enable(namespaces)\n}\n\nexport function enabled (namespaces: string): boolean {\n return debug.enabled(namespaces)\n}\n\nfunction notEmpty (str?: string): string | undefined {\n if (str == null) {\n return\n }\n\n str = str.trim()\n\n if (str.length === 0) {\n return\n }\n\n return str\n}\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 * Filter values out of an (async)iterable\n *\n * @example\n *\n * ```javascript\n * import all from 'it-all'\n * import filter from 'it-filter'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const fn = (val, index) => val > 2 // Return boolean to keep item\n *\n * const arr = all(filter(values, fn))\n *\n * console.info(arr) // 3, 4\n * ```\n *\n * Async sources and filter functions must be awaited:\n *\n * ```javascript\n * import all from 'it-all'\n * import filter from 'it-filter'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const fn = async val => (val, index) > 2 // Return boolean or promise of boolean to keep item\n *\n * const arr = await all(filter(values, fn))\n *\n * console.info(arr) // 3, 4\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 * Filters the passed (async) iterable by using the filter function\n */\nfunction filter <T> (source: Iterable<T>, fn: (val: T, index: number) => Promise<boolean>): AsyncGenerator<T, void, undefined>\nfunction filter <T> (source: Iterable<T>, fn: (val: T, index: number) => boolean): Generator<T, void, undefined>\nfunction filter <T> (source: Iterable<T> | AsyncIterable<T>, fn: (val: T, index: number) => boolean | Promise<boolean>): AsyncGenerator<T, void, undefined>\nfunction filter <T> (source: Iterable<T> | AsyncIterable<T>, fn: (val: T, index: number) => boolean | Promise<boolean>): Generator<T, void, undefined> | AsyncGenerator<T, void, undefined> {\n let index = 0\n\n if (isAsyncIterable(source)) {\n return (async function * () {\n for await (const entry of source) {\n if (await fn(entry, index++)) {\n yield entry\n }\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 = fn(value, index++)\n\n // @ts-expect-error .then is not present on O\n if (typeof res.then === 'function') {\n return (async function * () {\n if (await res) {\n yield value\n }\n\n for (const entry of peekable) {\n if (await fn(entry, index++)) {\n yield entry\n }\n }\n })()\n }\n\n const func = fn as (val: T, index: number) => boolean\n\n return (function * () {\n if (res === true) {\n yield value\n }\n\n for (const entry of peekable) {\n if (func(entry, index++)) {\n yield entry\n }\n }\n })()\n}\n\nexport default filter\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", "/**\n * @packageDocumentation\n *\n * Pass a promise and an abort signal and await the result.\n *\n * @example Basic usage\n *\n * ```ts\n * import { raceSignal } from 'race-signal'\n *\n * const controller = new AbortController()\n *\n * const promise = new Promise((resolve, reject) => {\n * setTimeout(() => {\n * resolve('a value')\n * }, 1000)\n * })\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * // throws an AbortError\n * const resolve = await raceSignal(promise, controller.signal)\n * ```\n *\n * @example Overriding errors\n *\n * By default the thrown error is the `.reason` property of the signal but it's\n * possible to override this behaviour with the `translateError` option:\n *\n * ```ts\n * import { raceSignal } from 'race-signal'\n *\n * const controller = new AbortController()\n *\n * const promise = new Promise((resolve, reject) => {\n * setTimeout(() => {\n * resolve('a value')\n * }, 1000)\n * })\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * // throws `Error('Oh no!')`\n * const resolve = await raceSignal(promise, controller.signal, {\n * translateError: (signal) => {\n * // use `signal`, or don't\n * return new Error('Oh no!')\n * }\n * })\n * ```\n */\n\nexport interface RaceSignalOptions {\n /**\n * By default the rejection reason will be taken from the `.reason` field of\n * the aborted signal.\n *\n * Passing a function here allows overriding the default error.\n */\n translateError?(signal: AbortSignal): Error\n}\n\nfunction defaultTranslate (signal: AbortSignal): Error {\n return signal.reason\n}\n\n/**\n * Race a promise against an abort signal\n */\nexport async function raceSignal <T> (promise: Promise<T>, signal?: AbortSignal, opts?: RaceSignalOptions): Promise<T> {\n if (signal == null) {\n return promise\n }\n\n const translateError = opts?.translateError ?? defaultTranslate\n\n if (signal.aborted) {\n // the passed promise may yet resolve or reject but the use has signalled\n // they are no longer interested so smother the error\n promise.catch(() => {})\n return Promise.reject(translateError(signal))\n }\n\n let listener\n\n try {\n return await Promise.race([\n promise,\n new Promise<T>((resolve, reject) => {\n listener = () => {\n reject(translateError(signal))\n }\n signal.addEventListener('abort', listener)\n })\n ])\n } finally {\n if (listener != null) {\n signal.removeEventListener('abort', listener)\n }\n }\n}\n", "/**\n * @packageDocumentation\n *\n * A pushable async generator that waits until the current value is consumed\n * before allowing a new value to be pushed.\n *\n * Useful for when you don't want to keep memory usage under control and/or\n * allow a downstream consumer to dictate how fast data flows through a pipe,\n * but you want to be able to apply a transform to that data.\n *\n * @example\n *\n * ```typescript\n * import { queuelessPushable } from 'it-queueless-pushable'\n *\n * const pushable = queuelessPushable<string>()\n *\n * // run asynchronously\n * Promise.resolve().then(async () => {\n * // push a value - the returned promise will not resolve until the value is\n * // read from the pushable\n * await pushable.push('hello')\n * })\n *\n * // read a value\n * const result = await pushable.next()\n * console.info(result) // { done: false, value: 'hello' }\n * ```\n */\n\nimport deferred from 'p-defer'\nimport { raceSignal } from 'race-signal'\nimport type { AbortOptions } from 'abort-error'\nimport type { RaceSignalOptions } from 'race-signal'\n\nexport interface Pushable<T> extends AsyncGenerator<T, void, unknown> {\n /**\n * End the iterable after all values in the buffer (if any) have been yielded. If an\n * error is passed the buffer is cleared immediately and the next iteration will\n * throw the passed error\n */\n end(err?: Error, options?: AbortOptions & RaceSignalOptions): Promise<void>\n\n /**\n * Push a value into the iterable. Values are yielded from the iterable in the order\n * they are pushed. Values not yet consumed from the iterable are buffered.\n */\n push(value: T, options?: AbortOptions & RaceSignalOptions): Promise<void>\n}\n\nclass QueuelessPushable <T> implements Pushable<T> {\n private readNext: PromiseWithResolvers<void>\n private haveNext: PromiseWithResolvers<void>\n private ended: boolean\n private nextResult: IteratorResult<T> | undefined\n private error?: Error\n\n constructor () {\n this.ended = false\n\n this.readNext = deferred()\n this.haveNext = deferred()\n }\n\n [Symbol.asyncIterator] (): AsyncGenerator<T, void, unknown> {\n return this\n }\n\n async next (): Promise<IteratorResult<T, void>> {\n if (this.nextResult == null) {\n // wait for the supplier to push a value\n await this.haveNext.promise\n }\n\n if (this.nextResult == null) {\n throw new Error('HaveNext promise resolved but nextResult was undefined')\n }\n\n const nextResult = this.nextResult\n this.nextResult = undefined\n\n // signal to the supplier that we read the value\n this.readNext.resolve()\n this.readNext = deferred()\n\n return nextResult\n }\n\n async throw (err?: Error): Promise<IteratorReturnResult<undefined>> {\n this.ended = true\n this.error = err\n\n if (err != null) {\n // this can cause unhandled promise rejections if nothing is awaiting the\n // next value so attach a dummy catch listener to the promise\n this.haveNext.promise.catch(() => {})\n this.haveNext.reject(err)\n }\n\n const result: IteratorReturnResult<undefined> = {\n done: true,\n value: undefined\n }\n\n return result\n }\n\n async return (): Promise<IteratorResult<T>> {\n const result: IteratorReturnResult<undefined> = {\n done: true,\n value: undefined\n }\n\n this.ended = true\n this.nextResult = result\n\n // let the consumer know we have a new value\n this.haveNext.resolve()\n\n return result\n }\n\n async push (value: T, options?: AbortOptions & RaceSignalOptions): Promise<void> {\n await this._push(value, options)\n }\n\n async end (err?: Error, options?: AbortOptions & RaceSignalOptions): Promise<void> {\n if (err != null) {\n await this.throw(err)\n } else {\n // abortable return\n await this._push(undefined, options)\n }\n }\n\n private async _push (value?: T, options?: AbortOptions & RaceSignalOptions): Promise<void> {\n if (value != null && this.ended) {\n throw this.error ?? new Error('Cannot push value onto an ended pushable')\n }\n\n // wait for all values to be read\n while (this.nextResult != null) {\n await this.readNext.promise\n }\n\n if (value != null) {\n this.nextResult = { done: false, value }\n } else {\n this.ended = true\n this.nextResult = { done: true, value: undefined }\n }\n\n // let the consumer know we have a new value\n this.haveNext.resolve()\n this.haveNext = deferred()\n\n // wait for the consumer to have finished processing the value and requested\n // the next one or for the passed signal to abort the waiting\n await raceSignal(\n this.readNext.promise,\n options?.signal,\n options\n )\n }\n}\n\nexport function queuelessPushable <T> (): Pushable<T> {\n return new QueuelessPushable<T>()\n}\n", "/**\n * @packageDocumentation\n *\n * Merge several (async)iterables into one, yield values as they arrive.\n *\n * Nb. sources are iterated over in parallel so the order of emitted items is not guaranteed.\n *\n * @example\n *\n * ```javascript\n * import merge from 'it-merge'\n * import all from 'it-all'\n *\n * // This can also be an iterator, generator, etc\n * const values1 = [0, 1, 2, 3, 4]\n * const values2 = [5, 6, 7, 8, 9]\n *\n * const arr = all(merge(values1, values2))\n *\n * console.info(arr) // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import merge from 'it-merge'\n * import all from 'it-all'\n *\n * // This can also be an iterator, async iterator, generator, etc\n * const values1 = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n * const values2 = async function * () {\n * yield * [5, 6, 7, 8, 9]\n * }\n *\n * const arr = await all(merge(values1(), values2()))\n *\n * console.info(arr) // 0, 1, 5, 6, 2, 3, 4, 7, 8, 9 <- nb. order is not guaranteed\n * ```\n */\n\nimport { queuelessPushable } from 'it-queueless-pushable'\nimport type { Pushable } from 'it-queueless-pushable'\n\nfunction isAsyncIterable <T> (thing: any): thing is AsyncIterable<T> {\n return thing[Symbol.asyncIterator] != null\n}\n\nasync function addAllToPushable <T> (sources: Array<AsyncIterable<T> | Iterable<T>>, output: Pushable<T>, signal: AbortSignal): Promise<void> {\n try {\n await Promise.all(\n sources.map(async (source) => {\n for await (const item of source) {\n await output.push(item, {\n signal\n })\n signal.throwIfAborted()\n }\n })\n )\n\n await output.end(undefined, {\n signal\n })\n } catch (err: any) {\n await output.end(err, {\n signal\n })\n .catch(() => {})\n }\n}\n\nasync function * mergeSources <T> (sources: Array<AsyncIterable<T> | Iterable<T>>): AsyncGenerator<T, void, undefined> {\n const controller = new AbortController()\n const output = queuelessPushable<T>()\n\n addAllToPushable(sources, output, controller.signal)\n .catch(() => {})\n\n try {\n yield * output\n } finally {\n controller.abort()\n }\n}\n\nfunction * mergeSyncSources <T> (syncSources: Array<Iterable<T>>): Generator<T, void, undefined> {\n for (const source of syncSources) {\n yield * source\n }\n}\n\n/**\n * Treat one or more iterables as a single iterable.\n *\n * Nb. sources are iterated over in parallel so the\n * order of emitted items is not guaranteed.\n */\nfunction merge <T> (...sources: Array<Iterable<T>>): Generator<T, void, undefined>\nfunction merge <T> (...sources: Array<AsyncIterable<T> | Iterable<T>>): AsyncGenerator<T, void, undefined>\nfunction merge <T> (...sources: Array<AsyncIterable<T> | Iterable<T>>): AsyncGenerator<T, void, undefined> | Generator<T, void, undefined> {\n const syncSources: Array<Iterable<T>> = []\n\n for (const source of sources) {\n if (!isAsyncIterable(source)) {\n syncSources.push(source)\n }\n }\n\n if (syncSources.length === sources.length) {\n // all sources are synchronous\n return mergeSyncSources(syncSources)\n }\n\n return mergeSources(sources)\n}\n\nexport default merge\n", "import { logger } from '@libp2p/logger'\nimport { NotFoundError } from 'interface-store'\nimport filter from 'it-filter'\nimport merge from 'it-merge'\nimport { BaseBlockstore } from './base.ts'\nimport type { AbortOptions } from 'abort-error'\nimport type { Blockstore, InputPair, Pair } from 'interface-blockstore'\nimport type { CID } from 'multiformats/cid'\n\nconst log = logger('blockstore:core:tiered')\n\n/**\n * A blockstore that can combine multiple stores. Puts and deletes\n * will write through to all blockstores. Has and get will\n * try each store sequentially. getAll will use every store but also\n * deduplicate any yielded pairs.\n */\nexport class TieredBlockstore extends BaseBlockstore {\n private readonly stores: Blockstore[]\n\n constructor (stores: Blockstore[]) {\n super()\n\n this.stores = stores.slice()\n }\n\n async put (key: CID, value: Uint8Array | Iterable<Uint8Array> | AsyncIterable<Uint8Array>, options?: AbortOptions): Promise<CID> {\n await Promise.all(\n this.stores.map(async store => {\n await store.put(key, value, options)\n })\n )\n\n return key\n }\n\n async * get (key: CID, options?: AbortOptions): Generator<Uint8Array> | AsyncGenerator<Uint8Array> {\n let error: Error | undefined\n\n for (const store of this.stores) {\n try {\n yield * store.get(key, options)\n return\n } catch (err: any) {\n error = err\n log.error(err)\n }\n }\n\n throw error ?? new NotFoundError()\n }\n\n async has (key: CID, options?: AbortOptions): Promise<boolean> {\n for (const s of this.stores) {\n if (await s.has(key, options)) {\n return true\n }\n }\n\n return false\n }\n\n async delete (key: CID, options?: AbortOptions): Promise<void> {\n await Promise.all(\n this.stores.map(async store => {\n await store.delete(key, options)\n })\n )\n }\n\n async * putMany (source: Iterable<InputPair> | AsyncIterable<InputPair>, options: AbortOptions = {}): Generator<CID> | AsyncGenerator<CID> {\n for await (const pair of source) {\n await this.put(pair.cid, pair.bytes, options)\n yield pair.cid\n }\n }\n\n async * deleteMany (source: Iterable<CID> | AsyncIterable<CID>, options: AbortOptions = {}): Generator<CID> | AsyncGenerator<CID> {\n for await (const cid of source) {\n await this.delete(cid, options)\n yield cid\n }\n }\n\n async * getAll (options?: AbortOptions): Generator<Pair> | AsyncGenerator<Pair> {\n // deduplicate yielded pairs\n const seen = new Set<string>()\n\n yield * filter(merge(...this.stores.map(s => s.getAll(options))), (pair) => {\n const cidStr = pair.cid.toString()\n\n if (seen.has(cidStr)) {\n return false\n }\n\n seen.add(cidStr)\n\n return true\n })\n }\n}\n", "import { Key } from 'interface-datastore/key'\nimport type { Shard } from './index.ts'\nimport type { Datastore } from 'interface-datastore'\n\nexport const PREFIX = '/repo/flatfs/shard/'\nexport const SHARDING_FN = 'SHARDING'\n\nexport class ShardBase implements Shard {\n public param: number\n public name: string\n public _padding: string\n\n constructor (param: number) {\n this.param = param\n this.name = 'base'\n this._padding = ''\n }\n\n fun (s: string): string {\n return 'implement me'\n }\n\n toString (): string {\n return `${PREFIX}v1/${this.name}/${this.param}`\n }\n}\n\nexport class Prefix extends ShardBase {\n constructor (prefixLen: number) {\n super(prefixLen)\n this._padding = ''.padStart(prefixLen, '_')\n this.name = 'prefix'\n }\n\n fun (noslash: string): string {\n return (noslash + this._padding).slice(0, this.param)\n }\n}\n\nexport class Suffix extends ShardBase {\n constructor (suffixLen: number) {\n super(suffixLen)\n\n this._padding = ''.padStart(suffixLen, '_')\n this.name = 'suffix'\n }\n\n fun (noslash: string): string {\n const s = this._padding + noslash\n return s.slice(s.length - this.param)\n }\n}\n\nexport class NextToLast extends ShardBase {\n constructor (suffixLen: number) {\n super(suffixLen)\n this._padding = ''.padStart(suffixLen + 1, '_')\n this.name = 'next-to-last'\n }\n\n fun (noslash: string): string {\n const s = this._padding + noslash\n const offset = s.length - this.param - 1\n return s.slice(offset, offset + this.param)\n }\n}\n\n/**\n * Convert a given string to the matching sharding function\n */\nexport function parseShardFun (str: string): Shard {\n str = str.trim()\n\n if (str.length === 0) {\n throw new Error('empty shard string')\n }\n\n if (!str.startsWith(PREFIX)) {\n throw new Error(`invalid or no path prefix: ${str}`)\n }\n\n const parts = str.slice(PREFIX.length).split('/')\n const version = parts[0]\n\n if (version !== 'v1') {\n throw new Error(`expect 'v1' version, got '${version}'`)\n }\n\n const name = parts[1]\n\n if (parts[2] == null || parts[2] === '') {\n throw new Error('missing param')\n }\n\n const param = parseInt(parts[2], 10)\n\n switch (name) {\n case 'prefix':\n return new Prefix(param)\n case 'suffix':\n return new Suffix(param)\n case 'next-to-last':\n return new NextToLast(param)\n default:\n throw new Error(`unkown sharding function: ${name}`)\n }\n}\n\nexport const readShardFun = async (path: string | Uint8Array, store: Datastore): Promise<Shard> => {\n const key = new Key(path).child(new Key(SHARDING_FN))\n // @ts-expect-error not all stores have this\n const get = typeof store.getRaw === 'function' ? store.getRaw.bind(store) : store.get.bind(store)\n const res = await get(key)\n return parseShardFun(new TextDecoder().decode(res ?? '').trim())\n}\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 * Consumes all values from an (async)iterable and returns them sorted by the passed sort function.\n *\n * @example\n *\n * ```javascript\n * import sort from 'it-sort'\n * import all from 'it-all'\n *\n * const sorter = (a, b) => {\n * return a.localeCompare(b)\n * }\n *\n * // This can also be an iterator, generator, etc\n * const values = ['foo', 'bar']\n *\n * const arr = all(sort(values, sorter))\n *\n * console.info(arr) // 'bar', 'foo'\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import sort from 'it-sort'\n * import all from 'it-all'\n *\n * const sorter = (a, b) => {\n * return a.localeCompare(b)\n * }\n *\n * const values = async function * () {\n * yield * ['foo', 'bar']\n * }\n *\n * const arr = await all(sort(values, sorter))\n *\n * console.info(arr) // 'bar', 'foo'\n * ```\n */\n\nimport all from 'it-all'\n\nfunction isAsyncIterable <T> (thing: any): thing is AsyncIterable<T> {\n return thing[Symbol.asyncIterator] != null\n}\n\nexport interface CompareFunction<T> {\n (a: T, b: T): number\n}\n\n/**\n * Collects all values from an async iterator, sorts them\n * using the passed function and yields them\n */\nfunction sort <T> (source: Iterable<T>, sorter: CompareFunction<T>): Generator<T, void, undefined>\nfunction sort <T> (source: Iterable<T> | AsyncIterable<T>, sorter: CompareFunction<T>): AsyncGenerator<T, void, undefined>\nfunction sort <T> (source: Iterable<T> | AsyncIterable<T>, sorter: CompareFunction<T>): AsyncGenerator<T, void, undefined> | Generator<T, void, undefined> {\n if (isAsyncIterable(source)) {\n return (async function * () {\n const arr = await all(source)\n\n yield * arr.sort(sorter)\n })()\n }\n\n return (function * () {\n const arr = all(source)\n\n yield * arr.sort(sorter)\n })()\n}\n\nexport default sort\n", "/**\n * @packageDocumentation\n *\n * For when you only want a few values out of an (async)iterable.\n *\n * @example\n *\n * ```javascript\n * import take from 'it-take'\n * import all from 'it-all'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const arr = all(take(values, 2))\n *\n * console.info(arr) // 0, 1\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import take from 'it-take'\n * import all from 'it-all'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const arr = await all(take(values(), 2))\n *\n * console.info(arr) // 0, 1\n * ```\n */\n\nfunction isAsyncIterable <T> (thing: any): thing is AsyncIterable<T> {\n return thing[Symbol.asyncIterator] != null\n}\n\n/**\n * Stop iteration after n items have been received\n */\nfunction take <T> (source: Iterable<T>, limit: number): Generator<T, void, undefined>\nfunction take <T> (source: Iterable<T> | AsyncIterable<T>, limit: number): AsyncGenerator<T, void, undefined>\nfunction take <T> (source: Iterable<T> | AsyncIterable<T>, limit: number): AsyncGenerator<T, void, undefined> | Generator<T, void, undefined> {\n if (isAsyncIterable(source)) {\n return (async function * () {\n let items = 0\n\n if (limit < 1) {\n return\n }\n\n for await (const entry of source) {\n yield entry\n\n items++\n\n if (items === limit) {\n return\n }\n }\n })()\n }\n\n return (function * () {\n let items = 0\n\n if (limit < 1) {\n return\n }\n\n for (const entry of source) {\n yield entry\n\n items++\n\n if (items === limit) {\n return\n }\n }\n })()\n}\n\nexport default take\n", "import drain from 'it-drain'\nimport filter from 'it-filter'\nimport sort from 'it-sort'\nimport take from 'it-take'\nimport type { AbortOptions } from 'abort-error'\nimport type { Batch, Datastore, Key, KeyQuery, Pair, Query } from 'interface-datastore'\n\nexport class BaseDatastore implements Datastore {\n put (key: Key, val: Uint8Array, options?: AbortOptions): Key | Promise<Key> {\n return Promise.reject(new Error('.put is not implemented'))\n }\n\n get (key: Key, options?: AbortOptions): Uint8Array | Promise<Uint8Array> {\n return Promise.reject(new Error('.get is not implemented'))\n }\n\n has (key: Key, options?: AbortOptions): boolean | Promise<boolean> {\n return Promise.reject(new Error('.has is not implemented'))\n }\n\n delete (key: Key, options?: AbortOptions): void | Promise<void> {\n return Promise.reject(new Error('.delete is not implemented'))\n }\n\n async * putMany (source: Iterable<Pair> | AsyncIterable<Pair>, options: AbortOptions = {}): Generator<Key> | AsyncGenerator<Key> {\n for await (const { key, value } of source) {\n await this.put(key, value, options)\n yield key\n }\n }\n\n async * getMany (source: Iterable<Key> | AsyncIterable<Key>, options: AbortOptions = {}): Generator<Pair> | AsyncGenerator<Pair> {\n for await (const key of source) {\n yield {\n key,\n value: await this.get(key, options)\n }\n }\n }\n\n async * deleteMany (source: Iterable<Key> | AsyncIterable<Key>, options: AbortOptions = {}): Generator<Key> | AsyncGenerator<Key> {\n for await (const key of source) {\n await this.delete(key, options)\n yield key\n }\n }\n\n batch (): Batch {\n let puts: Pair[] = []\n let dels: Key[] = []\n\n return {\n put (key, value) {\n puts.push({ key, value })\n },\n\n delete (key) {\n dels.push(key)\n },\n commit: async (options) => {\n await drain(this.putMany(puts, options))\n puts = []\n await drain(this.deleteMany(dels, options))\n dels = []\n }\n }\n }\n\n /**\n * Extending classes should override `query` or implement this method\n */\n // eslint-disable-next-line require-yield\n async * _all (q: Query, options?: AbortOptions): Generator<Pair> | AsyncGenerator<Pair> {\n throw new Error('._all is not implemented')\n }\n\n /**\n * Extending classes should override `queryKeys` or implement this method\n */\n // eslint-disable-next-line require-yield\n async * _allKeys (q: KeyQuery, options?: AbortOptions): Generator<Key> | AsyncGenerator<Key> {\n throw new Error('._allKeys is not implemented')\n }\n\n query (q: Query, options?: AbortOptions): Generator<Pair> | AsyncGenerator<Pair> {\n let it = this._all(q, options)\n\n if (q.prefix != null) {\n const prefix = q.prefix\n it = filter(it, (e) => e.key.toString().startsWith(prefix))\n }\n\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it)\n }\n\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sort(it, f), it)\n }\n\n if (q.offset != null) {\n let i = 0\n const offset = q.offset\n it = filter(it, () => i++ >= offset)\n }\n\n if (q.limit != null) {\n it = take(it, q.limit)\n }\n\n return it\n }\n\n queryKeys (q: KeyQuery, options?: AbortOptions): Generator<Key> | AsyncGenerator<Key> {\n let it = this._allKeys(q, options)\n\n if (q.prefix != null) {\n const prefix = q.prefix\n it = filter(it, (key) =>\n key.toString().startsWith(prefix)\n )\n }\n\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it)\n }\n\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sort(it, f), it)\n }\n\n if (q.offset != null) {\n const offset = q.offset\n let i = 0\n it = filter(it, () => i++ >= offset)\n }\n\n if (q.limit != null) {\n it = take(it, q.limit)\n }\n\n return it\n }\n}\n", "import { Key } from 'interface-datastore/key'\nimport { NotFoundError } from 'interface-store'\nimport { BaseDatastore } from './base.ts'\nimport type { AbortOptions } from 'abort-error'\nimport type { KeyQuery, Pair, Query } from 'interface-datastore'\n\nexport class MemoryDatastore extends BaseDatastore {\n private readonly data: Map<string, Uint8Array>\n\n constructor () {\n super()\n\n this.data = new Map()\n }\n\n put (key: Key, val: Uint8Array, options?: AbortOptions): Key | Promise<Key> {\n options?.signal?.throwIfAborted()\n\n this.data.set(key.toString(), val)\n\n return key\n }\n\n get (key: Key, options?: AbortOptions): Uint8Array | Promise<Uint8Array> {\n options?.signal?.throwIfAborted()\n\n const result = this.data.get(key.toString())\n\n if (result == null) {\n throw new NotFoundError()\n }\n\n return result\n }\n\n has (key: Key, options?: AbortOptions): boolean | Promise<boolean> {\n options?.signal?.throwIfAborted()\n return this.data.has(key.toString())\n }\n\n delete (key: Key, options?: AbortOptions): void | Promise<void> {\n options?.signal?.throwIfAborted()\n this.data.delete(key.toString())\n }\n\n * _all (q: Query, options?: AbortOptions): Generator<Pair> | AsyncGenerator<Pair> {\n options?.signal?.throwIfAborted()\n for (const [key, value] of this.data.entries()) {\n yield { key: new Key(key), value }\n options?.signal?.throwIfAborted()\n }\n }\n\n * _allKeys (q: KeyQuery, options?: AbortOptions): Generator<Key> | AsyncGenerator<Key> {\n options?.signal?.throwIfAborted()\n for (const key of this.data.keys()) {\n yield new Key(key)\n options?.signal?.throwIfAborted()\n }\n }\n}\n", "// ported from https://www.npmjs.com/package/fast-fifo\n\nexport interface Next<T> {\n done?: boolean\n error?: Error\n value?: T\n}\n\nclass FixedFIFO<T> {\n public buffer: Array<Next<T> | undefined>\n private readonly mask: number\n private top: number\n private btm: number\n public next: FixedFIFO<T> | null\n\n constructor (hwm: number) {\n if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) {\n throw new Error('Max size for a FixedFIFO should be a power of two')\n }\n\n this.buffer = new Array(hwm)\n this.mask = hwm - 1\n this.top = 0\n this.btm = 0\n this.next = null\n }\n\n push (data: Next<T>): boolean {\n if (this.buffer[this.top] !== undefined) {\n return false\n }\n\n this.buffer[this.top] = data\n this.top = (this.top + 1) & this.mask\n\n return true\n }\n\n shift (): Next<T> | undefined {\n const last = this.buffer[this.btm]\n\n if (last === undefined) {\n return undefined\n }\n\n this.buffer[this.btm] = undefined\n this.btm = (this.btm + 1) & this.mask\n return last\n }\n\n isEmpty (): boolean {\n return this.buffer[this.btm] === undefined\n }\n}\n\nexport interface FIFOOptions {\n /**\n * When the queue reaches this size, it will be split into head/tail parts\n */\n splitLimit?: number\n}\n\nexport class FIFO<T> {\n public size: number\n private readonly hwm: number\n private head: FixedFIFO<T>\n private tail: FixedFIFO<T>\n\n constructor (options: FIFOOptions = {}) {\n this.hwm = options.splitLimit ?? 16\n this.head = new FixedFIFO<T>(this.hwm)\n this.tail = this.head\n this.size = 0\n }\n\n calculateSize (obj: any): number {\n if (obj?.byteLength != null) {\n return obj.byteLength\n }\n\n return 1\n }\n\n push (val: Next<T>): void {\n if (val?.value != null) {\n this.size += this.calculateSize(val.value)\n }\n\n if (!this.head.push(val)) {\n const prev = this.head\n this.head = prev.next = new FixedFIFO<T>(2 * this.head.buffer.length)\n this.head.push(val)\n }\n }\n\n shift (): Next<T> | undefined {\n let val = this.tail.shift()\n\n if (val === undefined && (this.tail.next != null)) {\n const next = this.tail.next\n this.tail.next = null\n this.tail = next\n val = this.tail.shift()\n }\n\n if (val?.value != null) {\n this.size -= this.calculateSize(val.value)\n }\n\n return val\n }\n\n isEmpty (): boolean {\n return this.head.isEmpty()\n }\n}\n", "/**\n * @packageDocumentation\n *\n * An iterable that you can push values into.\n *\n * @example\n *\n * ```js\n * import { pushable } from 'it-pushable'\n *\n * const source = pushable()\n *\n * setTimeout(() => source.push('hello'), 100)\n * setTimeout(() => source.push('world'), 200)\n * setTimeout(() => source.end(), 300)\n *\n * const start = Date.now()\n *\n * for await (const value of source) {\n * console.log(`got \"${value}\" after ${Date.now() - start}ms`)\n * }\n * console.log(`done after ${Date.now() - start}ms`)\n *\n * // Output:\n * // got \"hello\" after 105ms\n * // got \"world\" after 207ms\n * // done after 309ms\n * ```\n *\n * @example\n *\n * ```js\n * import { pushableV } from 'it-pushable'\n * import all from 'it-all'\n *\n * const source = pushableV()\n *\n * source.push(1)\n * source.push(2)\n * source.push(3)\n * source.end()\n *\n * console.info(await all(source))\n *\n * // Output:\n * // [ [1, 2, 3] ]\n * ```\n */\n\nimport deferred from 'p-defer'\nimport { FIFO } from './fifo.ts'\nimport type { Next } from './fifo.ts'\n\nexport class AbortError extends Error {\n type: string\n code: string\n\n constructor (message?: string, code?: string) {\n super(message ?? 'The operation was aborted')\n this.type = 'aborted'\n this.code = code ?? 'ABORT_ERR'\n }\n}\n\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\ninterface BasePushable<T> {\n /**\n * End the iterable after all values in the buffer (if any) have been yielded. If an\n * error is passed the buffer is cleared immediately and the next iteration will\n * throw the passed error\n */\n end(err?: Error): this\n\n /**\n * Push a value into the iterable. Values are yielded from the iterable in the order\n * they are pushed. Values not yet consumed from the iterable are buffered.\n */\n push(value: T): this\n\n /**\n * Returns a promise that resolves when the underlying queue becomes empty (e.g.\n * this.readableLength === 0).\n *\n * If an AbortSignal is passed as an option and that signal aborts, it only\n * causes the returned promise to reject - it does not end the pushable.\n */\n onEmpty(options?: AbortOptions): Promise<void>\n\n /**\n * This property contains the number of bytes (or objects) in the queue ready to be read.\n *\n * If `objectMode` is true, this is the number of objects in the queue, if false it's the\n * total number of bytes in the queue.\n */\n readableLength: number\n}\n\n/**\n * An iterable that you can push values into.\n */\nexport interface Pushable<T, R = void, N = unknown> extends AsyncGenerator<T, R, N>, BasePushable<T> {}\n\n/**\n * Similar to `pushable`, except it yields multiple buffered chunks at a time. All values yielded from the iterable will be arrays.\n */\nexport interface PushableV<T, R = void, N = unknown> extends AsyncGenerator<T[], R, N>, BasePushable<T> {}\n\nexport interface Options {\n /**\n * A boolean value that means non-`Uint8Array`s will be passed to `.push`, default: `false`\n */\n objectMode?: boolean\n\n /**\n * A function called after *all* values have been yielded from the iterator (including\n * buffered values). In the case when the iterator is ended with an error it will be\n * passed the error as a parameter.\n */\n onEnd?(err?: Error): void\n}\n\nexport interface DoneResult { done: true }\nexport interface ValueResult<T> { done: false, value: T }\nexport type NextResult<T> = ValueResult<T> | DoneResult\n\ninterface getNext<T, V = T> { (buffer: FIFO<T>): NextResult<V> }\n\nexport interface ObjectPushableOptions extends Options {\n objectMode: true\n}\n\nexport interface BytePushableOptions extends Options {\n objectMode?: false\n}\n\n/**\n * Create a new async iterable. The values yielded from calls to `.next()`\n * or when used in a `for await of`loop are \"pushed\" into the iterable.\n * Returns an async iterable object with additional methods.\n */\nexport function pushable<T extends { byteLength: number } = Uint8Array> (options?: BytePushableOptions): Pushable<T>\nexport function pushable<T> (options: ObjectPushableOptions): Pushable<T>\nexport function pushable<T> (options: Options = {}): Pushable<T> {\n const getNext = (buffer: FIFO<T>): NextResult<T> => {\n const next: Next<T> | undefined = buffer.shift()\n\n if (next == null) {\n return { done: true }\n }\n\n if (next.error != null) {\n throw next.error\n }\n\n return {\n done: next.done === true,\n // @ts-expect-error if done is false, value will be present\n value: next.value\n }\n }\n\n return _pushable<T, T, Pushable<T>>(getNext, options)\n}\n\nexport function pushableV<T extends { byteLength: number } = Uint8Array> (options?: BytePushableOptions): PushableV<T>\nexport function pushableV<T> (options: ObjectPushableOptions): PushableV<T>\nexport function pushableV<T> (options: Options = {}): PushableV<T> {\n const getNext = (buffer: FIFO<T>): NextResult<T[]> => {\n let next: Next<T> | undefined\n const values: T[] = []\n\n while (!buffer.isEmpty()) {\n next = buffer.shift()\n\n if (next == null) {\n break\n }\n\n if (next.error != null) {\n throw next.error\n }\n\n if (next.done === false) {\n // @ts-expect-error if done is false value should be pushed\n values.push(next.value)\n }\n }\n\n if (next == null) {\n return { done: true }\n }\n\n return {\n done: next.done === true,\n value: values\n }\n }\n\n return _pushable<T, T[], PushableV<T>>(getNext, options)\n}\n\nfunction _pushable<PushType, ValueType, ReturnType> (getNext: getNext<PushType, ValueType>, options?: Options): ReturnType {\n options = options ?? {}\n let onEnd = options.onEnd\n let buffer = new FIFO<PushType>()\n let pushable: any\n let onNext: ((next: Next<PushType>) => ReturnType) | null\n let ended: boolean\n let drain = deferred()\n\n const waitNext = async (): Promise<NextResult<ValueType>> => {\n try {\n if (!buffer.isEmpty()) {\n return getNext(buffer)\n }\n\n if (ended) {\n return { done: true }\n }\n\n return await new Promise<NextResult<ValueType>>((resolve, reject) => {\n onNext = (next: Next<PushType>) => {\n onNext = null\n buffer.push(next)\n\n try {\n resolve(getNext(buffer))\n } catch (err) {\n reject(err)\n }\n\n return pushable\n }\n })\n } finally {\n if (buffer.isEmpty()) {\n // settle promise in the microtask queue to give consumers a chance to\n // await after calling .push\n queueMicrotask(() => {\n drain.resolve()\n drain = deferred()\n })\n }\n }\n }\n\n const bufferNext = (next: Next<PushType>): ReturnType => {\n if (onNext != null) {\n return onNext(next)\n }\n\n buffer.push(next)\n return pushable\n }\n\n const bufferError = (err: Error): ReturnType => {\n buffer = new FIFO()\n\n if (onNext != null) {\n return onNext({ error: err })\n }\n\n buffer.push({ error: err })\n return pushable\n }\n\n const push = (value: PushType): ReturnType => {\n if (ended) {\n return pushable\n }\n\n // @ts-expect-error `byteLength` is not declared on PushType\n if (options?.objectMode !== true && value?.byteLength == null) {\n throw new Error('objectMode was not true but tried to push non-Uint8Array value')\n }\n\n return bufferNext({ done: false, value })\n }\n const end = (err?: Error): ReturnType => {\n if (ended) { return pushable }\n ended = true\n\n return (err != null) ? bufferError(err) : bufferNext({ done: true })\n }\n const _return = (): DoneResult => {\n buffer = new FIFO()\n end()\n\n return { done: true }\n }\n const _throw = (err: Error): DoneResult => {\n end(err)\n\n return { done: true }\n }\n\n pushable = {\n [Symbol.asyncIterator] () { return this },\n next: waitNext,\n return: _return,\n throw: _throw,\n push,\n end,\n get readableLength (): number {\n return buffer.size\n },\n onEmpty: async (options?: AbortOptions) => {\n const signal = options?.signal\n signal?.throwIfAborted()\n\n if (buffer.isEmpty()) {\n return\n }\n\n let cancel: Promise<void> | undefined\n let listener: (() => void) | undefined\n\n if (signal != null) {\n cancel = new Promise((resolve, reject) => {\n listener = () => {\n reject(new AbortError())\n }\n\n signal.addEventListener('abort', listener)\n })\n }\n\n try {\n await Promise.race([\n drain.promise,\n cancel\n ])\n } finally {\n if (listener != null && signal != null) {\n signal?.removeEventListener('abort', listener)\n }\n }\n }\n }\n\n if (onEnd == null) {\n return pushable\n }\n\n const _pushable = pushable\n\n pushable = {\n [Symbol.asyncIterator] () { return this },\n next () {\n return _pushable.next()\n },\n throw (err: Error) {\n _pushable.throw(err)\n\n if (onEnd != null) {\n onEnd(err)\n onEnd = undefined\n }\n\n return { done: true }\n },\n return () {\n _pushable.return()\n\n if (onEnd != null) {\n onEnd()\n onEnd = undefined\n }\n\n return { done: true }\n },\n push,\n end (err: Error) {\n _pushable.end(err)\n\n if (onEnd != null) {\n onEnd(err)\n onEnd = undefined\n }\n\n return pushable\n },\n get readableLength () {\n return _pushable.readableLength\n },\n onEmpty: (opts?: AbortOptions) => {\n return _pushable.onEmpty(opts)\n }\n }\n\n return pushable\n}\n", "import { Key } from 'interface-datastore'\nimport { OpenFailedError } from 'interface-store'\nimport { BaseDatastore } from './base.ts'\nimport { KeyTransformDatastore } from './keytransform.ts'\nimport {\n readShardFun,\n SHARDING_FN\n} from './shard.ts'\nimport type { Shard } from './index.ts'\nimport type { AbortOptions } from 'abort-error'\nimport type { Batch, KeyQuery, KeyQueryFilter, Pair, Query, QueryFilter, Datastore } from 'interface-datastore'\n\nconst shardKey = new Key(SHARDING_FN)\n\n/**\n * Backend independent abstraction of go-ds-flatfs.\n *\n * Wraps another datastore such that all values are stored\n * sharded according to the given sharding function.\n */\nexport class ShardingDatastore extends BaseDatastore {\n private readonly child: KeyTransformDatastore\n private shard: Shard\n\n constructor (store: Datastore, shard: Shard) {\n super()\n\n this.child = new KeyTransformDatastore(store, {\n convert: this._convertKey.bind(this),\n invert: this._invertKey.bind(this)\n })\n this.shard = shard\n }\n\n async open (): Promise<void> {\n this.shard = await ShardingDatastore.create(this.child, this.shard)\n }\n\n _convertKey (key: Key): Key {\n const s = key.toString()\n if (s === shardKey.toString()) {\n return key\n }\n\n const parent = new Key(this.shard.fun(s))\n return parent.child(key)\n }\n\n _invertKey (key: Key): Key {\n const s = key.toString()\n if (s === shardKey.toString()) {\n return key\n }\n return Key.withNamespaces(key.list().slice(1))\n }\n\n static async create (store: Datastore, shard?: Shard): Promise<Shard> {\n const hasShard = await store.has(shardKey)\n\n if (!hasShard) {\n if (shard == null) {\n throw new OpenFailedError('Shard is required when datastore doesn\\'t have a shard key already')\n }\n\n await store.put(shardKey, new TextEncoder().encode(shard.toString() + '\\n'))\n }\n\n if (shard == null) {\n shard = await readShardFun('/', store)\n }\n\n // test shards\n const diskShard = await readShardFun('/', store)\n const a = diskShard.toString()\n const b = shard.toString()\n\n if (a !== b) {\n throw new Error(`specified fun ${b} does not match repo shard fun ${a}`)\n }\n\n return diskShard\n }\n\n async put (key: Key, val: Uint8Array, options?: AbortOptions): Promise<Key> {\n await this.child.put(key, val, options)\n\n return key\n }\n\n async get (key: Key, options?: AbortOptions): Promise<Uint8Array> {\n return this.child.get(key, options)\n }\n\n async has (key: Key, options?: AbortOptions): Promise<boolean> {\n return this.child.has(key, options)\n }\n\n async delete (key: Key, options?: AbortOptions): Promise<void> {\n await this.child.delete(key, options)\n }\n\n async * putMany (source: Iterable<Pair> | AsyncIterable<Pair>, options: AbortOptions = {}): Generator<Key> | AsyncGenerator<Key> {\n yield * this.child.putMany(source, options)\n }\n\n async * getMany (source: Iterable<Key> | AsyncIterable<Key>, options: AbortOptions = {}): Generator<Pair> | AsyncGenerator<Pair> {\n yield * this.child.getMany(source, options)\n }\n\n async * deleteMany (source: Iterable<Key> | AsyncIterable<Key>, options: AbortOptions = {}): Generator<Key> | AsyncGenerator<Key> {\n yield * this.child.deleteMany(source, options)\n }\n\n batch (): Batch {\n return this.child.batch()\n }\n\n query (q: Query, options?: AbortOptions): Generator<Pair> | AsyncGenerator<Pair> {\n const omitShard: QueryFilter = ({ key }) => key.toString() !== shardKey.toString()\n\n const tq: Query = {\n ...q,\n filters: [\n omitShard\n ].concat(q.filters ?? [])\n }\n\n return this.child.query(tq, options)\n }\n\n queryKeys (q: KeyQuery, options?: AbortOptions): Generator<Key> | AsyncGenerator<Key> {\n const omitShard: KeyQueryFilter = (key) => key.toString() !== shardKey.toString()\n\n const tq: KeyQuery = {\n ...q,\n filters: [\n omitShard\n ].concat(q.filters ?? [])\n }\n\n return this.child.queryKeys(tq, options)\n }\n}\n", "import { logger } from '@libp2p/logger'\nimport { NotFoundError } from 'interface-store'\nimport { BaseDatastore } from './base.ts'\nimport type { AbortOptions } from 'abort-error'\nimport type { Batch, Datastore, Key, KeyQuery, Pair, Query } from 'interface-datastore'\n\nconst log = logger('datastore:core:tiered')\n\n/**\n * A datastore that can combine multiple stores. Puts and deletes\n * will write through to all datastores. Has and get will\n * try each store sequentially. Query will always try the\n * last one first.\n *\n */\nexport class TieredDatastore extends BaseDatastore {\n private readonly stores: Datastore[]\n\n constructor (stores: Datastore[]) {\n super()\n\n this.stores = stores.slice()\n }\n\n async put (key: Key, value: Uint8Array, options?: AbortOptions): Promise<Key> {\n await Promise.all(\n this.stores.map(async store => {\n await store.put(key, value, options)\n })\n )\n\n return key\n }\n\n async get (key: Key, options?: AbortOptions): Promise<Uint8Array> {\n let error: Error | undefined\n\n for (const store of this.stores) {\n try {\n const res = await store.get(key, options)\n\n if (res != null) {\n return res\n }\n } catch (err: any) {\n error = err\n log.error(err)\n }\n }\n\n throw error ?? new NotFoundError()\n }\n\n async has (key: Key, options?: AbortOptions): Promise<boolean> {\n for (const s of this.stores) {\n if (await s.has(key, options)) {\n return true\n }\n }\n\n return false\n }\n\n async delete (key: Key, options?: AbortOptions): Promise<void> {\n await Promise.all(\n this.stores.map(async store => {\n await store.delete(key, options)\n })\n )\n }\n\n async * putMany (source: Iterable<Pair> | AsyncIterable<Pair>, options: AbortOptions = {}): Generator<Key> | AsyncGenerator<Key> {\n for await (const pair of source) {\n await this.put(pair.key, pair.value, options)\n yield pair.key\n }\n }\n\n async * deleteMany (source: Iterable<Key> | AsyncIterable<Key>, options: AbortOptions = {}): Generator<Key> | AsyncGenerator<Key> {\n for await (const key of source) {\n await this.delete(key, options)\n yield key\n }\n }\n\n batch (): Batch {\n const batches = this.stores.map(store => store.batch())\n\n return {\n put: (key, value) => {\n batches.forEach(b => { b.put(key, value) })\n },\n delete: (key) => {\n batches.forEach(b => { b.delete(key) })\n },\n commit: async (options) => {\n for (const batch of batches) {\n await batch.commit(options)\n }\n }\n }\n }\n\n query (q: Query, options?: AbortOptions): Generator<Pair> | AsyncGenerator<Pair> {\n return this.stores[this.stores.length - 1].query(q, options)\n }\n\n queryKeys (q: KeyQuery, options?: AbortOptions): Generator<Key> | AsyncGenerator<Key> {\n return this.stores[this.stores.length - 1].queryKeys(q, options)\n }\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\n// Types that reach getObjectType() - excludes types with fast-paths above:\n// primitives (typeof), Array (isArray), Uint8Array (instanceof), plain Object (constructor)\nconst objectTypeNames = [\n 'Object', // for Object.create(null) and other non-plain objects\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 'Uint8ClampedArray',\n 'Int16Array',\n 'Uint16Array',\n 'Int32Array',\n 'Uint32Array',\n 'Float32Array',\n 'Float64Array',\n 'BigInt64Array',\n 'BigUint64Array',\n 'Tagged'\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 (typeOf === 'string' || typeOf === 'number' || typeOf === 'bigint' || typeOf === 'symbol') {\n return typeOf\n }\n /* c8 ignore next 3 */\n if (typeOf === 'function') {\n return 'Function'\n }\n if (Array.isArray(value)) {\n return 'Array'\n }\n // Also catches Node.js Buffer which extends Uint8Array\n if (value instanceof Uint8Array) {\n return 'Uint8Array'\n }\n // Fast path for plain objects (most common case after primitives/arrays/bytes)\n if (value.constructor === Object) {\n return 'Object'\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 {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 * Check equality between two Type instances. Safe to use across different\n * copies of the Type class (e.g., when bundlers duplicate the module).\n * (major, name) uniquely identifies a Type; terminal is implied by these.\n * @param {Type} a\n * @param {Type} b\n * @returns {boolean}\n */\n static equals (a, b) {\n return a === b || (a.major === b.major && a.name === b.name)\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 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\n// Threshold for manual UTF-8 encoding vs native methods.\n// Node.js Buffer.from: crossover ~24 chars\n// Browser TextEncoder: crossover ~200 chars\nconst FROM_STRING_THRESHOLD_BUFFER = 24\nconst FROM_STRING_THRESHOLD_TEXTENCODER = 200\n\nexport const fromString = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {string} string\n */\n (string) => {\n return string.length >= FROM_STRING_THRESHOLD_BUFFER\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 >= FROM_STRING_THRESHOLD_TEXTENCODER ? 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 // Buffer.slice() returns a view, not a copy, so we need special handling\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 if ((c >= 0xD800) && (c <= 0xDFFF)) {\n c = 0xFFFD // Unpaired Surrogate\n }\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// 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\n/**\n * U8Bl is a buffer list that writes directly to a user-provided Uint8Array.\n * It provides the same interface as Bl but writes to a fixed destination.\n */\nexport class U8Bl {\n /**\n * @param {Uint8Array} dest\n */\n constructor (dest) {\n this.dest = dest\n /** @type {number} */\n this.cursor = 0\n // chunks is for interface compatibility with Bl - encode.js checks chunks.length\n // as a sanity check for pre-calculated sizes. For U8Bl this is always [dest].\n /** @type {Uint8Array[]} */\n this.chunks = [dest]\n }\n\n reset () {\n this.cursor = 0\n }\n\n /**\n * @param {Uint8Array|number[]} bytes\n */\n push (bytes) {\n if (this.cursor + bytes.length > this.dest.length) {\n throw new Error('write out of bounds, destination buffer is too small')\n }\n this.dest.set(bytes, this.cursor)\n this.cursor += bytes.length\n }\n\n /**\n * @param {boolean} [reset]\n * @returns {Uint8Array}\n */\n toBytes (reset = false) {\n const byts = this.dest.subarray(0, this.cursor)\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('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').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 {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeUint (writer, token) {\n return encodeUintValue(writer, 0, token.value)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {number} major\n * @param {number|bigint} uint\n */\nexport function encodeUintValue (writer, major, uint) {\n if (uint < uintBoundaries[0]) {\n const nuint = Number(uint)\n // pack into one byte, minor=0, additional=value\n writer.push([major | nuint])\n } else if (uint < uintBoundaries[1]) {\n const nuint = Number(uint)\n // pack into two byte, minor=0, additional=24\n writer.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 writer.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 writer.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 writer.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('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').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 {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeNegint (writer, token) {\n const negint = token.value\n const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))\n uint.encodeUintValue(writer, 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 } from './byte-utils.js'\n\n/**\n * @typedef {import('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').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 = data.slice(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 = Type.equals(token.type, Type.string) ? fromString(token.value) : token.value\n }\n // @ts-ignore c'mon\n return token.encodedBytes\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeBytes (writer, token) {\n const bytes = tokenBytes(token)\n uint.encodeUintValue(writer, token.type.majorEncoded, bytes.length)\n writer.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'\n\nconst textDecoder = new TextDecoder()\n\n// Threshold for ASCII fast-path vs TextDecoder. Short ASCII strings (common for\n// map keys) are faster to decode with a simple loop than TextDecoder overhead.\nconst ASCII_THRESHOLD = 32\n\n/**\n * @typedef {import('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').DecodeOptions} DecodeOptions\n */\n\n/**\n * Decode UTF-8 bytes to string. For short ASCII strings (common case for map keys),\n * a simple loop is faster than TextDecoder.\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n * @returns {string}\n */\nfunction toStr (bytes, start, end) {\n const len = end - start\n if (len < ASCII_THRESHOLD) {\n let str = ''\n for (let i = start; i < end; i++) {\n const c = bytes[i]\n if (c & 0x80) { // non-ASCII, fall back to TextDecoder\n return textDecoder.decode(bytes.subarray(start, end))\n }\n str += String.fromCharCode(c)\n }\n return str\n }\n return textDecoder.decode(bytes.subarray(start, end))\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, toStr(data, pos + prefix, pos + totLength), totLength)\n if (options.retainStringBytes === true) {\n tok.byteValue = data.slice(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('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').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 {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeArray (writer, token) {\n uint.encodeUintValue(writer, 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('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').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 {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeMap (writer, token) {\n uint.encodeUintValue(writer, 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('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').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 {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeTag (writer, token) {\n uint.encodeUintValue(writer, 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('../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../interface.js').DecodeOptions} DecodeOptions\n * @typedef {import('../interface.js').EncodeOptions} EncodeOptions\n */\n\nexport const MINOR_FALSE = 20\nexport const MINOR_TRUE = 21\nexport const MINOR_NULL = 22\nexport const 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 {ByteWriter} writer\n * @param {Token} token\n * @param {EncodeOptions} options\n */\nexport function encodeFloat (writer, token, options) {\n const float = token.value\n\n if (float === false) {\n writer.push([Type.float.majorEncoded | MINOR_FALSE])\n } else if (float === true) {\n writer.push([Type.float.majorEncoded | MINOR_TRUE])\n } else if (float === null) {\n writer.push([Type.float.majorEncoded | MINOR_NULL])\n } else if (float === undefined) {\n writer.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 writer.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 writer.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 writer.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 // Use valu32 for sign bit since bitwise ops on floats lose -0 sign\n dataView.setUint16(0, ((valu32 & 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.js').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, U8Bl } from './bl.js'\nimport { encodeErrPrefix } from './common.js'\nimport { quickEncodeToken } from './jump.js'\nimport { asU8A, compare, fromString } from './byte-utils.js'\n\nimport { encodeUint, encodeUintValue } 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, MINOR_FALSE, MINOR_TRUE, MINOR_NULL, MINOR_UNDEFINED } from './7float.js'\n\n/**\n * @typedef {import('../interface.js').EncodeOptions} EncodeOptions\n * @typedef {import('../interface.js').OptionalTypeEncoder} OptionalTypeEncoder\n * @typedef {import('../interface.js').Reference} Reference\n * @typedef {import('../interface.js').StrictTypeEncoder} StrictTypeEncoder\n * @typedef {import('../interface.js').TokenTypeEncoder} TokenTypeEncoder\n * @typedef {import('../interface.js').TokenOrNestedTokens} TokenOrNestedTokens\n * @typedef {import('../interface.js').ByteWriter} ByteWriter\n */\n\n/** @type {EncodeOptions} */\nconst defaultEncodeOptions = {\n float64: false,\n mapSorter,\n quickEncodeToken\n}\n\n/** @type {EncodeOptions} */\nexport const rfc8949EncodeOptions = Object.freeze({\n float64: true,\n mapSorter: rfc8949MapSorter,\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 defaultWriter = 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 maxLength = isMap ? obj.size : keys.length\n\n /** @type {undefined | [TokenOrNestedTokens, TokenOrNestedTokens][]} */\n let entries\n\n if (maxLength) {\n // Pre-allocate the array with the expected size\n entries = new Array(maxLength)\n refStack = Ref.createCheck(refStack, obj)\n const skipUndefined = !isMap && options.ignoreUndefinedProperties\n\n let i = 0\n for (const key of keys) {\n const value = isMap ? obj.get(key) : obj[key]\n if (skipUndefined && value === undefined) {\n continue\n }\n entries[i++] = [\n objectToTokens(key, options, refStack),\n objectToTokens(value, options, refStack)\n ]\n }\n\n // Truncate only if properties were skipped\n if (i < maxLength) {\n entries.length = i\n }\n }\n\n if (!entries?.length) {\n if (options.addBreakTokens === true) {\n return [simpleTokens.emptyMap, new Token(Type.break)]\n }\n return simpleTokens.emptyMap\n }\n\n sortMapEntries(entries, options)\n if (options.addBreakTokens) {\n return [new Token(Type.map, entries.length), entries, new Token(Type.break)]\n }\n return [new Token(Type.map, entries.length), entries]\n },\n\n /**\n * Encode a `Tagged` wrapper as a CBOR tag header followed by the encoded\n * form of the wrapped value. The value is recursively tokenised through\n * `objectToTokens()` so any registered `typeEncoders` apply to it.\n *\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} options\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\n Tagged (obj, _typ, options, refStack) {\n return [\n new Token(Type.tag, obj.tag),\n objectToTokens(obj.value, options, refStack)\n ]\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 * @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 * @typedef {Token & { _keyBytes?: Uint8Array }} TokenEx\n *\n * @param {(Token|Token[])[]} e1\n * @param {(Token|Token[])[]} e2\n * @returns {number}\n */\nfunction rfc8949MapSorter (e1, e2) {\n if (e1[0] instanceof Token && e2[0] instanceof Token) {\n const t1 = /** @type {TokenEx} */ (e1[0])\n const t2 = /** @type {TokenEx} */ (e2[0])\n\n if (!t1._keyBytes) {\n t1._keyBytes = encodeRfc8949(t1.value)\n }\n\n if (!t2._keyBytes) {\n t2._keyBytes = encodeRfc8949(t2.value)\n }\n\n return compare(t1._keyBytes, t2._keyBytes)\n }\n\n throw new Error('rfc8949MapSorter: complex key types are not supported yet')\n}\n\n/**\n * @param {any} data\n * @returns {Uint8Array}\n */\nfunction encodeRfc8949 (data) {\n return encodeCustom(data, cborEncoders, rfc8949EncodeOptions)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {TokenOrNestedTokens} tokens\n * @param {TokenTypeEncoder[]} encoders\n * @param {EncodeOptions} options\n */\nfunction tokensToEncoded (writer, tokens, encoders, options) {\n if (Array.isArray(tokens)) {\n for (const token of tokens) {\n tokensToEncoded(writer, token, encoders, options)\n }\n } else {\n encoders[tokens.type.major](writer, tokens, options)\n }\n}\n\n// CBOR major type prefixes, cached from Type for hot path performance\nconst MAJOR_UINT = Type.uint.majorEncoded\nconst MAJOR_NEGINT = Type.negint.majorEncoded\nconst MAJOR_BYTES = Type.bytes.majorEncoded\nconst MAJOR_STRING = Type.string.majorEncoded\nconst MAJOR_ARRAY = Type.array.majorEncoded\n\n// Simple value bytes (CBOR major type 7 + minor value)\nconst SIMPLE_FALSE = Type.float.majorEncoded | MINOR_FALSE\nconst SIMPLE_TRUE = Type.float.majorEncoded | MINOR_TRUE\nconst SIMPLE_NULL = Type.float.majorEncoded | MINOR_NULL\nconst SIMPLE_UNDEFINED = Type.float.majorEncoded | MINOR_UNDEFINED\n\nconst neg1b = BigInt(-1)\nconst pos1b = BigInt(1)\n\n/**\n * Check if direct encoding can be used for the given options.\n * Direct encoding bypasses token creation for most values.\n * @param {EncodeOptions} options\n * @returns {boolean}\n */\nfunction canDirectEncode (options) {\n // Cannot use direct encode with addBreakTokens (needs special break token handling).\n // Direct encode checks typeEncoders per-value, falling back to tokens as needed.\n // Maps fall back to token-based encoding for efficient key sorting.\n return options.addBreakTokens !== true\n}\n\n/**\n * Direct encode a value to the writer, bypassing token creation for most types.\n * Falls back to token-based encoding for custom type encoders.\n * @param {ByteWriter} writer\n * @param {any} data\n * @param {EncodeOptions} options\n * @param {Reference|undefined} refStack\n */\nfunction directEncode (writer, data, options, refStack) {\n const typ = is(data)\n\n // Check for custom encoder for THIS specific type\n const customEncoder = options.typeEncoders && options.typeEncoders[typ]\n if (customEncoder) {\n const tokens = customEncoder(data, typ, options, refStack)\n if (tokens != null) {\n // Custom encoder returned tokens, serialize immediately\n tokensToEncoded(writer, tokens, cborEncoders, options)\n return\n }\n // Custom encoder returned null, fall through to default handling\n }\n\n // Direct encode based on type\n switch (typ) {\n case 'null':\n writer.push([SIMPLE_NULL])\n return\n\n case 'undefined':\n writer.push([SIMPLE_UNDEFINED])\n return\n\n case 'boolean':\n writer.push([data ? SIMPLE_TRUE : SIMPLE_FALSE])\n return\n\n case 'number':\n if (!Number.isInteger(data) || !Number.isSafeInteger(data)) {\n // Float, use token encoder for complex float encoding\n encodeFloat(writer, new Token(Type.float, data), options)\n } else if (data >= 0) {\n encodeUintValue(writer, MAJOR_UINT, data)\n } else {\n // Negative integer\n encodeUintValue(writer, MAJOR_NEGINT, data * -1 - 1)\n }\n return\n\n case 'bigint':\n if (data >= BigInt(0)) {\n encodeUintValue(writer, MAJOR_UINT, data)\n } else {\n encodeUintValue(writer, MAJOR_NEGINT, data * neg1b - pos1b)\n }\n return\n\n case 'string': {\n const bytes = fromString(data)\n encodeUintValue(writer, MAJOR_STRING, bytes.length)\n writer.push(bytes)\n return\n }\n\n case 'Uint8Array':\n encodeUintValue(writer, MAJOR_BYTES, data.length)\n writer.push(data)\n return\n\n case 'Array':\n if (!data.length) {\n writer.push([MAJOR_ARRAY]) // Empty array: 0x80\n return\n }\n refStack = Ref.createCheck(refStack, data)\n encodeUintValue(writer, MAJOR_ARRAY, data.length)\n for (const elem of data) {\n directEncode(writer, elem, options, refStack)\n }\n return\n\n case 'Object':\n case 'Map':\n // Maps require key sorting, use token-based encoding for efficiency\n // (pre-encoding all keys for sorting is expensive)\n {\n const tokens = typeEncoders.Object(data, typ, options, refStack)\n tokensToEncoded(writer, tokens, cborEncoders, options)\n }\n return\n\n default:\n // Fall back to token-based encoding for other types (DataView, TypedArrays, etc.)\n {\n const typeEncoder = typeEncoders[typ]\n if (!typeEncoder) {\n throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)\n }\n const tokens = typeEncoder(data, typ, options, refStack)\n tokensToEncoded(writer, tokens, cborEncoders, options)\n }\n }\n}\n\n/**\n * @param {any} data\n * @param {TokenTypeEncoder[]} encoders\n * @param {EncodeOptions} options\n * @param {Uint8Array} [destination]\n * @returns {Uint8Array}\n */\nfunction encodeCustom (data, encoders, options, destination) {\n // arg ordering is different to encodeInto for backward compatibility\n const hasDest = destination instanceof Uint8Array\n let writeTo = hasDest ? new U8Bl(destination) : defaultWriter\n\n const tokens = objectToTokens(data, options)\n if (!Array.isArray(tokens) && options.quickEncodeToken) {\n const quickBytes = options.quickEncodeToken(tokens)\n if (quickBytes) {\n if (hasDest) {\n // Copy quick bytes into destination buffer\n writeTo.push(quickBytes)\n return writeTo.toBytes()\n }\n return quickBytes\n }\n const encoder = encoders[tokens.type.major]\n if (encoder.encodedSize) {\n const size = encoder.encodedSize(tokens, options)\n if (!hasDest) {\n writeTo = new Bl(size)\n }\n encoder(writeTo, tokens, options)\n /* c8 ignore next 4 */\n // this would be a problem with encodedSize() functions\n if (writeTo.chunks.length !== 1) {\n throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)\n }\n return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0])\n }\n }\n writeTo.reset()\n tokensToEncoded(writeTo, tokens, encoders, options)\n return writeTo.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\n // Use direct encode path when possible\n if (canDirectEncode(options)) {\n defaultWriter.reset()\n directEncode(defaultWriter, data, options, undefined)\n return defaultWriter.toBytes(true)\n }\n\n return encodeCustom(data, cborEncoders, options)\n}\n\n/**\n * @param {any} data\n * @param {Uint8Array} destination\n * @param {EncodeOptions} [options]\n * @returns {{ written: number }}\n */\nfunction encodeInto (data, destination, options) {\n options = Object.assign({}, defaultEncodeOptions, options)\n\n // Use direct encode path when possible\n if (canDirectEncode(options)) {\n const writer = new U8Bl(destination)\n directEncode(writer, data, options, undefined)\n return { written: writer.toBytes().length }\n }\n\n const result = encodeCustom(data, cborEncoders, options, destination)\n return { written: result.length }\n}\n\nexport { objectToTokens, encode, encodeCustom, encodeInto, Ref }\n", "import { decodeErrPrefix } from './common.js'\nimport { Type } from './token.js'\nimport { jump, quick } from './jump.js'\nimport { asU8A } from './byte-utils.js'\n\n/**\n * @typedef {import('./token.js').Token} Token\n * @typedef {import('../interface.js').DecodeOptions} DecodeOptions\n * @typedef {import('../interface.js').DecodeTokenizer} DecodeTokenizer\n * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl\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 rejectDuplicateMapKeys = options.rejectDuplicateMapKeys === 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 && typeof key !== 'string') {\n throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)\n }\n if (rejectDuplicateMapKeys) {\n // @ts-ignore\n if ((useMaps && m.has(key)) || (!useMaps && Object.hasOwn(obj, key))) {\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 * Generator that yields [key, value] entries from a CBOR map token.\n * Used by tag decoders that need to preserve key types (e.g., Tag 259 Map).\n * @param {Token} token - The map token\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {Generator<[any, any], void, unknown>}\n */\nfunction * tokenToMapEntries (token, tokeniser, options) {\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 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 yield [key, value]\n }\n}\n\n/**\n * Creates a TagDecodeControl object for tag decoders.\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {TagDecodeControl}\n */\nfunction createTagDecodeControl (tokeniser, options) {\n let called = false\n\n /**\n * @type {TagDecodeControl}\n */\n const decode = function () {\n if (called) {\n throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)\n }\n called = true\n const value = tokensToObject(tokeniser, options)\n if (value === DONE) {\n throw new Error(`${decodeErrPrefix} tag content missing`)\n }\n if (value === BREAK) {\n throw new Error(`${decodeErrPrefix} got unexpected break in tag content`)\n }\n return value\n }\n\n decode.entries = function () {\n if (called) {\n throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)\n }\n called = true\n\n // Get the next token and ensure it's a map\n const token = tokeniser.next()\n if (!Type.equals(token.type, Type.map)) {\n throw new Error(`${decodeErrPrefix} entries() requires map content, got ${token.type.name}`)\n }\n\n // Collect all entries into an array (ensures full content consumption)\n const entries = []\n for (const entry of tokenToMapEntries(token, tokeniser, options)) {\n entries.push(entry)\n }\n return entries\n }\n\n // For internal tracking\n Object.defineProperty(decode, '_called', {\n get () { return called },\n enumerable: false\n })\n\n return decode\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 (Type.equals(token.type, Type.break)) {\n return BREAK\n }\n\n if (token.type.terminal) {\n return token.value\n }\n\n if (Type.equals(token.type, Type.array)) {\n return tokenToArray(token, tokeniser, options)\n }\n\n if (Type.equals(token.type, Type.map)) {\n return tokenToMap(token, tokeniser, options)\n }\n\n if (Type.equals(token.type, Type.tag)) {\n if (options.tags && typeof options.tags[token.value] === 'function') {\n const decodeControl = createTagDecodeControl(tokeniser, options)\n const result = options.tags[token.value](decodeControl)\n if (!decodeControl._called) {\n throw new Error(`${decodeErrPrefix} tag decoder must call decode() or entries()`)\n }\n return result\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 // Convert Buffer to plain Uint8Array for faster slicing in decode path\n const u8aData = asU8A(data)\n const tokeniser = options.tokenizer || new Tokeniser(u8aData, 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", "/**\n * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl\n * @typedef {(decode: TagDecodeControl) => Tagged} TaggedTagDecoder\n */\n\n/**\n * A wrapper class for representing a CBOR tag with an arbitrary nested value.\n *\n * `Tagged` is a symmetric primitive: it can be passed to `encode()` to emit\n * a CBOR tag header followed by the encoded form of `value`, and it can be\n * returned from a tag decoder (via `Tagged.decoder(tag)` or `Tagged.preserve()`)\n * to round-trip a tag through decode without losing the tag number.\n *\n * Use `Tagged` for one-off tag handling where defining a dedicated\n * `typeEncoders` entry and tag decoder pair would be heavyweight, e.g. when\n * wrapping a structure in a single application-specific tag (COSE, dCBOR\n * envelopes, etc.).\n *\n * For systematic mapping of a JS type to a tag (e.g. CID -> tag 42), prefer\n * a dedicated `typeEncoders` entry instead.\n */\nexport class Tagged {\n /**\n * @param {number} tag - CBOR tag number, a non-negative integer\n * @param {any} value - The value to be tagged; encoded recursively\n */\n constructor (tag, value) {\n if (typeof tag !== 'number' || !Number.isInteger(tag) || tag < 0) {\n throw new TypeError('Tagged: tag must be a non-negative integer')\n }\n this.tag = tag\n this.value = value\n }\n\n /**\n * Build a tag decoder for use in `decode()`'s `tags` option that returns the\n * decoded content wrapped in a `Tagged` instance, preserving the tag number\n * for the caller to inspect.\n *\n * @param {number} tag - The CBOR tag number this decoder will be registered for\n * @returns {TaggedTagDecoder}\n *\n * @example\n * import { decode, Tagged } from 'cborg'\n * const value = decode(bytes, { tags: { 16: Tagged.decoder(16) } })\n * // value instanceof Tagged; value.tag === 16\n */\n static decoder (tag) {\n return (decode) => new Tagged(tag, decode())\n }\n\n /**\n * Build a `tags` option for `decode()` that wraps each listed tag number in\n * a `Tagged` instance, preserving those tags through decode without\n * registering a dedicated decoder per tag.\n *\n * @param {...number} tagNumbers - One or more CBOR tag numbers to preserve\n * @returns {{[tagNumber: number]: TaggedTagDecoder}}\n *\n * @example\n * import { decode, Tagged } from 'cborg'\n * const value = decode(bytes, { tags: Tagged.preserve(16, 96) })\n */\n static preserve (...tagNumbers) {\n /** @type {{[tagNumber: number]: TaggedTagDecoder}} */\n const tags = {}\n for (const tag of tagNumbers) {\n tags[tag] = Tagged.decoder(tag)\n }\n return tags\n }\n}\n\n// Symbol.toStringTag so the internal `is()` type detection returns 'Tagged'\n// for instances, allowing the default Tagged typeEncoder to match.\nObject.defineProperty(Tagged.prototype, Symbol.toStringTag, {\n value: 'Tagged'\n})\n", "export class AlreadyPinnedError extends Error {\n static name = 'AlreadyPinnedError'\n name = 'AlreadyPinnedError'\n}\n\nexport class BlockPinnedError extends Error {\n static name = 'BlockPinnedError'\n name = 'BlockPinnedError'\n}\n\nexport class InvalidDatastoreVersionError extends Error {\n static name = 'InvalidDatastoreVersionError'\n name = 'InvalidDatastoreVersionError'\n}\n\nexport class InvalidConfigurationError extends Error {\n static name = 'InvalidConfigurationError'\n name = 'InvalidConfigurationError'\n}\n\nexport class GetFailedError extends AggregateError {\n static name = 'GetFailedError'\n name = 'GetFailedError'\n}\n\nexport class LoadBlockFailedError extends AggregateError {\n static name = 'LoadBlockFailedError'\n name = 'LoadBlockFailedError'\n}\n\nexport class BlockNotFoundWhileOfflineError extends Error {\n static name = 'BlockNotFoundWhileOfflineError'\n name = 'BlockNotFoundWhileOfflineError'\n}\n\nexport class DecryptionFailedError extends Error {\n static name = 'DecryptionFailedError'\n name = 'DecryptionFailedError'\n}\n", "// FNV_PRIMES and FNV_OFFSETS from\n// http://www.isthe.com/chongo/tech/comp/fnv/index.html#FNV-param\n\nconst FNV_PRIMES = {\n\t32: 16_777_619n,\n\t64: 1_099_511_628_211n,\n\t128: 309_485_009_821_345_068_724_781_371n,\n\t256: 374_144_419_156_711_147_060_143_317_175_368_453_031_918_731_002_211n,\n\t512: 35_835_915_874_844_867_368_919_076_489_095_108_449_946_327_955_754_392_558_399_825_615_420_669_938_882_575_126_094_039_892_345_713_852_759n,\n\t1024: 5_016_456_510_113_118_655_434_598_811_035_278_955_030_765_345_404_790_744_303_017_523_831_112_055_108_147_451_509_157_692_220_295_382_716_162_651_878_526_895_249_385_292_291_816_524_375_083_746_691_371_804_094_271_873_160_484_737_966_720_260_389_217_684_476_157_468_082_573n,\n};\n\nconst FNV_OFFSETS = {\n\t32: 2_166_136_261n,\n\t64: 14_695_981_039_346_656_037n,\n\t128: 144_066_263_297_769_815_596_495_629_667_062_367_629n,\n\t256: 100_029_257_958_052_580_907_070_968_620_625_704_837_092_796_014_241_193_945_225_284_501_741_471_925_557n,\n\t512: 9_659_303_129_496_669_498_009_435_400_716_310_466_090_418_745_672_637_896_108_374_329_434_462_657_994_582_932_197_716_438_449_813_051_892_206_539_805_784_495_328_239_340_083_876_191_928_701_583_869_517_785n,\n\t1024: 14_197_795_064_947_621_068_722_070_641_403_218_320_880_622_795_441_933_960_878_474_914_617_582_723_252_296_732_303_717_722_150_864_096_521_202_355_549_365_628_174_669_108_571_814_760_471_015_076_148_029_755_969_804_077_320_157_692_458_563_003_215_304_957_150_157_403_644_460_363_550_505_412_711_285_966_361_610_267_868_082_893_823_963_790_439_336_411_086_884_584_107_735_010_676_915n,\n};\n\nconst cachedEncoder = new globalThis.TextEncoder();\n\nfunction fnv1aUint8Array(uint8Array, size) {\n\tconst fnvPrime = FNV_PRIMES[size];\n\tlet hash = FNV_OFFSETS[size];\n\n\t// eslint-disable-next-line unicorn/no-for-loop -- This is a performance-sensitive loop\n\tfor (let index = 0; index < uint8Array.length; index++) {\n\t\thash ^= BigInt(uint8Array[index]);\n\t\thash = BigInt.asUintN(size, hash * fnvPrime);\n\t}\n\n\treturn hash;\n}\n\nfunction fnv1aEncodeInto(string, size, utf8Buffer) {\n\tif (utf8Buffer.length === 0) {\n\t\tthrow new Error('The `utf8Buffer` option must have a length greater than zero');\n\t}\n\n\tconst fnvPrime = FNV_PRIMES[size];\n\tlet hash = FNV_OFFSETS[size];\n\tlet remaining = string;\n\n\twhile (remaining.length > 0) {\n\t\tconst result = cachedEncoder.encodeInto(remaining, utf8Buffer);\n\t\tremaining = remaining.slice(result.read);\n\t\tfor (let index = 0; index < result.written; index++) {\n\t\t\thash ^= BigInt(utf8Buffer[index]);\n\t\t\thash = BigInt.asUintN(size, hash * fnvPrime);\n\t\t}\n\t}\n\n\treturn hash;\n}\n\nexport default function fnv1a(value, {size = 32, utf8Buffer} = {}) {\n\tif (!FNV_PRIMES[size]) {\n\t\tthrow new Error('The `size` option must be one of 32, 64, 128, 256, 512, or 1024');\n\t}\n\n\tif (typeof value === 'string') {\n\t\tif (utf8Buffer) {\n\t\t\treturn fnv1aEncodeInto(value, size, utf8Buffer);\n\t\t}\n\n\t\tvalue = cachedEncoder.encode(value);\n\t}\n\n\treturn fnv1aUint8Array(value, size);\n}\n", "import fnv1aHash from '@sindresorhus/fnv1a'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\nexport interface Hash {\n hash(input: Uint8Array, seed: number): number\n hashV(input: Uint8Array, seed: number): Uint8Array\n}\n\nexport const fnv1a: Hash = {\n hash: (input) => {\n return Number(fnv1aHash(input, {\n size: 32\n }))\n },\n hashV: (input, seed) => {\n return numberToBuffer(fnv1a.hash(input, seed))\n }\n}\n\nexport function numberToBuffer (num: bigint | number): Uint8Array {\n let hex = num.toString(16)\n\n if (hex.length % 2 === 1) {\n hex = `0${hex}`\n }\n\n return uint8ArrayFromString(hex, 'base16')\n}\n", "import { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport type { Hash } from './hashes.ts'\n\nexport const MAX_FINGERPRINT_SIZE = 64\n\nexport class Fingerprint {\n private readonly fp: Uint8Array\n private readonly h: Hash\n private readonly seed: number\n\n constructor (buf: Uint8Array, hash: Hash, seed: number, fingerprintSize: number = 2) {\n if (fingerprintSize > MAX_FINGERPRINT_SIZE) {\n throw new TypeError('Invalid Fingerprint Size')\n }\n\n const fnv = hash.hashV(buf, seed)\n const fp = uint8ArrayAlloc(fingerprintSize)\n\n for (let i = 0; i < fp.length; i++) {\n fp[i] = fnv[i]\n }\n\n if (fp.length === 0) {\n fp[0] = 7\n }\n\n this.fp = fp\n this.h = hash\n this.seed = seed\n }\n\n hash (): number {\n return this.h.hash(this.fp, this.seed)\n }\n\n equals (other?: any): boolean {\n if (!(other?.fp instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.fp, other.fp)\n }\n}\n", "export function getRandomInt (min: number, max: number): number {\n return Math.floor(Math.random() * (max - min)) + min\n}\n", "import { Fingerprint } from './fingerprint.ts'\nimport { getRandomInt } from './utils.ts'\n\nexport class Bucket {\n private readonly contents: Array<Fingerprint | null>\n\n constructor (size: number) {\n this.contents = new Array(size).fill(null)\n }\n\n has (fingerprint: Fingerprint): boolean {\n if (!(fingerprint instanceof Fingerprint)) {\n throw new TypeError('Invalid Fingerprint')\n }\n\n return this.contents.some((fp) => {\n return fingerprint.equals(fp)\n })\n }\n\n add (fingerprint: Fingerprint): boolean {\n if (!(fingerprint instanceof Fingerprint)) {\n throw new TypeError('Invalid Fingerprint')\n }\n\n for (let i = 0; i < this.contents.length; i++) {\n if (this.contents[i] == null) {\n this.contents[i] = fingerprint\n return true\n }\n }\n\n return true\n }\n\n swap (fingerprint: Fingerprint): Fingerprint | null {\n if (!(fingerprint instanceof Fingerprint)) {\n throw new TypeError('Invalid Fingerprint')\n }\n\n const i = getRandomInt(0, this.contents.length - 1)\n const current = this.contents[i]\n this.contents[i] = fingerprint\n\n return current\n }\n\n remove (fingerprint: Fingerprint): boolean {\n if (!(fingerprint instanceof Fingerprint)) {\n throw new TypeError('Invalid Fingerprint')\n }\n\n const found = this.contents.findIndex((fp) => {\n return fingerprint.equals(fp)\n })\n\n if (found > -1) {\n this.contents[found] = null\n return true\n } else {\n return false\n }\n }\n}\n", "import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { Bucket } from './bucket.ts'\nimport { Fingerprint, MAX_FINGERPRINT_SIZE } from './fingerprint.ts'\nimport { fnv1a } from './hashes.ts'\nimport { getRandomInt } from './utils.ts'\nimport type { Hash } from './hashes.ts'\nimport type { Filter } from './index.ts'\n\nconst maxCuckooCount = 500\n\nexport interface CuckooFilterInit {\n /**\n * How many items the filter is expected to contain\n */\n filterSize: number\n\n /**\n * How many items to put in each bucket\n */\n bucketSize?: number\n\n /**\n * How many bytes the fingerprint is expected to be\n */\n fingerprintSize?: number\n\n /**\n * A non-cryptographic hash implementation\n */\n hash?: Hash\n\n /**\n * A number used to seed the hash\n */\n seed?: number\n}\n\nexport class CuckooFilter implements Filter {\n private readonly bucketSize: number\n private readonly filterSize: number\n private readonly fingerprintSize: number\n private readonly buckets: Bucket[]\n public count: number\n private readonly hash: Hash\n private readonly seed: number\n\n constructor (init: CuckooFilterInit) {\n this.filterSize = init.filterSize\n this.bucketSize = init.bucketSize ?? 4\n this.fingerprintSize = init.fingerprintSize ?? 2\n this.count = 0\n this.buckets = []\n this.hash = init.hash ?? fnv1a\n this.seed = init.seed ?? getRandomInt(0, Math.pow(2, 10))\n }\n\n add (item: Uint8Array | string): boolean {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item)\n }\n\n const fingerprint = new Fingerprint(item, this.hash, this.seed, this.fingerprintSize)\n const j = this.hash.hash(item, this.seed) % this.filterSize\n const k = (j ^ fingerprint.hash()) % this.filterSize\n\n if (this.buckets[j] == null) {\n this.buckets[j] = new Bucket(this.bucketSize)\n }\n\n if (this.buckets[k] == null) {\n this.buckets[k] = new Bucket(this.bucketSize)\n }\n\n if (this.buckets[j].add(fingerprint) || this.buckets[k].add(fingerprint)) {\n this.count++\n return true\n }\n\n const rand = [j, k]\n let i = rand[getRandomInt(0, rand.length - 1)]\n\n if (this.buckets[i] == null) {\n this.buckets[i] = new Bucket(this.bucketSize)\n }\n\n for (let n = 0; n < maxCuckooCount; n++) {\n const swapped = this.buckets[i].swap(fingerprint)\n\n if (swapped == null) {\n continue\n }\n\n i = (i ^ swapped.hash()) % this.filterSize\n\n if (this.buckets[i] == null) {\n this.buckets[i] = new Bucket(this.bucketSize)\n }\n\n if (this.buckets[i].add(swapped)) {\n this.count++\n\n return true\n } else {\n continue\n }\n }\n\n return false\n }\n\n has (item: Uint8Array | string): boolean {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item)\n }\n\n const fingerprint = new Fingerprint(item, this.hash, this.seed, this.fingerprintSize)\n const j = this.hash.hash(item, this.seed) % this.filterSize\n const inJ = this.buckets[j]?.has(fingerprint) ?? false\n\n if (inJ) {\n return inJ\n }\n\n const k = (j ^ fingerprint.hash()) % this.filterSize\n\n return this.buckets[k]?.has(fingerprint) ?? false\n }\n\n remove (item: Uint8Array | string): boolean {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item)\n }\n\n const fingerprint = new Fingerprint(item, this.hash, this.seed, this.fingerprintSize)\n const j = this.hash.hash(item, this.seed) % this.filterSize\n const inJ = this.buckets[j]?.remove(fingerprint) ?? false\n\n if (inJ) {\n this.count--\n return inJ\n }\n\n const k = (j ^ fingerprint.hash()) % this.filterSize\n const inK = this.buckets[k]?.remove(fingerprint) ?? false\n\n if (inK) {\n this.count--\n }\n\n return inK\n }\n\n get reliable (): boolean {\n return Math.floor(100 * (this.count / this.filterSize)) <= 90\n }\n}\n\n// max load constants, defined in the cuckoo paper\nconst MAX_LOAD = {\n 1: 0.5,\n 2: 0.84,\n 4: 0.95,\n 8: 0.98\n}\n\nfunction calculateBucketSize (errorRate: number = 0.001): 2 | 4 | 8 {\n if (errorRate > 0.002) {\n return 2\n }\n\n if (errorRate > 0.00001) {\n return 4\n }\n\n return 8\n}\n\nexport function optimize (maxItems: number, errorRate: number = 0.001): CuckooFilterInit {\n // https://www.eecs.harvard.edu/~michaelm/postscripts/cuckoo-conext2014.pdf\n // Section 5.1 Optimal Bucket Size\n const bucketSize = calculateBucketSize(errorRate)\n const load = MAX_LOAD[bucketSize]\n\n // https://stackoverflow.com/questions/57555236/how-to-size-a-cuckoo-filter/57617208#57617208\n const filterSize = Math.round(maxItems / load)\n const fingerprintSize = Math.min(Math.ceil(Math.log2(1 / errorRate) + Math.log2(2 * bucketSize)), MAX_FINGERPRINT_SIZE)\n\n return {\n filterSize,\n bucketSize,\n fingerprintSize\n }\n}\n\nexport function createCuckooFilter (maxItems: number, errorRate: number = 0.005): Filter {\n const opts = optimize(maxItems, errorRate)\n return new CuckooFilter(opts)\n}\n", "import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { CuckooFilter, optimize } from './cuckoo-filter.ts'\nimport { fnv1a } from './hashes.ts'\nimport { getRandomInt } from './utils.ts'\nimport type { CuckooFilterInit } from './cuckoo-filter.ts'\nimport type { Hash } from './hashes.ts'\nimport type { Filter } from './index.ts'\n\nexport interface ScalableCuckooFilterInit extends CuckooFilterInit {\n /**\n * A number to multiply maxItems by when adding new sub-filters\n */\n scale?: number\n}\n\nexport class ScalableCuckooFilter implements Filter {\n private readonly filterSize: number\n private readonly bucketSize: number\n private readonly fingerprintSize: number\n private readonly scale: number\n private readonly filterSeries: CuckooFilter[]\n private readonly hash: Hash\n private readonly seed: number\n\n constructor (init: ScalableCuckooFilterInit) {\n this.bucketSize = init.bucketSize ?? 4\n this.filterSize = init.filterSize ?? (1 << 18) / this.bucketSize\n this.fingerprintSize = init.fingerprintSize ?? 2\n this.scale = init.scale ?? 2\n this.hash = init.hash ?? fnv1a\n this.seed = init.seed ?? getRandomInt(0, Math.pow(2, 10))\n this.filterSeries = [\n new CuckooFilter({\n filterSize: this.filterSize,\n bucketSize: this.bucketSize,\n fingerprintSize: this.fingerprintSize,\n hash: this.hash,\n seed: this.seed\n })\n ]\n }\n\n add (item: Uint8Array | string): boolean {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item)\n }\n\n if (this.has(item)) {\n return true\n }\n\n let current = this.filterSeries.find((cuckoo) => {\n return cuckoo.reliable\n })\n\n if (current == null) {\n const curSize = this.filterSize * Math.pow(this.scale, this.filterSeries.length)\n\n current = new CuckooFilter({\n filterSize: curSize,\n bucketSize: this.bucketSize,\n fingerprintSize: this.fingerprintSize,\n hash: this.hash,\n seed: this.seed\n })\n\n this.filterSeries.push(current)\n }\n\n return current.add(item)\n }\n\n has (item: Uint8Array | string): boolean {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item)\n }\n\n for (let i = 0; i < this.filterSeries.length; i++) {\n if (this.filterSeries[i].has(item)) {\n return true\n }\n }\n\n return false\n }\n\n remove (item: Uint8Array | string): boolean {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item)\n }\n\n for (let i = 0; i < this.filterSeries.length; i++) {\n if (this.filterSeries[i].remove(item)) {\n return true\n }\n }\n\n return false\n }\n\n get count (): number {\n return this.filterSeries.reduce((acc, curr) => {\n return acc + curr.count\n }, 0)\n }\n}\n\nexport function createScalableCuckooFilter (maxItems: number, errorRate: number = 0.001, options?: Pick<ScalableCuckooFilterInit, 'hash' | 'seed' | 'scale'>): Filter {\n return new ScalableCuckooFilter({\n ...optimize(maxItems, errorRate),\n ...(options ?? {})\n })\n}\n", "import pTimeout from 'p-timeout';\n\nconst normalizeEmitter = emitter => {\n\tconst addListener = emitter.addEventListener || emitter.on || emitter.addListener;\n\tconst removeListener = emitter.removeEventListener || emitter.off || emitter.removeListener;\n\n\tif (!addListener || !removeListener) {\n\t\tthrow new TypeError('Emitter is not compatible');\n\t}\n\n\treturn {\n\t\taddListener: addListener.bind(emitter),\n\t\tremoveListener: removeListener.bind(emitter),\n\t};\n};\n\nexport function pEventMultiple(emitter, event, options) {\n\tlet cancel;\n\tconst returnValue = new Promise((resolve, reject) => {\n\t\toptions = {\n\t\t\trejectionEvents: ['error'],\n\t\t\tmultiArgs: false,\n\t\t\trejectionMultiArgs: false,\n\t\t\tresolveImmediately: false,\n\t\t\t...options,\n\t\t};\n\n\t\tif (!(options.count >= 0 && (options.count === Number.POSITIVE_INFINITY || Number.isInteger(options.count)))) {\n\t\t\tthrow new TypeError('The `count` option should be at least 0 or more');\n\t\t}\n\n\t\toptions.signal?.throwIfAborted();\n\n\t\t// Allow multiple events\n\t\tconst events = [event].flat();\n\n\t\tconst items = [];\n\t\tconst {addListener, removeListener} = normalizeEmitter(emitter);\n\n\t\tconst onItem = async (...arguments_) => {\n\t\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\t\tif (options.filter) {\n\t\t\t\ttry {\n\t\t\t\t\tif (!(await options.filter(value))) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tcancel();\n\t\t\t\t\treject(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\titems.push(value);\n\n\t\t\tif (options.count === items.length) {\n\t\t\t\tcancel();\n\t\t\t\tresolve(items);\n\t\t\t}\n\t\t};\n\n\t\tconst rejectHandler = (...arguments_) => {\n\t\t\tcancel();\n\t\t\treject(options.rejectionMultiArgs ? arguments_ : arguments_[0]);\n\t\t};\n\n\t\tcancel = () => {\n\t\t\tfor (const event of events) {\n\t\t\t\tremoveListener(event, onItem);\n\t\t\t}\n\n\t\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\t\t// Only remove rejection handler if we actually registered it\n\t\t\t\tif (!events.includes(rejectionEvent)) {\n\t\t\t\t\tremoveListener(rejectionEvent, rejectHandler);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tfor (const event of events) {\n\t\t\taddListener(event, onItem);\n\t\t}\n\n\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\t// Skip registering rejection handler if we're already listening to this event\n\t\t\t// as the main event takes priority (as documented)\n\t\t\tif (!events.includes(rejectionEvent)) {\n\t\t\t\taddListener(rejectionEvent, rejectHandler);\n\t\t\t}\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\toptions.signal.addEventListener('abort', () => {\n\t\t\t\trejectHandler(options.signal.reason);\n\t\t\t}, {once: true});\n\t\t}\n\n\t\tif (options.resolveImmediately) {\n\t\t\tresolve(items);\n\t\t}\n\t});\n\n\treturnValue.cancel = cancel;\n\n\tif (typeof options.timeout === 'number') {\n\t\tconst timeout = pTimeout(returnValue, {milliseconds: options.timeout});\n\t\t// When cancelling, also clear the timeout timer\n\t\ttimeout.cancel = () => {\n\t\t\tcancel();\n\t\t\ttimeout.clear();\n\t\t};\n\n\t\treturn timeout;\n\t}\n\n\treturn returnValue;\n}\n\nexport function pEvent(emitter, event, options) {\n\tif (typeof options === 'function') {\n\t\toptions = {filter: options};\n\t}\n\n\toptions = {\n\t\t...options,\n\t\tcount: 1,\n\t\tresolveImmediately: false,\n\t};\n\n\tconst arrayPromise = pEventMultiple(emitter, event, options);\n\tconst promise = arrayPromise.then(array => array[0]); // eslint-disable-line promise/prefer-await-to-then\n\tpromise.cancel = arrayPromise.cancel;\n\n\treturn promise;\n}\n\nexport function pEventIterator(emitter, event, options) {\n\tif (typeof options === 'function') {\n\t\toptions = {filter: options};\n\t}\n\n\t// Allow multiple events\n\tconst events = [event].flat();\n\n\toptions = {\n\t\trejectionEvents: ['error'],\n\t\tresolutionEvents: [],\n\t\tlimit: Number.POSITIVE_INFINITY,\n\t\tmultiArgs: false,\n\t\trejectionMultiArgs: false,\n\t\t...options,\n\t};\n\n\tconst {limit} = options;\n\tconst isValidLimit = limit >= 0 && (limit === Number.POSITIVE_INFINITY || Number.isInteger(limit));\n\tif (!isValidLimit) {\n\t\tthrow new TypeError('The `limit` option should be a non-negative integer or Infinity');\n\t}\n\n\toptions.signal?.throwIfAborted();\n\n\tif (limit === 0) {\n\t\t// Return an empty async iterator to avoid any further cost\n\t\treturn {\n\t\t\t[Symbol.asyncIterator]() {\n\t\t\t\treturn this;\n\t\t\t},\n\t\t\tasync next() {\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: undefined,\n\t\t\t\t};\n\t\t\t},\n\t\t};\n\t}\n\n\tconst {addListener, removeListener} = normalizeEmitter(emitter);\n\n\tlet isDone = false;\n\tlet error;\n\tlet hasPendingError = false;\n\tconst nextQueue = [];\n\tconst valueQueue = [];\n\tlet eventCount = 0;\n\tlet isLimitReached = false;\n\n\tconst valueHandler = (...arguments_) => {\n\t\teventCount++;\n\t\tisLimitReached = eventCount === limit;\n\n\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\n\t\t\tresolve({done: false, value});\n\n\t\t\tif (isLimitReached) {\n\t\t\t\tcancel();\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tvalueQueue.push(value);\n\n\t\tif (isLimitReached) {\n\t\t\tcancel();\n\t\t}\n\t};\n\n\tconst cancel = () => {\n\t\tisDone = true;\n\n\t\tfor (const event of events) {\n\t\t\tremoveListener(event, valueHandler);\n\t\t}\n\n\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\tremoveListener(rejectionEvent, rejectHandler);\n\t\t}\n\n\t\tfor (const resolutionEvent of options.resolutionEvents) {\n\t\t\tremoveListener(resolutionEvent, resolveHandler);\n\t\t}\n\n\t\twhile (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\t\t\tresolve({done: true, value: undefined});\n\t\t}\n\t};\n\n\tconst rejectHandler = (...arguments_) => {\n\t\terror = options.rejectionMultiArgs ? arguments_ : arguments_[0];\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {reject} = nextQueue.shift();\n\t\t\treject(error);\n\t\t} else {\n\t\t\thasPendingError = true;\n\t\t}\n\n\t\tcancel();\n\t};\n\n\tconst resolveHandler = async (...arguments_) => {\n\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\tif (options.filter) {\n\t\t\ttry {\n\t\t\t\tif (!(await options.filter(value))) {\n\t\t\t\t\tcancel();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} catch (filterError) {\n\t\t\t\tcancel();\n\t\t\t\tif (nextQueue.length > 0) {\n\t\t\t\t\tconst {reject} = nextQueue.shift();\n\t\t\t\t\treject(filterError);\n\t\t\t\t} else {\n\t\t\t\t\t// Store error for next iterator call\n\t\t\t\t\thasPendingError = true;\n\t\t\t\t\terror = filterError;\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\t\t\tresolve({done: true, value});\n\t\t} else {\n\t\t\tvalueQueue.push(value);\n\t\t}\n\n\t\tcancel();\n\t};\n\n\tfor (const event of events) {\n\t\taddListener(event, valueHandler);\n\t}\n\n\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\taddListener(rejectionEvent, rejectHandler);\n\t}\n\n\tfor (const resolutionEvent of options.resolutionEvents) {\n\t\taddListener(resolutionEvent, resolveHandler);\n\t}\n\n\tif (options.signal) {\n\t\toptions.signal.addEventListener('abort', () => {\n\t\t\trejectHandler(options.signal.reason);\n\t\t}, {once: true});\n\t}\n\n\treturn {\n\t\t[Symbol.asyncIterator]() {\n\t\t\treturn this;\n\t\t},\n\t\tasync next() {\n\t\t\tif (valueQueue.length > 0) {\n\t\t\t\tconst value = valueQueue.shift();\n\t\t\t\treturn {\n\t\t\t\t\tdone: isDone && valueQueue.length === 0 && !isLimitReached,\n\t\t\t\t\tvalue,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (hasPendingError) {\n\t\t\t\thasPendingError = false;\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tif (isDone) {\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: undefined,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tnextQueue.push({resolve, reject});\n\t\t\t});\n\t\t},\n\t\tasync return(value) {\n\t\t\tcancel();\n\t\t\treturn {\n\t\t\t\tdone: isDone,\n\t\t\t\tvalue,\n\t\t\t};\n\t\t},\n\t};\n}\n\nexport {TimeoutError} from 'p-timeout';\n", "import type { Startable } from '@libp2p/interface'\n\nexport interface DebouncedFunction extends Startable {\n (): void\n}\n\n/**\n * Returns a function wrapper that will only call the passed function once\n *\n * Important - the passed function should not throw or reject\n */\nexport function debounce (func: () => void | Promise<void>, wait: number): DebouncedFunction {\n let timeout: ReturnType<typeof setTimeout> | undefined\n\n const output = function (): void {\n const later = function (): void {\n timeout = undefined\n void func()\n }\n\n clearTimeout(timeout)\n timeout = setTimeout(later, wait)\n }\n output.start = (): void => {}\n output.stop = (): void => {\n clearTimeout(timeout)\n }\n\n return output\n}\n", "import type { RateLimiterResult } from './rate-limiter.ts'\n\n/**\n * A rate limit was hit\n */\nexport class RateLimitError extends Error {\n remainingPoints: number\n msBeforeNext: number\n consumedPoints: number\n isFirstInDuration: boolean\n\n constructor (message = 'Rate limit exceeded', props: RateLimiterResult) {\n super(message)\n this.name = 'RateLimitError'\n this.remainingPoints = props.remainingPoints\n this.msBeforeNext = props.msBeforeNext\n this.consumedPoints = props.consumedPoints\n this.isFirstInDuration = props.isFirstInDuration\n }\n}\n\nexport class QueueFullError extends Error {\n static name = 'QueueFullError'\n\n constructor (message: string = 'The queue was full') {\n super(message)\n this.name = 'QueueFullError'\n }\n}\n\nexport class UnexpectedEOFError extends Error {\n static name = 'UnexpectedEOFError'\n name = 'UnexpectedEOFError'\n}\n\nexport class MaxEarlyStreamsError extends Error {\n static name = 'MaxEarlyStreamsError'\n name = 'MaxEarlyStreamsError'\n}\n\nexport class StreamClosedError extends Error {\n static name = 'StreamClosedError'\n name = 'StreamClosedError'\n}\n", "import { AbortError } from '@libp2p/interface'\nimport pDefer from 'p-defer'\nimport type { AbortOptions } from '@libp2p/interface'\nimport type { DeferredPromise } from 'p-defer'\nimport type { ProgressOptions, ProgressEventListener } from 'progress-events'\n\nexport class JobRecipient<JobReturnType, JobOptions extends AbortOptions & ProgressOptions = any> {\n public deferred: DeferredPromise<JobReturnType>\n public signal?: AbortSignal\n public onProgress?: ProgressEventListener\n\n constructor (options?: Partial<Pick<JobOptions, 'signal' | 'onProgress'>>) {\n this.signal = options?.signal\n this.onProgress = options?.onProgress\n this.deferred = pDefer()\n\n this.onAbort = this.onAbort.bind(this)\n this.signal?.addEventListener('abort', this.onAbort)\n }\n\n onAbort (): void {\n this.deferred.reject(this.signal?.reason ?? new AbortError())\n }\n\n cleanup (): void {\n this.signal?.removeEventListener('abort', this.onAbort)\n }\n}\n", "import { AbortError } from '@libp2p/interface'\nimport { setMaxListeners } from 'main-event'\nimport { raceSignal } from 'race-signal'\nimport { JobRecipient } from './recipient.ts'\nimport type { JobStatus } from './index.ts'\nimport type { AbortOptions } from '@libp2p/interface'\nimport type { ProgressOptions } from 'progress-events'\n\n/**\n * Returns a random string\n */\nfunction randomId (): string {\n return `${(parseInt(String(Math.random() * 1e9), 10)).toString()}${Date.now()}`\n}\n\nexport interface JobTimeline {\n created: number\n started?: number\n finished?: number\n}\n\nexport class Job <JobOptions extends AbortOptions & ProgressOptions = AbortOptions, JobReturnType = unknown> {\n public id: string\n public fn: (options: JobOptions) => Promise<JobReturnType>\n public options: JobOptions\n public recipients: Array<JobRecipient<JobReturnType>>\n public status: JobStatus\n public readonly timeline: JobTimeline\n private readonly controller: AbortController\n private dispatchingProgress: boolean\n\n constructor (fn: (options: JobOptions) => Promise<JobReturnType>, options: any) {\n this.id = randomId()\n this.status = 'queued'\n this.fn = fn\n this.options = options\n this.recipients = []\n this.timeline = {\n created: Date.now()\n }\n\n this.controller = new AbortController()\n setMaxListeners(Infinity, this.controller.signal)\n\n this.dispatchingProgress = false\n\n this.onAbort = this.onAbort.bind(this)\n }\n\n abort (err: Error): void {\n this.controller.abort(err)\n }\n\n onAbort (): void {\n const allAborted = this.recipients.reduce((acc, curr) => {\n return acc && (curr.signal?.aborted === true)\n }, true)\n\n // if all recipients have aborted the job, actually abort the job\n if (allAborted) {\n this.controller.abort(new AbortError())\n this.cleanup()\n }\n }\n\n async join (options?: Partial<Pick<JobOptions, 'signal' | 'onProgress'>>): Promise<JobReturnType> {\n const recipient = new JobRecipient<JobReturnType>(options)\n this.recipients.push(recipient)\n\n options?.signal?.addEventListener('abort', this.onAbort)\n\n return recipient.deferred.promise\n }\n\n async run (): Promise<void> {\n this.status = 'running'\n this.timeline.started = Date.now()\n\n try {\n this.controller.signal.throwIfAborted()\n\n const result = await raceSignal(this.fn({\n ...(this.options ?? {}),\n signal: this.controller.signal,\n onProgress: (evt: any): void => {\n // Recipients can transitively re-enter this dispatcher; without\n // this guard a single event recurses until the stack overflows.\n if (this.dispatchingProgress) {\n return\n }\n\n this.dispatchingProgress = true\n\n try {\n this.recipients.forEach(recipient => {\n recipient.onProgress?.(evt)\n })\n } finally {\n this.dispatchingProgress = false\n }\n }\n }), this.controller.signal)\n\n this.recipients.forEach(recipient => {\n recipient.deferred.resolve(result)\n })\n\n this.status = 'complete'\n } catch (err) {\n this.recipients.forEach(recipient => {\n recipient.deferred.reject(err)\n })\n\n this.status = 'errored'\n } finally {\n this.timeline.finished = Date.now()\n this.cleanup()\n }\n }\n\n cleanup (): void {\n this.recipients.forEach(recipient => {\n recipient.cleanup()\n recipient.signal?.removeEventListener('abort', this.onAbort)\n })\n }\n}\n", "import { AbortError } from '@libp2p/interface'\nimport { pushable } from 'it-pushable'\nimport { TypedEventEmitter } from 'main-event'\nimport { pEvent } from 'p-event'\nimport { debounce } from '../debounce.ts'\nimport { QueueFullError } from '../errors.ts'\nimport { Job } from './job.ts'\nimport type { AbortOptions, Metrics } from '@libp2p/interface'\nimport type { ProgressOptions } from 'progress-events'\n\nexport type { Job, JobTimeline } from './job.ts'\nexport type { JobRecipient } from './recipient.ts'\n\nexport interface Comparator<T> {\n (a: T, b: T): -1 | 0 | 1\n}\n\nexport interface QueueInit<JobReturnType, JobOptions extends AbortOptions = AbortOptions> {\n /**\n * Concurrency limit.\n *\n * Minimum: `1`.\n *\n * @default Infinity\n */\n concurrency?: number\n\n /**\n * If the queue size grows to larger than this number the promise returned\n * from the add function will reject\n *\n * @default Infinity\n */\n maxSize?: number\n\n /**\n * The name of the metric for the queue length\n */\n metricName?: string\n\n /**\n * An implementation of the libp2p Metrics interface\n */\n metrics?: Metrics\n\n /**\n * An optional function that will sort the queue after a job has been added\n */\n sort?: Comparator<Job<JobOptions, JobReturnType>>\n}\n\nexport type JobStatus = 'queued' | 'running' | 'errored' | 'complete'\n\nexport interface RunFunction<Options extends AbortOptions = AbortOptions, ReturnType = void> {\n (options: Options): Promise<ReturnType>\n}\n\nexport interface JobMatcher<JobOptions extends AbortOptions = AbortOptions> {\n (options?: Partial<JobOptions>): boolean\n}\n\nexport interface QueueJobSuccess<JobReturnType, JobOptions extends AbortOptions = AbortOptions> {\n job: Job<JobOptions, JobReturnType>\n result: JobReturnType\n}\n\nexport interface QueueJobFailure<JobReturnType, JobOptions extends AbortOptions = AbortOptions> {\n job: Job<JobOptions, JobReturnType>\n error: Error\n}\n\nexport interface QueueEvents<JobReturnType, JobOptions extends AbortOptions = AbortOptions> {\n /**\n * A job is about to start running\n */\n active: CustomEvent\n\n /**\n * All jobs have finished and the queue is empty\n */\n idle: CustomEvent\n\n /**\n * The queue is empty, jobs may be running\n */\n empty: CustomEvent\n\n /**\n * A job was added to the queue\n */\n add: CustomEvent\n\n /**\n * A job has finished or failed\n */\n next: CustomEvent\n\n /**\n * A job has finished successfully\n */\n completed: CustomEvent<JobReturnType>\n\n /**\n * Emitted just after `\"completed\", a job has finished successfully - this\n * event gives access to the job and it's result\n */\n success: CustomEvent<QueueJobSuccess<JobReturnType, JobOptions>>\n\n /**\n * Emitted just after `\"error\", a job has failed - this event gives access to\n * the job and the thrown error\n */\n failure: CustomEvent<QueueJobFailure<JobReturnType, JobOptions>>\n}\n\n/**\n * Heavily influence by `p-queue` with the following differences:\n *\n * 1. Items remain at the head of the queue while they are running so `queue.size` includes `queue.pending` items - this is so interested parties can join the results of a queue item while it is running\n * 2. The options for a job are stored separately to the job in order for them to be modified while they are still in the queue\n */\nexport class Queue<JobReturnType = unknown, JobOptions extends AbortOptions & ProgressOptions = AbortOptions> extends TypedEventEmitter<QueueEvents<JobReturnType, JobOptions>> {\n public concurrency: number\n public maxSize: number\n public queue: Array<Job<JobOptions, JobReturnType>>\n private pending: number\n private readonly sort?: Comparator<Job<JobOptions, JobReturnType>>\n private paused: boolean\n\n constructor (init: QueueInit<JobReturnType, JobOptions> = {}) {\n super()\n\n this.concurrency = init.concurrency ?? Number.POSITIVE_INFINITY\n this.maxSize = init.maxSize ?? Number.POSITIVE_INFINITY\n this.pending = 0\n this.paused = false\n\n if (init.metricName != null) {\n init.metrics?.registerMetricGroup(init.metricName, {\n calculate: () => {\n return {\n size: this.queue.length,\n running: this.pending,\n queued: this.queue.length - this.pending\n }\n }\n })\n }\n\n this.sort = init.sort\n this.queue = []\n\n this.emitEmpty = debounce(this.emitEmpty.bind(this), 1)\n this.emitIdle = debounce(this.emitIdle.bind(this), 1)\n }\n\n emitEmpty (): void {\n if (this.size !== 0) {\n return\n }\n\n this.safeDispatchEvent('empty')\n }\n\n emitIdle (): void {\n if (this.running !== 0) {\n return\n }\n\n this.safeDispatchEvent('idle')\n }\n\n pause (): void {\n this.paused = true\n }\n\n resume (): void {\n if (!this.paused) {\n return\n }\n\n this.paused = false\n this.tryToStartAnother()\n }\n\n private tryToStartAnother (): boolean {\n if (this.paused) {\n return false\n }\n\n if (this.size === 0) {\n this.emitEmpty()\n\n if (this.running === 0) {\n this.emitIdle()\n }\n\n return false\n }\n\n if (this.pending < this.concurrency) {\n let job: Job<JobOptions, JobReturnType> | undefined\n\n for (const j of this.queue) {\n if (j.status === 'queued') {\n job = j\n break\n }\n }\n\n if (job == null) {\n return false\n }\n\n this.safeDispatchEvent('active')\n\n this.pending++\n\n void job.run()\n .finally(() => {\n // remove the job from the queue\n for (let i = 0; i < this.queue.length; i++) {\n if (this.queue[i] === job) {\n this.queue.splice(i, 1)\n break\n }\n }\n\n this.pending--\n this.tryToStartAnother()\n this.safeDispatchEvent('next')\n })\n\n return true\n }\n\n return false\n }\n\n private enqueue (job: Job<JobOptions, JobReturnType>): void {\n this.queue.push(job)\n\n if (this.sort != null) {\n this.queue.sort(this.sort)\n }\n }\n\n /**\n * Adds a sync or async task to the queue. Always returns a promise.\n */\n async add (fn: RunFunction<JobOptions, JobReturnType>, options?: JobOptions): Promise<JobReturnType> {\n options?.signal?.throwIfAborted()\n\n if (this.size === this.maxSize) {\n throw new QueueFullError()\n }\n\n const job = new Job<JobOptions, JobReturnType>(fn, options)\n this.enqueue(job)\n this.safeDispatchEvent('add')\n\n const result = job.join(options)\n .then(result => {\n this.safeDispatchEvent('completed', { detail: result })\n this.safeDispatchEvent('success', { detail: { job, result } })\n\n return result\n })\n .catch(err => {\n if (job.status === 'queued') {\n // job was aborted before it started - remove the job from the queue\n for (let i = 0; i < this.queue.length; i++) {\n if (this.queue[i] === job) {\n this.queue.splice(i, 1)\n break\n }\n }\n }\n\n this.safeDispatchEvent('failure', { detail: { job, error: err } })\n\n throw err\n })\n\n this.tryToStartAnother()\n\n return result\n }\n\n /**\n * Clear the queue\n */\n clear (): void {\n this.queue.splice(0, this.queue.length)\n }\n\n /**\n * Abort all jobs in the queue and clear it\n */\n abort (): void {\n this.queue.forEach(job => {\n job.abort(new AbortError())\n })\n\n this.clear()\n }\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 (options?: AbortOptions): Promise<void> {\n // Instantly resolve if the queue is empty\n if (this.size === 0) {\n return\n }\n\n await pEvent(this, 'empty', options)\n }\n\n /**\n * @returns A promise that settles when the queue size is less than the given\n * limit: `queue.size < limit`.\n *\n * If you want to avoid having the queue grow beyond a certain size you can\n * `await queue.onSizeLessThan()` before adding a new item.\n *\n * Note that this only limits the number of items waiting to start. There\n * could still be up to `concurrency` jobs already running that this call does\n * not include in its calculation.\n */\n async onSizeLessThan (limit: number, options?: AbortOptions): Promise<void> {\n // Instantly resolve if the queue is empty.\n if (this.size < limit) {\n return\n }\n\n await pEvent(this, 'next', {\n ...options,\n filter: () => this.size < limit\n })\n }\n\n /**\n * The difference with `.onEmpty` is that `.onIdle` guarantees that all work\n * from the queue has finished. `.onEmpty` merely signals that the queue is\n * 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\n * promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle (options?: AbortOptions): Promise<void> {\n // Instantly resolve if none pending and if nothing else is queued\n if (this.pending === 0 && this.size === 0) {\n return\n }\n\n await pEvent(this, 'idle', options)\n }\n\n /**\n * Size of the queue including running items\n */\n get size (): number {\n return this.queue.length\n }\n\n /**\n * The number of queued items waiting to run.\n */\n get queued (): number {\n return this.queue.length - this.pending\n }\n\n /**\n * The number of items currently running.\n */\n get running (): number {\n return this.pending\n }\n\n /**\n * Returns an async generator that makes it easy to iterate over the results\n * of jobs added to the queue.\n *\n * The generator will end when the queue becomes idle, that is there are no\n * jobs running and no jobs that have yet to run.\n *\n * If you need to keep the queue open indefinitely, consider using it-pushable\n * instead.\n */\n async * toGenerator (options?: AbortOptions): AsyncGenerator<JobReturnType, void, unknown> {\n options?.signal?.throwIfAborted()\n\n const stream = pushable<JobReturnType>({\n objectMode: true\n })\n\n const cleanup = (err?: Error): void => {\n if (err != null) {\n this.abort()\n } else {\n this.clear()\n }\n\n stream.end(err)\n }\n\n const onQueueJobComplete = (evt: CustomEvent<JobReturnType>): void => {\n if (evt.detail != null) {\n stream.push(evt.detail)\n }\n }\n\n const onQueueFailure = (evt: CustomEvent<QueueJobFailure<JobReturnType, JobOptions>>): void => {\n cleanup(evt.detail.error)\n }\n\n const onQueueIdle = (): void => {\n cleanup()\n }\n\n // clear the queue and throw if the query is aborted\n const onSignalAbort = (): void => {\n cleanup(new AbortError('Queue aborted'))\n }\n\n // add listeners\n this.addEventListener('completed', onQueueJobComplete)\n this.addEventListener('failure', onQueueFailure)\n this.addEventListener('idle', onQueueIdle)\n options?.signal?.addEventListener('abort', onSignalAbort)\n\n try {\n yield * stream\n } finally {\n // remove listeners\n this.removeEventListener('completed', onQueueJobComplete)\n this.removeEventListener('failure', onQueueFailure)\n this.removeEventListener('idle', onQueueIdle)\n options?.signal?.removeEventListener('abort', onSignalAbort)\n\n // empty the queue for when the user has broken out of a loop early\n cleanup()\n }\n }\n}\n", "/**\n * @packageDocumentation\n *\n * Similar to [AbortSignal.any](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/any_static)\n * except the returned promise has a `.clear` method that removes all event\n * listeners added to passed signals preventing memory leaks.\n *\n * At the time of writing at least, `AbortSignal.any` leaks memory in Node.js\n * and Deno environments:\n *\n * - https://github.com/nodejs/node/issues/54614\n * - https://github.com/denoland/deno/issues/24842\n *\n * @example\n *\n * ```js\n * import { anySignal } from 'any-signal'\n *\n * const userController = new AbortController()\n *\n * // Abort after 1 second\n * const timeoutSignal = AbortSignal.timeout(1000)\n *\n * const combinedSignal = anySignal([userController.signal, timeoutSignal])\n * combinedSignal.addEventListener('abort', () => console.log('Abort!'))\n *\n * try {\n * // The user or the timeout can now abort the action\n * await performSomeAction({ signal: combinedSignal })\n * } finally {\n * // Clear will clean up internal event handlers\n * combinedSignal.clear()\n * }\n * ```\n */\n\nexport interface ClearableSignal extends AbortSignal {\n clear(): void\n}\n\n/**\n * Takes an array of AbortSignals and returns a single signal.\n * If any signals are aborted, the returned signal will be aborted.\n */\nexport function anySignal (signals: Array<AbortSignal | undefined | null>): ClearableSignal {\n const controller = new globalThis.AbortController()\n\n function onAbort (): void {\n const reason = signals\n .filter(s => s?.aborted === true)\n .map(s => s?.reason)\n .pop()\n\n controller.abort(reason)\n\n for (const signal of signals) {\n if (signal?.removeEventListener != null) {\n signal.removeEventListener('abort', onAbort)\n }\n }\n }\n\n for (const signal of signals) {\n if (signal?.aborted === true) {\n onAbort()\n break\n }\n\n if (signal?.addEventListener != null) {\n signal.addEventListener('abort', onAbort)\n }\n }\n\n function clear (): void {\n for (const signal of signals) {\n if (signal?.removeEventListener != null) {\n signal.removeEventListener('abort', onAbort)\n }\n }\n }\n\n const signal = controller.signal as ClearableSignal\n signal.clear = clear\n\n return signal\n}\n", "/**\n * @packageDocumentation\n *\n * Collects all `Uint8Array` values from an (async)iterable and returns them as a single `Uint8Array`.\n *\n * @example\n *\n * ```javascript\n * import toBuffer from 'it-to-buffer'\n *\n * // This can also be an iterator, generator, etc\n * const values = [Buffer.from([0, 1]), Buffer.from([2, 3])]\n *\n * const result = toBuffer(values)\n *\n * console.info(result) // Buffer[0, 1, 2, 3]\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import toBuffer from 'it-to-buffer'\n *\n * const values = async function * () {\n * yield Buffer.from([0, 1])\n * yield Buffer.from([2, 3])\n * }\n *\n * const result = await toBuffer(values())\n *\n * console.info(result) // Buffer[0, 1, 2, 3]\n * ```\n */\n\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\n\nfunction isAsyncIterable <T> (thing: any): thing is AsyncIterable<T> {\n return thing[Symbol.asyncIterator] != null\n}\n\n/**\n * Takes an (async) iterable that yields buffer-like-objects and concats them\n * into one buffer\n */\nfunction toBuffer (source: Iterable<Uint8Array>): Uint8Array<ArrayBuffer>\nfunction toBuffer (source: Iterable<Uint8Array> | AsyncIterable<Uint8Array>): Promise<Uint8Array<ArrayBuffer>>\nfunction toBuffer (source: Iterable<Uint8Array> | AsyncIterable<Uint8Array>): Promise<Uint8Array<ArrayBuffer>> | Uint8Array<ArrayBuffer> {\n if (isAsyncIterable(source)) {\n return (async () => {\n let buffer = new Uint8Array(0)\n\n for await (const buf of source) {\n buffer = uint8ArrayConcat([buffer, buf], buffer.length + buf.length)\n }\n\n return buffer\n })()\n }\n\n const bufs = []\n let length = 0\n\n for (const buf of source) {\n bufs.push(buf)\n length += buf.byteLength\n }\n\n return uint8ArrayConcat(bufs, length)\n}\n\nexport default toBuffer\n", "import { bytes as binary, CID } from './index.ts'\nimport type * as API from './interface.ts'\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", "import { Queue } from '@libp2p/utils'\nimport filter from 'it-filter'\nimport toBuffer from 'it-to-buffer'\nimport { createUnsafe } from 'multiformats/block'\nimport type {\n GraphWalker,\n GraphWalkerComponents,\n GraphWalkerInit,\n GraphNode,\n WalkOptions\n} from '@helia/interface'\nimport type { AbortOptions } from '@libp2p/interface'\nimport type { CID } from 'multiformats'\n\nexport type { GraphWalker, GraphWalkerComponents, GraphWalkerInit, GraphNode, WalkOptions }\n\n/**\n * A depth-first walker descends into child blocks before processing successor\n * sibling blocks\n */\nexport function depthFirstWalker (init?: GraphWalkerInit): (components: GraphWalkerComponents) => GraphWalker {\n return (components) => new DepthFirstGraphWalker(components, init)\n}\n\n/**\n * A breadth-first walker processes sibling blocks before child blocks\n */\nexport function breadthFirstWalker (init?: GraphWalkerInit): (components: GraphWalkerComponents) => GraphWalker {\n return (components) => new BreadthFirstGraphWalker(components, init)\n}\n\n/**\n * A natural order walker processes blocks in the order defined by the codec and\n * does not try to sort them\n */\nexport function naturalOrderWalker (init?: GraphWalkerInit): (components: GraphWalkerComponents) => GraphWalker {\n return (components) => new NaturalOrderGraphWalker(components, init)\n}\n\ninterface JobOptions extends AbortOptions {\n cid: CID\n depth: number\n path: CID[]\n}\n\nabstract class AbstractGraphWalker {\n private readonly components: GraphWalkerComponents\n\n constructor (components: GraphWalkerComponents, init: GraphWalkerInit = {}) {\n this.components = components\n }\n\n async * walk <T = any> (cid: CID, options?: WalkOptions<T>): AsyncGenerator<GraphNode<T>> {\n const queue = this.getQueue()\n const gen = filter(queue.toGenerator(options), (node) => node != null) as AsyncGenerator<GraphNode<T>>\n let finished = false\n const maxDepth = options?.depth ?? Infinity\n\n const job = async (opts: JobOptions): Promise<GraphNode<T> | undefined> => {\n const cid = opts.cid\n const bytes = await toBuffer(this.components.blockstore.get(cid, opts))\n const block = createUnsafe<T, number, number, 0 | 1>({\n cid,\n bytes,\n codec: await this.components.getCodec(cid.code)\n })\n\n if (opts.depth < maxDepth) {\n for (const [, linkedCid] of block.links()) {\n if (options?.includeChild?.(linkedCid, block) === false) {\n continue\n }\n\n queue.add(job, {\n ...opts,\n cid: linkedCid,\n depth: opts.depth + 1,\n path: [...opts.path, linkedCid]\n })\n // eslint-disable-next-line no-loop-func\n .catch(err => {\n // only throw if the generator is still yielding results, otherwise\n // it can cause unhandled promise rejections\n if (!finished) {\n gen.throw(err)\n }\n })\n }\n }\n\n return {\n block,\n depth: opts.depth,\n path: opts.path\n }\n }\n\n queue.add(job, {\n ...options,\n cid,\n depth: 0,\n path: [cid]\n })\n .catch(err => {\n // only throw if the generator is still yielding results, otherwise it\n // can cause unhandled promise rejections\n if (!finished) {\n gen.throw(err)\n }\n })\n\n try {\n yield * gen\n } finally {\n finished = true\n // abort any in-progress operations\n queue.abort()\n }\n }\n\n abstract getQueue <T> (): Queue<GraphNode<T> | undefined, JobOptions>\n}\n\nclass DepthFirstGraphWalker extends AbstractGraphWalker {\n getQueue<T>(): Queue<GraphNode<T> | undefined, JobOptions> {\n return new Queue<GraphNode<T> | undefined, JobOptions>({\n concurrency: 1,\n sort: (a, b) => {\n if (a.options.depth === b.options.depth) {\n return 0\n }\n\n if (a.options.depth < b.options.depth) {\n return 1\n }\n\n return -1\n }\n })\n }\n}\n\nclass BreadthFirstGraphWalker extends AbstractGraphWalker {\n getQueue<T>(): Queue<GraphNode<T> | undefined, JobOptions> {\n return new Queue<GraphNode<T> | undefined, JobOptions>({\n concurrency: 1,\n sort: (a, b) => {\n if (a.options.depth === b.options.depth) {\n return 0\n }\n\n if (a.options.depth < b.options.depth) {\n return -1\n }\n\n return 1\n }\n })\n }\n}\n\nexport class NaturalOrderGraphWalker extends AbstractGraphWalker {\n getQueue<T>(): Queue<GraphNode<T> | undefined, JobOptions> {\n return new Queue<GraphNode<T> | undefined, JobOptions>({\n concurrency: 1\n })\n }\n}\n", "import { InvalidParametersError } from '@libp2p/interface'\nimport * as cborg from 'cborg'\nimport { Key } from 'interface-datastore'\nimport { base36 } from 'multiformats/bases/base36'\nimport { CID } from 'multiformats/cid'\nimport { CustomProgressEvent } from 'progress-events'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { AlreadyPinnedError } from './errors.ts'\nimport { depthFirstWalker } from './graph-walker.ts'\nimport type { CodecLoader } from '@helia/interface'\nimport type { AddOptions, IsPinnedOptions, LsOptions, Pin, Pins, RmOptions } from '@helia/interface'\nimport type { AbortOptions } from '@libp2p/interface'\nimport type { Blockstore } from 'interface-blockstore'\nimport type { Datastore } from 'interface-datastore'\nimport type { Version } from 'multiformats/cid'\n\ninterface DatastorePin {\n /**\n * 0 for a direct pin or an arbitrary (+ve, whole) number or Infinity\n */\n depth: number\n\n /**\n * User-specific metadata for the pin\n */\n metadata: Record<string, string | number | boolean>\n}\n\ninterface DatastorePinnedBlock {\n pinCount: number\n pinnedBy: Uint8Array[]\n}\n\n/**\n * Callback for updating a {@link DatastorePinnedBlock}'s properties when\n * calling `#updatePinnedBlock`\n *\n * The callback should return `false` to prevent any pinning modifications to\n * the block, and true in all other cases.\n */\ninterface WithPinnedBlockCallback {\n (pinnedBlock: DatastorePinnedBlock): boolean\n}\n\nconst DATASTORE_PIN_PREFIX = '/pin/'\nconst DATASTORE_BLOCK_PREFIX = '/pinned-block/'\nconst DATASTORE_ENCODING = base36\n\nfunction toDSKey (cid: CID): Key {\n if (cid.version === 0) {\n cid = cid.toV1()\n }\n\n return new Key(`${DATASTORE_PIN_PREFIX}${cid.toString(DATASTORE_ENCODING)}`)\n}\n\nexport class PinsImpl implements Pins {\n private readonly datastore: Datastore\n private readonly blockstore: Blockstore\n private readonly getCodec: CodecLoader\n\n constructor (datastore: Datastore, blockstore: Blockstore, getCodec: CodecLoader) {\n this.datastore = datastore\n this.blockstore = blockstore\n this.getCodec = getCodec\n }\n\n async * add (cid: CID<unknown, number, number, Version>, options: AddOptions = {}): AsyncGenerator<CID, void, undefined> {\n const pinKey = toDSKey(cid)\n\n if (await this.datastore.has(pinKey)) {\n throw new AlreadyPinnedError('Already pinned')\n }\n\n const depth = Math.round(options.depth ?? Infinity)\n\n if (depth < 0) {\n throw new InvalidParametersError('Depth must be greater than or equal to 0')\n }\n\n const walker = (options.walker ?? depthFirstWalker())({\n blockstore: this.blockstore,\n getCodec: this.getCodec\n })\n\n for await (const node of walker.walk(cid, { ...options, depth })) {\n const childCid = node.block.cid\n await this.#updatePinnedBlock(childCid, (pinnedBlock: DatastorePinnedBlock) => {\n // do not update pinned block if this block is already pinned by this CID\n if (pinnedBlock.pinnedBy.find(c => uint8ArrayEquals(c, cid.bytes)) != null) {\n return false\n }\n\n pinnedBlock.pinCount++\n pinnedBlock.pinnedBy.push(cid.bytes)\n return true\n }, options)\n\n yield childCid\n }\n\n const pin: DatastorePin = {\n depth,\n metadata: options.metadata ?? {}\n }\n\n await this.datastore.put(pinKey, cborg.encode(pin), options)\n }\n\n /**\n * Update the pin count for the CID\n */\n async #updatePinnedBlock (cid: CID, withPinnedBlock: WithPinnedBlockCallback, options: AddOptions): Promise<void> {\n const blockKey = new Key(`${DATASTORE_BLOCK_PREFIX}${DATASTORE_ENCODING.encode(cid.multihash.bytes)}`)\n\n let pinnedBlock: DatastorePinnedBlock = {\n pinCount: 0,\n pinnedBy: []\n }\n\n try {\n pinnedBlock = cborg.decode(await this.datastore.get(blockKey, options))\n } catch (err: any) {\n if (err.name !== 'NotFoundError') {\n throw err\n }\n }\n\n const shouldContinue = withPinnedBlock(pinnedBlock)\n\n if (!shouldContinue) {\n return\n }\n\n if (pinnedBlock.pinCount === 0) {\n if (await this.datastore.has(blockKey)) {\n await this.datastore.delete(blockKey)\n return\n }\n }\n\n await this.datastore.put(blockKey, cborg.encode(pinnedBlock), options)\n options.onProgress?.(new CustomProgressEvent<CID>('helia:pin:add', cid))\n }\n\n async * rm (cid: CID<unknown, number, number, Version>, options: RmOptions = {}): AsyncGenerator<CID, void, undefined> {\n const pinKey = toDSKey(cid)\n const buf = await this.datastore.get(pinKey, options)\n const pin = cborg.decode(buf)\n\n await this.datastore.delete(pinKey, options)\n\n const walker = (options.walker ?? depthFirstWalker())({\n blockstore: this.blockstore,\n getCodec: this.getCodec\n })\n\n for await (const node of walker.walk(cid, { ...options, depth: pin.depth })) {\n const childCid = node.block.cid\n await this.#updatePinnedBlock(childCid, (pinnedBlock): boolean => {\n pinnedBlock.pinCount--\n pinnedBlock.pinnedBy = pinnedBlock.pinnedBy.filter(c => uint8ArrayEquals(c, cid.bytes))\n return true\n }, {\n ...options,\n depth: pin.depth\n })\n\n yield childCid\n }\n }\n\n async * ls (options: LsOptions = {}): AsyncGenerator<Pin, void, undefined> {\n for await (const { key, value } of this.datastore.query({\n prefix: DATASTORE_PIN_PREFIX + (options.cid != null ? `${options.cid.toString(base36)}` : '')\n }, options)) {\n const cid = CID.parse(key.toString().substring(5), base36)\n const pin = cborg.decode(value)\n\n yield {\n cid,\n ...pin\n }\n }\n }\n\n async isPinned (cid: CID, options: IsPinnedOptions = {}): Promise<boolean> {\n const blockKey = new Key(`${DATASTORE_BLOCK_PREFIX}${DATASTORE_ENCODING.encode(cid.multihash.bytes)}`)\n\n return this.datastore.has(blockKey, options)\n }\n\n async get (cid: CID, options?: AbortOptions): Promise<Pin> {\n const pinKey = toDSKey(cid)\n const buf = await this.datastore.get(pinKey, options)\n\n return cborg.decode(buf)\n }\n\n async setMetadata (cid: CID, metadata: Record<string, string | number | boolean> | undefined, options?: AbortOptions): Promise<void> {\n const pinKey = toDSKey(cid)\n const buf = await this.datastore.get(pinKey, options)\n const pin: DatastorePin = cborg.decode(buf)\n\n pin.metadata = metadata ?? {}\n\n await this.datastore.put(pinKey, cborg.encode(pin), options)\n }\n}\n", "export class InsufficientProvidersError extends Error {\n static name = 'InsufficientProvidersError'\n\n constructor (message = 'Insufficient providers found') {\n super(message)\n this.name = 'InsufficientProvidersError'\n }\n}\n\nexport class NoRoutersAvailableError extends Error {\n static name = 'NoRoutersAvailableError'\n\n constructor (message = 'No routers available') {\n super(message)\n this.name = 'NoRoutersAvailableError'\n }\n}\n\nexport class UnknownHashAlgorithmError extends Error {\n static name = 'UnknownHashAlgorithmError'\n\n constructor (message = 'Unknown hash algorithm') {\n super(message)\n this.name = 'UnknownHashAlgorithmError'\n }\n}\n\nexport class UnknownCodecError extends Error {\n static name = 'UnknownCodecError'\n\n constructor (message = 'Unknown codec') {\n super(message)\n this.name = 'UnknownCodecError'\n }\n}\n\nexport class InvalidCodecError extends Error {\n static name = 'InvalidCodecError'\n\n constructor (message = 'Invalid codec') {\n super(message)\n this.name = 'InvalidCodecError'\n }\n}\n\nexport class UnknownCryptoError extends Error {\n static name = 'UnknownCryptoError'\n name = 'UnknownCryptoError'\n}\n", "import { NoRoutersAvailableError } from '@helia/interface'\nimport { NotFoundError, start, stop } from '@libp2p/interface'\nimport { Queue } from '@libp2p/utils'\nimport merge from 'it-merge'\nimport { CustomProgressEvent } from 'progress-events'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { GetFailedError } from './errors.ts'\nimport type { Routing as RoutingInterface, Provider, RoutingOptions, RoutingFindProvidersProgressEvents, RoutingProvideProgressEvents, RoutingPutProgressEvents, RoutingGetProgressEvents, RoutingFindPeerProgressEvents, RoutingGetClosestPeersProgressEvents, RoutingCancelReprovideProgressEvents, Router, Peer } from '@helia/interface'\nimport type { ComponentLogger, Logger, Metrics, Startable } from '@libp2p/interface'\nimport type { AbortOptions } from 'abort-error'\nimport type { CID } from 'multiformats/cid'\n\nconst DEFAULT_PROVIDER_LOOKUP_CONCURRENCY = 5\n\nexport interface RoutingInit {\n routers: Router[]\n providerLookupConcurrency?: number\n}\n\nexport interface RoutingComponents {\n logger: ComponentLogger\n metrics?: Metrics\n}\n\ninterface PeerQueueOptions extends AbortOptions {\n peer: CID\n}\n\nexport class Routing implements RoutingInterface, Startable {\n public name: string\n\n private readonly log: Logger\n private readonly routers: Router[]\n private readonly providerLookupConcurrency: number\n\n constructor (components: RoutingComponents, init: RoutingInit) {\n this.name = 'helia'\n this.log = components.logger.forComponent('helia:routing')\n this.routers = init.routers ?? []\n this.providerLookupConcurrency = init.providerLookupConcurrency ?? DEFAULT_PROVIDER_LOOKUP_CONCURRENCY\n\n this.findProviders = components.metrics?.traceFunction('helia.routing.findProviders', this.findProviders.bind(this), {\n optionsIndex: 1\n }) ?? this.findProviders\n this.provide = components.metrics?.traceFunction('helia.routing.provide', this.provide.bind(this), {\n optionsIndex: 1\n }) ?? this.provide\n this.cancelReprovide = components.metrics?.traceFunction('helia.routing.cancelReprovide', this.cancelReprovide.bind(this), {\n optionsIndex: 1\n }) ?? this.cancelReprovide\n this.put = components.metrics?.traceFunction('helia.routing.put', this.put.bind(this), {\n optionsIndex: 2\n }) ?? this.put\n this.get = components.metrics?.traceFunction('helia.routing.get', this.get.bind(this), {\n optionsIndex: 1\n }) ?? this.get\n this.findPeer = components.metrics?.traceFunction('helia.routing.findPeer', this.findPeer.bind(this), {\n optionsIndex: 1\n }) ?? this.findPeer\n this.getClosestPeers = components.metrics?.traceFunction('helia.routing.getClosestPeers', this.getClosestPeers.bind(this), {\n optionsIndex: 1\n }) ?? this.getClosestPeers\n }\n\n async start (): Promise<void> {\n await start(...this.routers)\n }\n\n async stop (): Promise<void> {\n await stop(...this.routers)\n }\n\n hasRouter (name: string): boolean {\n return this.routers.findIndex(r => r.name === name) !== -1\n }\n\n addRouter (router: Router): void {\n this.routers.push(router)\n }\n\n /**\n * Iterates over all content routers in parallel to find providers of the\n * given key\n */\n async * findProviders (key: CID, options: RoutingOptions<RoutingFindProvidersProgressEvents> = {}): AsyncIterable<Provider> {\n if (this.routers.length === 0) {\n throw new NoRoutersAvailableError('No content routers available')\n }\n\n // provider multiaddrs are only cached for a limited time, so they can come\n // back as an empty array - when this happens we have to do a FIND_PEER\n // query to get updated addresses, but we shouldn't block on this so use a\n // separate bounded queue to perform this lookup\n const queue = new Queue<Provider | null, PeerQueueOptions>({\n concurrency: this.providerLookupConcurrency\n })\n\n let foundProviders = 0\n const errors: Error[] = []\n const self = this\n let routersFinished = 0\n\n this.log('findProviders for %c start using routers %s', key, this.routers.map(r => r.toString()).join(', '))\n\n const routers = supports(this.routers, 'findProviders')\n .map(async function * (router) {\n let foundProviders = 0\n\n options?.onProgress?.(new CustomProgressEvent('helia:routing:find-providers:start', {\n routing: router.name,\n cid: key\n }))\n\n try {\n for await (const prov of router.findProviders(key, options)) {\n foundProviders++\n\n // @ts-expect-error router.name is a string, needs to be specific\n options?.onProgress?.(new CustomProgressEvent('helia:routing:find-providers:provider', {\n routing: router.name,\n cid: key,\n provider: prov\n }))\n\n yield prov\n }\n } catch (err: any) {\n errors.push(err)\n } finally {\n self.log('router %s found %d providers for %c', router, foundProviders, key)\n\n options?.onProgress?.(new CustomProgressEvent('helia:routing:find-providers:end', {\n routing: router.name,\n cid: key,\n found: foundProviders\n }))\n\n routersFinished++\n\n // if all routers have finished and there are no jobs to find updated\n // peer multiaddres running or queued, cause the generator to exit\n if (routersFinished === routers.length && queue.size === 0) {\n queue.emitIdle()\n }\n }\n })\n\n for await (const peer of merge(\n queue.toGenerator(),\n ...routers)\n ) {\n // the peer was yielded by a content router without multiaddrs and we\n // failed to load them\n if (peer == null) {\n continue\n }\n\n // have to refresh peer info for this peer to get updated multiaddrs\n if (peer.multiaddrs.length === 0) {\n // already looking this peer up\n if (queue.queue.find(job => job.options.peer.equals(peer.id)) != null) {\n continue\n }\n\n queue.add(async () => {\n try {\n const provider = await this.findPeer(peer.id, options)\n\n if (provider.multiaddrs.length === 0) {\n return null\n }\n\n return {\n ...provider,\n protocols: peer.protocols,\n routing: peer.routing\n }\n } catch (err) {\n this.log.error('could not load multiaddrs for peer %p - %e', peer.id, err)\n return null\n }\n }, {\n peer: peer.id,\n signal: options.signal\n })\n .catch(err => {\n this.log.error('could not load multiaddrs for peer %p - %e', peer.id, err)\n })\n\n continue\n }\n\n foundProviders++\n yield peer\n }\n\n this.log('findProviders finished, found %d providers for %c', foundProviders, key)\n }\n\n /**\n * Iterates over all content routers in parallel to notify it is\n * a provider of the given key\n */\n async provide (key: CID, options: RoutingOptions<RoutingProvideProgressEvents> = {}): Promise<void> {\n if (this.routers.length === 0) {\n throw new NoRoutersAvailableError('No content routers available')\n }\n\n await Promise.all(\n supports(this.routers, 'provide')\n .map(async (router) => {\n options?.onProgress?.(new CustomProgressEvent('helia:routing:provide:start', {\n routing: router.name,\n cid: key\n }))\n\n await router.provide(key, options)\n\n options?.onProgress?.(new CustomProgressEvent('helia:routing:provide:end', {\n routing: router.name,\n cid: key\n }))\n })\n )\n }\n\n async cancelReprovide (key: CID, options: RoutingOptions<RoutingCancelReprovideProgressEvents> = {}): Promise<void> {\n await Promise.all(\n supports(this.routers, 'cancelReprovide')\n .map(async (router) => {\n options?.onProgress?.(new CustomProgressEvent('helia:routing:cancel-reprovide:start', {\n routing: router.name,\n cid: key\n }))\n\n await router.cancelReprovide(key, options)\n\n options?.onProgress?.(new CustomProgressEvent('helia:routing:cancel-reprovide:end', {\n routing: router.name,\n cid: key\n }))\n })\n )\n }\n\n /**\n * Store the given key/value pair in the available content routings\n */\n async put (key: Uint8Array, value: Uint8Array, options?: RoutingOptions<RoutingPutProgressEvents>): Promise<void> {\n await Promise.all(\n supports(this.routers, 'put')\n .map(async (router) => {\n options?.onProgress?.(new CustomProgressEvent('helia:routing:put:start', {\n routing: router.name,\n key,\n value\n }))\n\n await router.put(key, value, options)\n\n options?.onProgress?.(new CustomProgressEvent('helia:routing:put:end', {\n routing: router.name,\n key,\n value\n }))\n })\n )\n }\n\n /**\n * Get the value to the given key. The first value offered by any configured\n * router will be returned.\n */\n async get (key: Uint8Array, options?: RoutingOptions<RoutingGetProgressEvents>): Promise<Uint8Array> {\n const errors: Error[] = []\n let result: Uint8Array | undefined\n\n try {\n result = await Promise.any(\n supports(this.routers, 'get')\n .map(async (router) => {\n options?.onProgress?.(new CustomProgressEvent('helia:routing:get:start', {\n routing: router.name,\n key\n }))\n\n try {\n return await router.get(key, options)\n } catch (err: any) {\n this.log('router %s failed with %e', router, err)\n errors.push(err)\n } finally {\n options?.onProgress?.(new CustomProgressEvent('helia:routing:get:end', {\n routing: router.name,\n key\n }))\n }\n })\n )\n } catch {\n // ignore AggregateError as we will throw a better-named one\n }\n\n if (result == null) {\n throw new GetFailedError(errors, `Failed to get value key ${uint8ArrayToString(key, 'base58btc')}`)\n }\n\n return result\n }\n\n /**\n * Iterates over all peer routers in parallel to find the given peer\n */\n async findPeer (id: CID, options?: RoutingOptions<RoutingFindPeerProgressEvents>): Promise<Peer> {\n if (this.routers.length === 0) {\n throw new NoRoutersAvailableError('No peer routers available')\n }\n\n const self = this\n const source = merge(\n ...supports(this.routers, 'findPeer')\n .map(router => (async function * () {\n options?.onProgress?.(new CustomProgressEvent('helia:routing:find-peer:start', {\n routing: router.name,\n peerId: id\n }))\n\n try {\n yield await router.findPeer(id, options)\n } catch (err) {\n self.log.error(err)\n } finally {\n options?.onProgress?.(new CustomProgressEvent('helia:routing:find-peer:end', {\n routing: router.name,\n peerId: id\n }))\n }\n })())\n )\n\n for await (const peer of source) {\n if (peer == null) {\n continue\n }\n\n return peer\n }\n\n throw new NotFoundError('Could not find peer in routing')\n }\n\n /**\n * Attempt to find the closest peers on the network to the given key\n */\n async * getClosestPeers (key: Uint8Array, options: RoutingOptions<RoutingGetClosestPeersProgressEvents> = {}): AsyncIterable<Peer> {\n if (this.routers.length === 0) {\n throw new NoRoutersAvailableError('No peer routers available')\n }\n\n for await (const peer of merge(\n ...supports(this.routers, 'getClosestPeers')\n .map(async function * (router) {\n options?.onProgress?.(new CustomProgressEvent('helia:routing:get-closest-peers:start', {\n routing: router.name,\n key\n }))\n\n try {\n yield * router.getClosestPeers(key, options)\n } finally {\n options?.onProgress?.(new CustomProgressEvent('helia:routing:get-closest-peers:end', {\n routing: router.name,\n key\n }))\n }\n })\n )) {\n if (peer == null) {\n continue\n }\n\n yield peer\n }\n }\n}\n\nfunction supports <Operation extends keyof Routing> (routers: any[], key: Operation): Array<Pick<Routing, Operation | 'name'>> {\n return routers.filter(router => router[key] != null)\n}\n", "/**\n * @packageDocumentation\n *\n * A simple error class and options interface that seems to get copied from\n * project to project.\n *\n * @example Using AbortError\n *\n * ```JavaScript\n * import { AbortError } from 'abort-error'\n *\n * // a promise that will be settled later\n * const deferred = Promise.withResolvers()\n *\n * const signal = AbortSignal.timeout(1000)\n * signal.addEventListener('abort', () => {\n * deferred.reject(new AbortError())\n * })\n * ```\n *\n * @example Using AbortOptions\n *\n * ```TypeScript\n * import type { AbortOptions } from 'abort-error'\n *\n * async function myFunction (options?: AbortOptions) {\n * return fetch('https://example.com', {\n * signal: options?.signal\n * })\n * }\n * ```\n */\n\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\nexport class AbortError extends Error {\n static name = 'AbortError'\n name = 'AbortError'\n\n constructor (message: string = 'The operation was aborted', ...rest: any[]) {\n super(message, ...rest)\n }\n}\n", "/**\n * @packageDocumentation\n *\n * Race an event against an AbortSignal, taking care to remove any event\n * listeners that were added.\n *\n * @example Getting started\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * setTimeout(() => {\n * // too late\n * emitter.dispatchEvent(new CustomEvent('event'))\n * }, 1000)\n *\n * // throws an AbortError\n * const resolve = await raceEvent(emitter, 'event', controller.signal)\n * ```\n *\n * @example Aborting the promise with an error event\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const emitter = new EventTarget()\n *\n * setTimeout(() => {\n * emitter.dispatchEvent(new CustomEvent('failure', {\n * detail: new Error('Oh no!')\n * }))\n * }, 1000)\n *\n * // throws 'Oh no!' error\n * const resolve = await raceEvent(emitter, 'success', AbortSignal.timeout(5000), {\n * errorEvent: 'failure'\n * })\n * ```\n *\n * @example Customising the thrown AbortError\n *\n * The error message and `.code` property of the thrown `AbortError` can be\n * specified by passing options:\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * // throws a Error: Oh no!\n * const resolve = await raceEvent(emitter, 'event', controller.signal, {\n * errorMessage: 'Oh no!',\n * errorCode: 'ERR_OH_NO'\n * })\n * ```\n *\n * @example Only resolving on specific events\n *\n * Where multiple events with the same type are emitted, a `filter` function can\n * be passed to only resolve on one of them:\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * // throws a Error: Oh no!\n * const resolve = await raceEvent(emitter, 'event', controller.signal, {\n * filter: (evt: Event) => {\n * return evt.detail.foo === 'bar'\n * }\n * })\n * ```\n *\n * @example Terminating early by throwing from the filter\n *\n * You can cause listening for the event to cease and all event listeners to be\n * removed by throwing from the filter:\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * // throws Error: Cannot continue\n * const resolve = await raceEvent(emitter, 'event', controller.signal, {\n * filter: (evt) => {\n * if (...reasons) {\n * throw new Error('Cannot continue')\n * }\n *\n * return true\n * }\n * })\n * ```\n */\n\nimport { AbortError } from 'abort-error'\nimport type { EventEmitter } from 'node:events'\n\nexport interface RaceEventOptions<T> {\n /**\n * The message for the error thrown if the signal aborts\n */\n errorMessage?: string\n\n /**\n * The code for the error thrown if the signal aborts\n */\n errorCode?: string\n\n /**\n * The name of an event emitted on the emitter that should cause the returned\n * promise to reject. The rejection reason will be the `.detail` field of the\n * event.\n *\n * @default \"error\"\n */\n errorEvent?: string\n\n /**\n * If the 'errorEvent' option has been passed, and the emitted event has no\n * `.detail` field, reject the promise with this error instead.\n */\n error?: Error\n\n /**\n * When multiple events with the same name may be emitted, pass a filter\n * function here to allow ignoring ones that should not cause the returned\n * promise to resolve.\n */\n filter?(evt: T): boolean\n}\n\n/**\n * Race a promise against an abort signal\n */\nexport async function raceEvent <T> (emitter: EventTarget | EventEmitter, eventName: string, signal?: AbortSignal, opts?: RaceEventOptions<T>): Promise<T> {\n // create the error here so we have more context in the stack trace\n const error = new AbortError(opts?.errorMessage)\n\n if (opts?.errorCode != null) {\n // @ts-expect-error not a field of AbortError\n error.code = opts.errorCode\n }\n\n const errorEvent = opts?.errorEvent ?? 'error'\n\n if (signal?.aborted === true) {\n return Promise.reject(error)\n }\n\n return new Promise((resolve, reject) => {\n function removeListeners (): void {\n removeListener(signal, 'abort', abortListener)\n removeListener(emitter, eventName, eventListener)\n removeListener(emitter, errorEvent, errorEventListener)\n }\n\n const eventListener = (evt: any): void => {\n try {\n if (opts?.filter?.(evt) === false) {\n return\n }\n } catch (err: any) {\n removeListeners()\n reject(err)\n return\n }\n\n removeListeners()\n resolve(evt)\n }\n\n const errorEventListener = (evt: any): void => {\n removeListeners()\n\n if (evt instanceof Error) {\n reject(evt)\n return\n }\n\n reject(evt.detail ?? opts?.error ?? new Error(`The \"${opts?.errorEvent}\" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))\n }\n\n const abortListener = (): void => {\n removeListeners()\n reject(error)\n }\n\n addListener(signal, 'abort', abortListener)\n addListener(emitter, eventName, eventListener)\n addListener(emitter, errorEvent, errorEventListener)\n })\n}\n\nfunction addListener (emitter: EventEmitter | EventTarget | undefined, event: string, listener: any): void {\n if (emitter == null) {\n return\n }\n\n if (isEventTarget(emitter)) {\n emitter.addEventListener(event, listener)\n } else {\n emitter.addListener(event, listener)\n }\n}\n\nfunction removeListener (emitter: EventEmitter | EventTarget | undefined, event: string, listener: any): void {\n if (emitter == null) {\n return\n }\n\n if (isEventTarget(emitter)) {\n emitter.removeEventListener(event, listener)\n } else {\n emitter.removeListener(event, listener)\n }\n}\n\nfunction isEventTarget (emitter: any): emitter is EventTarget {\n return typeof emitter.addEventListener === 'function' && typeof emitter.removeEventListener === 'function'\n}\n", "export class QueueFullError extends Error {\n static name = 'QueueFullError'\n\n constructor (message: string = 'The queue was full') {\n super(message)\n this.name = 'QueueFullError'\n }\n}\n", "import { AbortError } from 'abort-error'\n\nexport class JobRecipient<JobReturnType> {\n public deferred: PromiseWithResolvers<JobReturnType>\n public signal?: AbortSignal\n\n constructor (signal?: AbortSignal) {\n this.signal = signal\n this.deferred = Promise.withResolvers()\n\n this.onAbort = this.onAbort.bind(this)\n this.signal?.addEventListener('abort', this.onAbort)\n }\n\n onAbort (): void {\n this.deferred.reject(this.signal?.reason ?? new AbortError())\n }\n\n cleanup (): void {\n this.signal?.removeEventListener('abort', this.onAbort)\n }\n}\n", "import { AbortError } from 'abort-error'\nimport { setMaxListeners } from 'main-event'\nimport { raceSignal } from 'race-signal'\nimport { JobRecipient } from './recipient.ts'\nimport type { JobStatus } from './index.ts'\nimport type { AbortOptions } from 'abort-error'\n\n/**\n * Returns a random string\n */\nfunction randomId (): string {\n return `${(parseInt(String(Math.random() * 1e9), 10)).toString()}${Date.now()}`\n}\n\nexport interface JobTimeline {\n created: number\n started?: number\n finished?: number\n}\n\nexport class Job <JobOptions extends AbortOptions = AbortOptions, JobReturnType = unknown> {\n public id: string\n public fn: (options: JobOptions) => Promise<JobReturnType>\n public options: JobOptions\n public recipients: Array<JobRecipient<JobReturnType>>\n public status: JobStatus\n public readonly timeline: JobTimeline\n private readonly controller: AbortController\n\n constructor (fn: (options: JobOptions) => Promise<JobReturnType>, options: any) {\n this.id = randomId()\n this.status = 'queued'\n this.fn = fn\n this.options = options\n this.recipients = []\n this.timeline = {\n created: Date.now()\n }\n\n this.controller = new AbortController()\n setMaxListeners(Infinity, this.controller.signal)\n\n this.onAbort = this.onAbort.bind(this)\n }\n\n abort (err: Error): void {\n this.controller.abort(err)\n }\n\n onAbort (): void {\n const allAborted = this.recipients.reduce((acc, curr) => {\n return acc && (curr.signal?.aborted === true)\n }, true)\n\n // if all recipients have aborted the job, actually abort the job\n if (allAborted) {\n this.controller.abort(new AbortError())\n this.cleanup()\n }\n }\n\n async join (options: AbortOptions = {}): Promise<JobReturnType> {\n const recipient = new JobRecipient<JobReturnType>(options.signal)\n this.recipients.push(recipient)\n\n options.signal?.addEventListener('abort', this.onAbort)\n\n return recipient.deferred.promise\n }\n\n async run (): Promise<void> {\n this.status = 'running'\n this.timeline.started = Date.now()\n\n try {\n this.controller.signal.throwIfAborted()\n\n const result = await raceSignal(this.fn({\n ...(this.options ?? {}),\n signal: this.controller.signal\n }), this.controller.signal)\n\n this.recipients.forEach(recipient => {\n recipient.deferred.resolve(result)\n })\n\n this.status = 'complete'\n } catch (err) {\n this.recipients.forEach(recipient => {\n recipient.deferred.reject(err)\n })\n\n this.status = 'errored'\n } finally {\n this.timeline.finished = Date.now()\n this.cleanup()\n }\n }\n\n cleanup (): void {\n this.recipients.forEach(recipient => {\n recipient.cleanup()\n recipient.signal?.removeEventListener('abort', this.onAbort)\n })\n }\n}\n", "/**\n * A function with additional start/stop methods\n */\nexport interface DebouncedFunction {\n (): void\n\n start(): void\n stop(): void\n}\n\n/**\n * Returns a function wrapper that will only call the passed function once\n *\n * Important - the passed function should not throw or reject\n */\nexport function debounce (func: () => void | Promise<void>, wait: number): DebouncedFunction {\n let timeout: ReturnType<typeof setTimeout> | undefined\n\n const output = function (): void {\n const later = function (): void {\n timeout = undefined\n void func()\n }\n\n clearTimeout(timeout)\n timeout = setTimeout(later, wait)\n }\n output.start = (): void => {}\n output.stop = (): void => {\n clearTimeout(timeout)\n }\n\n return output\n}\n", "/**\n * @packageDocumentation\n *\n * Based on `p-queue` but with access to the underlying queue, aborting a task\n * removes it from the queue and you can iterate over the queue results.\n *\n * @example\n *\n * ```ts\n * import all from 'it-all'\n * import { Queue } from 'it-queue'\n *\n * const queue = new Queue({\n * concurrency: Infinity\n * })\n * void queue.add(async () => {\n * return 'hello'\n * })\n * void queue.add(async () => {\n * return 'world'\n * })\n *\n * const results = await all(queue)\n * // ['hello', 'world']\n *\n * // how many items are in the queue (includes running items)\n * console.info(queue.size)\n *\n * // how many items are running\n * console.info(queue.running)\n *\n * // how many items have not started running yet\n * console.info(queue.queued)\n * ```\n */\n\nimport { AbortError } from 'abort-error'\nimport { pushable } from 'it-pushable'\nimport { TypedEventEmitter } from 'main-event'\nimport { raceEvent } from 'race-event'\nimport { QueueFullError } from './errors.ts'\nimport { Job } from './job.ts'\nimport { debounce } from './utils.ts'\nimport type { AbortOptions } from 'abort-error'\nexport type { Job, JobTimeline } from './job.ts'\nexport type { JobRecipient } from './recipient.ts'\n\nexport interface Comparator<T> {\n (a: T, b: T): -1 | 0 | 1\n}\n\nexport interface QueueInit<JobReturnType, JobOptions extends AbortOptions = AbortOptions> {\n /**\n * Concurrency limit.\n *\n * Minimum: `1`.\n *\n * @default Infinity\n */\n concurrency?: number\n\n /**\n * If the queue size grows to larger than this number the promise returned\n * from the add function will reject\n *\n * @default Infinity\n */\n maxSize?: number\n\n /**\n * An optional function that will sort the queue after a job has been added\n */\n sort?: Comparator<Job<JobOptions, JobReturnType>>\n\n /**\n * If false, `.start` will need to be called to start processing jobs\n *\n * @default true\n */\n autoStart?: boolean\n}\n\nexport type JobStatus = 'queued' | 'running' | 'errored' | 'complete'\n\nexport interface RunFunction<Options extends AbortOptions = AbortOptions, ReturnType = void> {\n (options: Options): Promise<ReturnType>\n}\n\nexport interface JobMatcher<JobOptions extends AbortOptions = AbortOptions> {\n (options?: Partial<JobOptions>): boolean\n}\n\nexport interface QueueJobSuccess<JobReturnType, JobOptions extends AbortOptions = AbortOptions> {\n job: Job<JobOptions, JobReturnType>\n result: JobReturnType\n}\n\nexport interface QueueJobFailure<JobReturnType, JobOptions extends AbortOptions = AbortOptions> {\n job: Job<JobOptions, JobReturnType>\n error: Error\n}\n\nexport interface QueueEvents<JobReturnType, JobOptions extends AbortOptions = AbortOptions> {\n /**\n * A job is about to start running\n */\n active: CustomEvent\n\n /**\n * All jobs have finished and the queue is empty\n */\n idle: CustomEvent\n\n /**\n * The queue is empty, jobs may be running\n */\n empty: CustomEvent\n\n /**\n * A job was added to the queue\n */\n add: CustomEvent\n\n /**\n * A job has finished or failed\n */\n next: CustomEvent\n\n /**\n * Emitted just after `\"completed\", a job has finished successfully - this\n * event gives access to the job and it's result\n */\n success: CustomEvent<QueueJobSuccess<JobReturnType, JobOptions>>\n\n /**\n * A job has failed - this event gives access to the job and the thrown error\n */\n failure: CustomEvent<QueueJobFailure<JobReturnType, JobOptions>>\n}\n\n/**\n * Heavily influence by `p-queue` with the following differences:\n *\n * 1. Items remain at the head of the queue while they are running so `queue.size` includes `queue.pending` items - this is so interested parties can join the results of a queue item while it is running\n * 2. The options for a job are stored separately to the job in order for them to be modified while they are still in the queue\n * 3. If a job's abort signal fires before execution begins, it is removed from the queue immediately\n * 4. 'success'/'failure' events are emitted instead of 'error'/'complete'\n */\nexport class Queue<JobReturnType = unknown, JobOptions extends AbortOptions = AbortOptions> extends TypedEventEmitter<QueueEvents<JobReturnType, JobOptions>> {\n public concurrency: number\n public maxSize: number\n public queue: Array<Job<JobOptions, JobReturnType>>\n private pending: number\n private readonly sort?: Comparator<Job<JobOptions, JobReturnType>>\n private autoStart: boolean\n\n constructor (init: QueueInit<JobReturnType, JobOptions> = {}) {\n super()\n\n this.concurrency = init.concurrency ?? Number.POSITIVE_INFINITY\n this.maxSize = init.maxSize ?? Number.POSITIVE_INFINITY\n this.pending = 0\n this.autoStart = init.autoStart ?? true\n\n this.sort = init.sort\n this.queue = []\n\n this.emitEmpty = debounce(this.emitEmpty.bind(this), 1)\n this.emitIdle = debounce(this.emitIdle.bind(this), 1)\n }\n\n [Symbol.asyncIterator] (): AsyncGenerator<JobReturnType, void, unknown> {\n return this.toGenerator()\n }\n\n emitEmpty (): void {\n if (this.size !== 0) {\n return\n }\n\n this.safeDispatchEvent('empty')\n }\n\n emitIdle (): void {\n if (this.running !== 0) {\n return\n }\n\n this.safeDispatchEvent('idle')\n }\n\n private tryToStartAnother (): boolean {\n if (this.size === 0) {\n this.emitEmpty()\n\n if (this.running === 0) {\n this.emitIdle()\n }\n\n return false\n }\n\n if (this.pending < this.concurrency) {\n let job: Job<JobOptions, JobReturnType> | undefined\n\n for (const j of this.queue) {\n if (j.status === 'queued') {\n job = j\n break\n }\n }\n\n if (job == null) {\n return false\n }\n\n this.safeDispatchEvent('active')\n\n this.pending++\n\n void job.run()\n .finally(() => {\n // remove the job from the queue\n for (let i = 0; i < this.queue.length; i++) {\n if (this.queue[i] === job) {\n this.queue.splice(i, 1)\n break\n }\n }\n\n this.pending--\n this.safeDispatchEvent('next')\n if (this.autoStart) {\n this.tryToStartAnother()\n }\n })\n\n return true\n }\n\n return false\n }\n\n private enqueue (job: Job<JobOptions, JobReturnType>): void {\n this.queue.push(job)\n\n if (this.sort != null) {\n this.queue.sort(this.sort)\n }\n }\n\n /**\n * Start the queue. If the `autoStart` parameter passed to the constructor was\n * not `false` this is a no-op\n */\n start (): void {\n if (this.autoStart !== false) {\n return\n }\n\n this.autoStart = true\n this.tryToStartAnother()\n }\n\n /**\n * Prevent further jobs from running - call `.start` to start the queue again\n */\n pause (): void {\n this.autoStart = false\n }\n\n /**\n * Adds a sync or async task to the queue. Always returns a promise.\n */\n async add (fn: RunFunction<JobOptions, JobReturnType>, options?: JobOptions): Promise<JobReturnType> {\n options?.signal?.throwIfAborted()\n\n if (this.size === this.maxSize) {\n throw new QueueFullError()\n }\n\n const job = new Job<JobOptions, JobReturnType>(fn, options)\n this.enqueue(job)\n this.safeDispatchEvent('add')\n\n if (this.autoStart) {\n this.tryToStartAnother()\n }\n\n return job.join(options)\n .then(result => {\n this.safeDispatchEvent('success', { detail: { job, result } })\n\n return result\n })\n .catch(err => {\n if (job.status === 'queued') {\n // job was aborted before it started - remove the job from the queue\n for (let i = 0; i < this.queue.length; i++) {\n if (this.queue[i] === job) {\n this.queue.splice(i, 1)\n break\n }\n }\n }\n\n this.safeDispatchEvent('failure', { detail: { job, error: err } })\n\n throw err\n })\n }\n\n /**\n * Clear the queue\n */\n clear (): void {\n this.queue.splice(0, this.queue.length)\n }\n\n /**\n * Abort all jobs in the queue and clear it\n */\n abort (): void {\n this.queue.forEach(job => {\n job.abort(new AbortError())\n })\n\n this.clear()\n }\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 (options?: AbortOptions): Promise<void> {\n // Instantly resolve if the queue is empty\n if (this.size === 0) {\n return\n }\n\n await raceEvent(this, 'empty', options?.signal)\n }\n\n /**\n * @returns A promise that settles when the queue size is less than the given\n * limit: `queue.size < limit`.\n *\n * If you want to avoid having the queue grow beyond a certain size you can\n * `await queue.onSizeLessThan()` before adding a new item.\n *\n * Note that this only limits the number of items waiting to start. There\n * could still be up to `concurrency` jobs already running that this call does\n * not include in its calculation.\n */\n async onSizeLessThan (limit: number, options?: AbortOptions): Promise<void> {\n // Instantly resolve if the queue is empty.\n if (this.size < limit) {\n return\n }\n\n await raceEvent(this, 'next', options?.signal, {\n filter: () => this.size < limit\n })\n }\n\n /**\n * The difference with `.onEmpty` is that `.onIdle` guarantees that all work\n * from the queue has finished. `.onEmpty` merely signals that the queue is\n * 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\n * promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle (options?: AbortOptions): Promise<void> {\n // Instantly resolve if none pending and if nothing else is queued\n if (this.pending === 0 && this.size === 0) {\n return\n }\n\n await raceEvent(this, 'idle', options?.signal)\n }\n\n /**\n * Size of the queue including running items\n */\n get size (): number {\n return this.queue.length\n }\n\n /**\n * The number of queued items waiting to run.\n */\n get queued (): number {\n return this.queue.length - this.pending\n }\n\n /**\n * The number of items currently running.\n */\n get running (): number {\n return this.pending\n }\n\n /**\n * Returns an async generator that makes it easy to iterate over the results\n * of jobs added to the queue.\n *\n * The generator will end when the queue becomes idle, that is there are no\n * jobs running and no jobs that have yet to run.\n *\n * If you need to keep the queue open indefinitely, consider using it-pushable\n * instead.\n */\n async * toGenerator (options?: AbortOptions): AsyncGenerator<JobReturnType, void, unknown> {\n options?.signal?.throwIfAborted()\n\n const stream = pushable<JobReturnType>({\n objectMode: true\n })\n\n const cleanup = (err?: Error): void => {\n if (err != null) {\n this.abort()\n } else {\n this.clear()\n }\n\n stream.end(err)\n }\n\n const onQueueJobComplete = (evt: CustomEvent<QueueJobSuccess<JobReturnType, JobOptions>>): void => {\n if (evt.detail != null) {\n stream.push(evt.detail.result)\n }\n }\n\n const onQueueError = (evt: CustomEvent<QueueJobFailure<JobReturnType, JobOptions>>): void => {\n cleanup(evt.detail.error)\n }\n\n const onQueueIdle = (): void => {\n cleanup()\n }\n\n // clear the queue and throw if the query is aborted\n const onSignalAbort = (): void => {\n cleanup(new AbortError('Queue aborted'))\n }\n\n // add listeners\n this.addEventListener('success', onQueueJobComplete)\n this.addEventListener('failure', onQueueError)\n this.addEventListener('idle', onQueueIdle)\n options?.signal?.addEventListener('abort', onSignalAbort)\n\n try {\n yield * stream\n } finally {\n // remove listeners\n this.removeEventListener('success', onQueueJobComplete)\n this.removeEventListener('failure', onQueueError)\n this.removeEventListener('idle', onQueueIdle)\n options?.signal?.removeEventListener('abort', onSignalAbort)\n\n // empty the queue for when the user has broken out of a loop early\n cleanup()\n }\n }\n}\n", "export const WORKER_REQUEST_READ_LOCK = 'lock:worker:request-read'\nexport const WORKER_ABORT_READ_LOCK_REQUEST = 'lock:worker:abort-read-request'\nexport const WORKER_RELEASE_READ_LOCK = 'lock:worker:release-read'\nexport const MASTER_GRANT_READ_LOCK = 'lock:master:grant-read'\nexport const MASTER_READ_LOCK_ERROR = 'lock:master:error-read'\n\nexport const WORKER_REQUEST_WRITE_LOCK = 'lock:worker:request-write'\nexport const WORKER_ABORT_WRITE_LOCK_REQUEST = 'lock:worker:abort-write-request'\nexport const WORKER_RELEASE_WRITE_LOCK = 'lock:worker:release-write'\nexport const MASTER_GRANT_WRITE_LOCK = 'lock:master:grant-write'\nexport const MASTER_WRITE_LOCK_ERROR = 'lock:master:error-write'\n\nexport const WORKER_FINALIZE = 'lock:worker:finalize'\n\nexport const BROADCAST_CHANNEL_NAME = 'mortice'\n\nexport const defaultOptions = {\n singleProcess: false\n}\n", "import {\n WORKER_FINALIZE\n} from '../constants.js'\nimport type { AbortEventData, AbortRequestType, FinalizeEventData, MorticeEvents, RequestType } from '../mortice.js'\nimport type { TypedEventTarget } from 'main-event'\n\nexport const handleChannelWorkerLockRequest = (emitter: TypedEventTarget<MorticeEvents>, channel: BroadcastChannel, masterEvent: RequestType, abortMasterEvent: AbortRequestType, requestType: string, abortType: string, errorType: string, releaseType: string, grantType: string) => {\n return (event: MessageEvent) => {\n if (event.data == null) {\n return\n }\n\n const requestEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n }\n\n // worker is requesting lock\n if (requestEvent.type === requestType) {\n emitter.safeDispatchEvent(masterEvent, {\n detail: {\n name: requestEvent.name,\n identifier: requestEvent.identifier,\n handler: async (): Promise<void> => {\n // grant lock to worker\n channel.postMessage({\n type: grantType,\n name: requestEvent.name,\n identifier: requestEvent.identifier\n })\n\n // wait for worker to finish\n await new Promise<void>((resolve) => {\n const releaseEventListener = (event: MessageEvent): void => {\n if (event?.data == null) {\n return\n }\n\n const releaseEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n }\n\n if (releaseEvent.type === releaseType && releaseEvent.identifier === requestEvent.identifier) {\n channel.removeEventListener('message', releaseEventListener)\n resolve()\n }\n }\n\n channel.addEventListener('message', releaseEventListener)\n })\n },\n onError: (err: Error) => {\n // send error to worker\n channel.postMessage({\n type: errorType,\n name: requestEvent.name,\n identifier: requestEvent.identifier,\n error: {\n message: err.message,\n name: err.name,\n stack: err.stack\n }\n })\n }\n }\n })\n }\n\n // worker is no longer interested in requesting the lock\n if (requestEvent.type === abortType) {\n emitter.safeDispatchEvent<AbortEventData>(abortMasterEvent, {\n detail: {\n name: requestEvent.name,\n identifier: requestEvent.identifier\n }\n })\n }\n\n // worker is done with lock\n if (requestEvent.type === WORKER_FINALIZE) {\n emitter.safeDispatchEvent<FinalizeEventData>('finalizeRequest', {\n detail: {\n name: requestEvent.name\n }\n })\n }\n }\n}\n", "export const nanoid = (size: number = 10): string => {\n return Math.random().toString().substring(2, size + 2)\n}\n", "import {\n WORKER_REQUEST_READ_LOCK,\n WORKER_RELEASE_READ_LOCK,\n MASTER_GRANT_READ_LOCK,\n WORKER_REQUEST_WRITE_LOCK,\n WORKER_RELEASE_WRITE_LOCK,\n MASTER_GRANT_WRITE_LOCK,\n WORKER_ABORT_READ_LOCK_REQUEST,\n WORKER_ABORT_WRITE_LOCK_REQUEST,\n MASTER_READ_LOCK_ERROR,\n MASTER_WRITE_LOCK_ERROR,\n WORKER_FINALIZE,\n BROADCAST_CHANNEL_NAME\n} from '../constants.js'\nimport { nanoid } from '../utils.js'\nimport type { Mortice, Release } from '../index.js'\nimport type { AbortOptions } from 'abort-error'\n\nexport class MorticeChannelWorker implements Mortice {\n private name: string\n private channel: BroadcastChannel\n\n constructor (name: string) {\n this.name = name\n this.channel = new BroadcastChannel(BROADCAST_CHANNEL_NAME)\n }\n\n readLock (options?: AbortOptions): Promise<Release> {\n return this.sendRequest(\n WORKER_REQUEST_READ_LOCK,\n WORKER_ABORT_READ_LOCK_REQUEST,\n MASTER_GRANT_READ_LOCK,\n MASTER_READ_LOCK_ERROR,\n WORKER_RELEASE_READ_LOCK,\n options\n )\n }\n\n writeLock (options?: AbortOptions): Promise<Release> {\n return this.sendRequest(\n WORKER_REQUEST_WRITE_LOCK,\n WORKER_ABORT_WRITE_LOCK_REQUEST,\n MASTER_GRANT_WRITE_LOCK,\n MASTER_WRITE_LOCK_ERROR,\n WORKER_RELEASE_WRITE_LOCK,\n options\n )\n }\n\n finalize (): void {\n this.channel.postMessage({\n type: WORKER_FINALIZE,\n name: this.name\n })\n\n this.channel.close()\n }\n\n private async sendRequest (requestType: string, abortType: string, grantType: string, errorType: string, releaseType: string, options?: AbortOptions): Promise<Release> {\n options?.signal?.throwIfAborted()\n const id = nanoid()\n\n this.channel.postMessage({\n type: requestType,\n identifier: id,\n name: this.name\n })\n\n return new Promise<Release>((resolve, reject) => {\n const abortListener = (): void => {\n this.channel.postMessage({\n type: abortType,\n identifier: id,\n name: this.name\n })\n }\n\n options?.signal?.addEventListener('abort', abortListener, {\n once: true\n })\n\n const listener = (event: MessageEvent): void => {\n if (event.data?.identifier !== id) {\n return\n }\n\n if (event.data?.type === grantType) {\n this.channel.removeEventListener('message', listener)\n options?.signal?.removeEventListener('abort', abortListener)\n\n // lock granted\n resolve(() => {\n // release lock\n this.channel.postMessage({\n type: releaseType,\n identifier: id,\n name: this.name\n })\n })\n }\n\n if (event.data.type === errorType) {\n this.channel.removeEventListener('message', listener)\n options?.signal?.removeEventListener('abort', abortListener)\n\n // error while waiting for grant of lock\n const err = new Error()\n\n if (event.data.error != null) {\n err.message = event.data.error.message\n err.name = event.data.error.name\n err.stack = event.data.error.stack\n }\n\n reject(err)\n }\n }\n\n this.channel.addEventListener('message', listener)\n })\n }\n}\n", "import { TypedEventEmitter } from 'main-event'\nimport {\n WORKER_REQUEST_READ_LOCK,\n WORKER_RELEASE_READ_LOCK,\n MASTER_GRANT_READ_LOCK,\n WORKER_REQUEST_WRITE_LOCK,\n WORKER_RELEASE_WRITE_LOCK,\n MASTER_GRANT_WRITE_LOCK,\n WORKER_ABORT_READ_LOCK_REQUEST,\n WORKER_ABORT_WRITE_LOCK_REQUEST,\n MASTER_READ_LOCK_ERROR,\n MASTER_WRITE_LOCK_ERROR,\n BROADCAST_CHANNEL_NAME,\n defaultOptions\n} from './constants.js'\nimport { handleChannelWorkerLockRequest } from './main/channel.ts'\nimport { MorticeChannelWorker } from './workers/channel.ts'\nimport type { Mortice, MorticeOptions } from './index.js'\nimport type { MorticeEvents } from './mortice.js'\nimport type { TypedEventTarget } from 'main-event'\n\nexport default (options: Required<MorticeOptions>): Mortice | TypedEventTarget<MorticeEvents> => {\n options = Object.assign({}, defaultOptions, options)\n const isPrimary = Boolean(globalThis.document) || options.singleProcess\n\n if (isPrimary) {\n const channel = new BroadcastChannel(BROADCAST_CHANNEL_NAME)\n const emitter = new TypedEventEmitter<MorticeEvents>()\n\n channel.addEventListener('message', handleChannelWorkerLockRequest(\n emitter,\n channel,\n 'requestReadLock',\n 'abortReadLockRequest',\n WORKER_REQUEST_READ_LOCK,\n WORKER_ABORT_READ_LOCK_REQUEST,\n MASTER_READ_LOCK_ERROR,\n WORKER_RELEASE_READ_LOCK,\n MASTER_GRANT_READ_LOCK\n ))\n channel.addEventListener('message', handleChannelWorkerLockRequest(\n emitter,\n channel,\n 'requestWriteLock',\n 'abortWriteLockRequest',\n WORKER_REQUEST_WRITE_LOCK,\n WORKER_ABORT_WRITE_LOCK_REQUEST,\n MASTER_WRITE_LOCK_ERROR,\n WORKER_RELEASE_WRITE_LOCK,\n MASTER_GRANT_WRITE_LOCK\n ))\n\n return emitter\n }\n\n return new MorticeChannelWorker(options.name)\n}\n", "import { AbortError } from 'abort-error'\nimport { Queue } from 'it-queue'\nimport impl from './node.js'\nimport type { Mortice, MorticeOptions, Release } from './index.js'\nimport type { AbortOptions } from 'abort-error'\nimport type { TypedEventTarget } from 'main-event'\n\nexport type RequestType = 'requestReadLock' | 'requestWriteLock'\nexport type AbortRequestType = 'abortReadLockRequest' | 'abortWriteLockRequest'\nexport type FinalizeRequestType = 'finalizeRequest'\n\nexport interface RequestEventData {\n name: string\n identifier: string\n handler(): Promise<void>\n onError(err: Error): void\n}\n\nexport interface RequestEvent {\n type: string\n identifier: string\n name: string,\n error?: {\n name: string\n message: string\n stack: string\n }\n}\n\nexport interface AbortEventData {\n name: string\n identifier: string\n}\n\nexport interface FinalizeEventData {\n name: string\n}\n\nexport interface MorticeEvents {\n requestReadLock: CustomEvent<RequestEventData>\n abortReadLockRequest: CustomEvent<AbortEventData>\n requestWriteLock: CustomEvent<RequestEventData>\n abortWriteLockRequest: CustomEvent<AbortEventData>\n finalizeRequest: CustomEvent<FinalizeEventData>\n}\n\nconst mutexes: Map<string, Mortice> = new Map()\nlet implementation: Mortice | TypedEventTarget<MorticeEvents>\n\nexport function isMortice (obj?: any): obj is Mortice {\n return typeof obj?.readLock === 'function' && typeof obj?.writeLock === 'function'\n}\n\nexport function getImplementation (opts: Required<MorticeOptions>): Mortice | TypedEventTarget<MorticeEvents> {\n if (implementation == null) {\n implementation = impl(opts)\n\n if (!isMortice(implementation)) {\n const emitter = implementation\n\n // we are master, set up worker requests\n emitter.addEventListener('requestReadLock', (event: CustomEvent<RequestEventData>) => {\n const mutexName = event.detail.name\n const identifier = event.detail.identifier\n const mutex = mutexes.get(mutexName)\n\n if (mutex == null) {\n return\n }\n\n const abortController = new AbortController()\n\n const abortListener = (event: CustomEvent<AbortEventData>): void => {\n if (event.detail.name !== mutexName || event.detail.identifier !== identifier) {\n return\n }\n\n abortController.abort()\n }\n\n emitter.addEventListener('abortReadLockRequest', abortListener)\n\n void mutex.readLock({\n signal: abortController.signal\n })\n .then(async release => {\n await event.detail.handler()\n .finally(() => {\n release()\n })\n })\n .catch(err => {\n event.detail.onError(err)\n })\n .finally(() => {\n emitter.removeEventListener('abortReadLockRequest', abortListener)\n })\n })\n\n emitter.addEventListener('requestWriteLock', (event: CustomEvent<RequestEventData>) => {\n const mutexName = event.detail.name\n const identifier = event.detail.identifier\n const mutex = mutexes.get(mutexName)\n\n if (mutex == null) {\n return\n }\n\n const abortController = new AbortController()\n\n const abortListener = (event: CustomEvent<AbortEventData>): void => {\n if (event.detail.name !== mutexName || event.detail.identifier !== identifier) {\n return\n }\n\n abortController.abort()\n }\n\n emitter.addEventListener('abortWriteLockRequest', abortListener)\n\n void mutex.writeLock({\n signal: abortController.signal\n })\n .then(async release => {\n await event.detail.handler()\n .finally(() => {\n release()\n })\n })\n .catch(err => {\n event.detail.onError(err)\n })\n .finally(() => {\n emitter.removeEventListener('abortWriteLockRequest', abortListener)\n })\n })\n\n emitter.addEventListener('finalizeRequest', (event: CustomEvent<FinalizeEventData>): void => {\n const mutexName = event.detail.name\n const mutex = mutexes.get(mutexName)\n\n if (mutex == null) {\n return\n }\n\n mutex.finalize()\n })\n }\n }\n\n return implementation\n}\n\nasync function createReleasable (queue: Queue, options?: AbortOptions): Promise<Release> {\n let res: (release: Release) => void\n let rej: (err: Error) => void\n\n const p = new Promise<Release>((resolve, reject) => {\n res = resolve\n rej = reject\n })\n\n const listener = (): void => {\n rej(new AbortError())\n }\n\n options?.signal?.addEventListener('abort', listener, {\n once: true\n })\n\n queue.add(async () => {\n await new Promise<void>((resolve) => {\n res(() => {\n options?.signal?.removeEventListener('abort', listener)\n resolve()\n })\n })\n }, {\n signal: options?.signal\n })\n .catch((err) => {\n rej(err)\n })\n\n return p\n}\n\nexport const createMutex = (name: string, options: Required<MorticeOptions>): Mortice => {\n let mutex = mutexes.get(name)\n\n if (mutex != null) {\n return mutex\n }\n\n const implementation = getImplementation(options)\n\n // a Mortice instance will be returned if we are a worker, otherwise if we are\n // primary an event target will be returned that fires events when workers\n // request a lock\n if (isMortice(implementation)) {\n mutex = implementation\n\n mutexes.set(name, mutex)\n\n return mutex\n }\n\n const masterQueue = new Queue({\n concurrency: 1\n })\n let readQueue: Queue | null\n\n mutex = {\n async readLock (opts?: AbortOptions) {\n // If there's already a read queue, just add the task to it\n if (readQueue != null) {\n return createReleasable(readQueue, opts)\n }\n\n // Create a new read queue\n readQueue = new Queue({\n concurrency: options.concurrency,\n autoStart: false\n })\n const localReadQueue = readQueue\n\n // Add the task to the read queue\n const readPromise = createReleasable(readQueue, opts)\n\n void masterQueue.add(async () => {\n // Start the task only once the master queue has completed processing\n // any previous tasks\n localReadQueue.start()\n\n // Once all the tasks in the read queue have completed, remove it so\n // that the next read lock will occur after any write locks that were\n // started in the interim\n await localReadQueue.onIdle()\n .then(() => {\n if (readQueue === localReadQueue) {\n readQueue = null\n }\n })\n })\n\n return readPromise\n },\n async writeLock (opts?: AbortOptions) {\n // Remove the read queue reference, so that any later read locks will be\n // added to a new queue that starts after this write lock has been\n // released\n readQueue = null\n\n return createReleasable(masterQueue, opts)\n },\n finalize: () => {\n mutexes.delete(name)\n },\n queue: masterQueue\n }\n\n mutexes.set(name, mutex)\n\n // if requested, finalize the lock once the last lock holder has released it\n if (options.autoFinalize === true) {\n masterQueue.addEventListener('idle', () => {\n mutex.finalize()\n }, {\n once: true\n })\n }\n\n return mutex\n}\n", "/**\n * @packageDocumentation\n *\n * - Reads occur concurrently\n * - Writes occur one at a time\n * - No reads occur while a write operation is in progress\n * - Locks can be created with different names\n * - Reads/writes can time out\n *\n * @example\n *\n * ```ts\n * import mortice from 'mortice'\n * import delay from 'delay'\n *\n * // the lock name & options objects are both optional\n * const mutex = mortice()\n *\n * Promise.all([\n * (async () => {\n * const release = await mutex.readLock()\n *\n * try {\n * console.info('read 1')\n * } finally {\n * release()\n * }\n * })(),\n * (async () => {\n * const release = await mutex.readLock()\n *\n * try {\n * console.info('read 2')\n * } finally {\n * release()\n * }\n * })(),\n * (async () => {\n * const release = await mutex.writeLock()\n *\n * try {\n * await delay(1000)\n *\n * console.info('write 1')\n * } finally {\n * release()\n * }\n * })(),\n * (async () => {\n * const release = await mutex.readLock()\n *\n * try {\n * console.info('read 3')\n * } finally {\n * release()\n * }\n * })()\n * ])\n * ```\n *\n * read 1\n * read 2\n * <small pause>\n * write 1\n * read 3\n *\n * ## Clean up\n *\n * Mutexes are stored globally reference by name, this is so you can obtain the\n * same lock from different contexts, including workers.\n *\n * When a mutex is no longer required, the `.finalize` function should be called\n * to remove any internal references to it.\n *\n * ```ts\n * import mortice from 'mortice'\n *\n * const mutex = mortice()\n *\n * // ...some time later\n *\n * mutex.finalize()\n * ```\n *\n * ## Auto clean up\n *\n * If your app generates a lot of short-lived mutexes and you want to clean them\n * up after the last lock has been released, pass the `autoFinalize` option to\n * mortice in the owning context:\n *\n ```ts\n * import mortice from 'mortice'\n *\n * const mutex = mortice({\n * autoFinalize: true\n * })\n *\n * const release = await mutex.readLock()\n * // ...some time later\n *\n * release()\n *\n * // mutex will be freed soon after\n * ```\n *\n * ## React native support\n *\n * This module should run on react native but it only supports single-process\n * concurrency as it's not clear to the author (disclaimer - not a react native\n * dev) what the officially supported process concurrency model is.\n *\n * Please open an issue if this is a feature you would like to see added.\n */\n\nimport { Queue } from 'it-queue'\nimport { createMutex } from './mortice.ts'\nimport type { AbortOptions } from 'abort-error'\n\nexport interface MorticeOptions {\n /**\n * An optional name for the lock\n */\n name?: string\n\n /**\n * How many read operations are executed concurrently\n *\n * @default Infinity\n */\n concurrency?: number\n\n /**\n * By default the the lock will be held on the main thread and child/worker\n * processes will coordinate to share the lock.\n *\n * Set this to true if each main/child/worker thread should maintain it's own\n * lock with no coordination between them.\n *\n * @default false\n */\n singleProcess?: boolean\n\n /**\n * If true, the lock will be finalized after the last reader/writer releases\n * it.\n *\n * @default false\n */\n autoFinalize?: boolean\n}\n\nexport interface Mortice {\n /**\n * Acquire a read lock. Multiple reads will occur simultaneously up to the\n * concurrency limit passed to the constructor.\n */\n readLock(options?: AbortOptions): Promise<Release>\n\n /**\n * Acquire a write lock. The write lock will wait for any in-flight reads to\n * complete, then prevent any further reads or writes until the lock is\n * released.\n */\n writeLock(options?: AbortOptions): Promise<Release>\n\n /**\n * Removes this mutex from the global state, after invoking this method it\n * cannot be used any more.\n */\n finalize(): void\n\n /**\n * If this is the main thread, the state of the read/write queue may be\n * inspected here\n */\n queue?: Queue\n}\n\nexport interface Release {\n (): void\n}\n\nconst defaultOptions = {\n name: 'lock',\n concurrency: Infinity,\n singleProcess: false,\n autoFinalize: false\n}\n\nexport default function createMortice (options?: MorticeOptions): Mortice {\n const opts: Required<MorticeOptions> = Object.assign({}, defaultOptions, options)\n\n return createMutex(opts.name, opts)\n}\n", "import { start, stop } from '@libp2p/interface'\nimport createMortice from 'mortice'\nimport { BlockPinnedError } from './errors.ts'\nimport type { Routing } from '@helia/interface'\nimport type { Blocks, Pair, DeleteManyBlocksProgressEvents, DeleteBlockProgressEvents, GetBlockProgressEvents, GetManyBlocksProgressEvents, PutManyBlocksProgressEvents, PutBlockProgressEvents, GetAllBlocksProgressEvents, GetOfflineOptions, SessionBlockstore } from '@helia/interface'\nimport type { Pins } from '@helia/interface'\nimport type { AbortOptions, Startable } from '@libp2p/interface'\nimport type { Blockstore, InputPair } from 'interface-blockstore'\nimport type { Mortice } from 'mortice'\nimport type { CID } from 'multiformats/cid'\nimport type { ProgressOptions } from 'progress-events'\n\nexport interface BlockStorageInit {\n holdGcLock?: boolean\n}\n\nexport interface GetOptions extends AbortOptions {\n progress?(evt: Event): void\n}\n\n/**\n * BlockStorage is a hybrid blockstore that puts/gets blocks from a configured\n * blockstore (that may be on disk, s3, or something else). If the blocks are\n * not present Bitswap will be used to fetch them from network peers.\n */\nexport class BlockStorage implements Blocks, Startable {\n public lock: Mortice\n private readonly child: Blocks\n private readonly pins: Pins\n private readonly routing: Routing\n private started: boolean\n\n /**\n * Create a new BlockStorage\n */\n constructor (blockstore: Blocks, pins: Pins, routing: Routing, options: BlockStorageInit = {}) {\n this.child = blockstore\n this.pins = pins\n this.routing = routing\n this.lock = createMortice({\n singleProcess: options.holdGcLock\n })\n this.started = false\n }\n\n isStarted (): boolean {\n return this.started\n }\n\n async start (): Promise<void> {\n await start(this.child)\n this.started = true\n }\n\n async stop (): Promise<void> {\n await stop(this.child)\n this.started = false\n }\n\n unwrap (): Blockstore {\n return this.child\n }\n\n /**\n * Put a block to the underlying datastore\n */\n async put (cid: CID, block: Uint8Array, options: AbortOptions & ProgressOptions<PutBlockProgressEvents> = {}): Promise<CID> {\n options?.signal?.throwIfAborted()\n const releaseLock = await this.lock.readLock()\n\n try {\n return await this.child.put(cid, block, options)\n } finally {\n releaseLock()\n }\n }\n\n /**\n * Put a multiple blocks to the underlying datastore\n */\n async * putMany (blocks: Iterable<InputPair> | AsyncIterable<InputPair>, options: AbortOptions & ProgressOptions<PutManyBlocksProgressEvents> = {}): AsyncGenerator<CID> {\n options?.signal?.throwIfAborted()\n const releaseLock = await this.lock.readLock()\n\n try {\n yield * this.child.putMany(blocks, options)\n } finally {\n releaseLock()\n }\n }\n\n /**\n * Get a block by cid\n */\n async * get (cid: CID, options: GetOfflineOptions & AbortOptions & ProgressOptions<GetBlockProgressEvents> = {}): AsyncGenerator<Uint8Array> {\n options?.signal?.throwIfAborted()\n const releaseLock = await this.lock.readLock()\n\n try {\n yield * this.child.get(cid, options)\n } finally {\n releaseLock()\n }\n }\n\n /**\n * Get multiple blocks back from an (async) iterable of cids\n */\n async * getMany (cids: Iterable<CID> | AsyncIterable<CID>, options: GetOfflineOptions & AbortOptions & ProgressOptions<GetManyBlocksProgressEvents> = {}): AsyncGenerator<Pair> {\n options?.signal?.throwIfAborted()\n const releaseLock = await this.lock.readLock()\n\n try {\n yield * this.child.getMany(cids, options)\n } finally {\n releaseLock()\n }\n }\n\n /**\n * Delete a block from the blockstore\n */\n async delete (cid: CID, options: AbortOptions & ProgressOptions<DeleteBlockProgressEvents> = {}): Promise<void> {\n options?.signal?.throwIfAborted()\n const releaseLock = await this.lock.writeLock()\n\n try {\n if (await this.pins.isPinned(cid)) {\n throw new BlockPinnedError('Block was pinned - please unpin and try again')\n }\n\n // stop re-providing this CID if necessary\n await this.routing.cancelReprovide(cid, options)\n\n await this.child.delete(cid, options)\n } finally {\n releaseLock()\n }\n }\n\n /**\n * Delete multiple blocks from the blockstore\n */\n async * deleteMany (cids: Iterable<CID> | AsyncIterable<CID>, options: AbortOptions & ProgressOptions<DeleteManyBlocksProgressEvents> = {}): AsyncGenerator<CID> {\n options?.signal?.throwIfAborted()\n const releaseLock = await this.lock.writeLock()\n\n try {\n const storage = this\n\n yield * this.child.deleteMany((async function * (): AsyncGenerator<CID> {\n for await (const cid of cids) {\n if (await storage.pins.isPinned(cid)) {\n throw new BlockPinnedError('Block was pinned - please unpin and try again')\n }\n\n // stop re-providing this CID if necessary\n await storage.routing.cancelReprovide(cid, options)\n\n yield cid\n }\n }()), options)\n } finally {\n releaseLock()\n }\n }\n\n async has (cid: CID, options: AbortOptions = {}): Promise<boolean> {\n options?.signal?.throwIfAborted()\n const releaseLock = await this.lock.readLock()\n\n try {\n return await this.child.has(cid, options)\n } finally {\n releaseLock()\n }\n }\n\n async * getAll (options: AbortOptions & ProgressOptions<GetAllBlocksProgressEvents> = {}): AsyncGenerator<Pair> {\n options?.signal?.throwIfAborted()\n const releaseLock = await this.lock.readLock()\n\n try {\n yield * this.child.getAll(options)\n } finally {\n releaseLock()\n }\n }\n\n createSession (root: CID, options?: AbortOptions): SessionBlockstore {\n options?.signal?.throwIfAborted()\n return this.child.createSession(root, options)\n }\n}\n", "import { Key } from 'interface-datastore'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { InvalidDatastoreVersionError } from '../errors.ts'\nimport type { Datastore } from 'interface-datastore'\n\nconst DS_VERSION_KEY = new Key('/version')\nconst CURRENT_VERSION = 1\n\nexport async function assertDatastoreVersionIsCurrent (datastore: Datastore): Promise<void> {\n if (!(await datastore.has(DS_VERSION_KEY))) {\n await datastore.put(DS_VERSION_KEY, uint8ArrayFromString(`${CURRENT_VERSION}`))\n\n return\n }\n\n const buf = await datastore.get(DS_VERSION_KEY)\n const str = uint8ArrayToString(buf)\n const version = parseInt(str, 10)\n\n if (version !== CURRENT_VERSION) {\n // TODO: write migrations when we break compatibility - for an example, see https://github.com/ipfs/js-ipfs-repo/tree/master/packages/ipfs-repo-migrations\n throw new InvalidDatastoreVersionError('Invalid datastore version, a datastore migration may be required')\n }\n}\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\n/**\n * @param {Map<any, any>} map\n * @returns {null}\n */\nfunction mapEncoder (map) {\n for (const key of map.keys()) {\n if (typeof key !== 'string' || key.length === 0) {\n throw new Error('Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded')\n }\n }\n return null\n}\n\nconst _encodeOptions = {\n float64: true,\n typeEncoders: {\n Map: mapEncoder,\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 {import('cborg').TagDecodeControl} decode\n * @returns {CID}\n */\nfunction cidDecoder (decode) {\n const bytes = /** @type {Uint8Array} */ (decode())\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 {{ [tagNumber: number]: import('cborg').TagDecoder }} */\n tags: { [CID_CBOR_TAG]: cidDecoder }\n}\n\nexport const decodeOptions = {\n ..._decodeOptions,\n tags: { ..._decodeOptions.tags }\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", "/* eslint max-depth: [\"error\", 7] */\nimport { Token, Type } from 'cborg'\nimport * as cborgJson from 'cborg/json'\nimport { CID } from 'multiformats'\nimport { base64 } from 'multiformats/bases/base64'\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ByteView<T>} ByteView\n */\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ArrayBufferView<T>} ArrayBufferView\n */\n/**\n * @template T\n * @typedef {import('multiformats').ToString<T>} ToString\n */\n/**\n * @typedef {import('cborg/interface').DecodeTokenizer} DecodeTokenizer\n */\n\n/**\n * @template T\n * @param {ByteView<T> | ArrayBufferView<T>} buf\n * @returns {ByteView<T>}\n */\nfunction 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. Encoding a CID means replacing it with a `{\"/\":\"<CidString>}`\n * object as per the DAG-JSON spec.\n *\n * @param {any} obj\n * @returns {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 cidString = cid.toString()\n\n return [\n new Token(Type.map, Infinity, 1),\n new Token(Type.string, '/', 1), // key\n new Token(Type.string, cidString, cidString.length), // value\n new Token(Type.break, undefined, 1)\n ]\n}\n\n/**\n * bytesEncoder will receive all Uint8Arrays (and friends) during encode, it\n * needs to replace it with a `{\"/\":{\"bytes\":\"Base64ByteString\"}}` object as\n * per the DAG-JSON spec.\n *\n * @param {Uint8Array} bytes\n * @returns {Token[]|null}\n */\nfunction bytesEncoder (bytes) {\n const bytesString = base64.encode(bytes).slice(1) // no mbase prefix\n return [\n new Token(Type.map, Infinity, 1),\n new Token(Type.string, '/', 1), // key\n new Token(Type.map, Infinity, 1), // value\n new Token(Type.string, 'bytes', 5), // inner key\n new Token(Type.string, bytesString, bytesString.length), // inner value\n new Token(Type.break, undefined, 1),\n new Token(Type.break, undefined, 1)\n ]\n}\n\n/**\n * taBytesEncoder wraps bytesEncoder() but for the more exotic typed arrays so\n * that we access the underlying ArrayBuffer data\n *\n * @param {Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array|Float64Array|Uint8ClampedArray|BigInt64Array|BigUint64Array} obj\n * @returns {Token[]|null}\n */\nfunction taBytesEncoder (obj) {\n return bytesEncoder(new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))\n}\n\n/**\n * abBytesEncoder wraps bytesEncoder() but for plain ArrayBuffers\n *\n * @param {ArrayBuffer} ab\n * @returns {Token[]|null}\n */\nfunction abBytesEncoder (ab) {\n return bytesEncoder(new Uint8Array(ab))\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 // process with standard number encoder\n}\n\nconst encodeOptions = {\n typeEncoders: {\n Object: cidEncoder,\n Buffer: bytesEncoder,\n Uint8Array: bytesEncoder,\n Int8Array: taBytesEncoder,\n Uint16Array: taBytesEncoder,\n Int16Array: taBytesEncoder,\n Uint32Array: taBytesEncoder,\n Int32Array: taBytesEncoder,\n Float32Array: taBytesEncoder,\n Float64Array: taBytesEncoder,\n Uint8ClampedArray: taBytesEncoder,\n BigInt64Array: taBytesEncoder,\n BigUint64Array: taBytesEncoder,\n DataView: taBytesEncoder,\n ArrayBuffer: abBytesEncoder,\n undefined: undefinedEncoder,\n number: numberEncoder\n }\n}\n\n/**\n * @implements {DecodeTokenizer}\n */\nclass DagJsonTokenizer extends cborgJson.Tokenizer {\n /**\n * @param {Uint8Array} data\n * @param {object} [options]\n */\n constructor (data, options) {\n super(data, options)\n /** @type {Token[]} */\n this.tokenBuffer = []\n }\n\n /**\n * @returns {boolean}\n */\n done () {\n return this.tokenBuffer.length === 0 && super.done()\n }\n\n /**\n * @returns {Token}\n */\n _next () {\n if (this.tokenBuffer.length > 0) {\n // @ts-ignore https://github.com/Microsoft/TypeScript/issues/30406\n return this.tokenBuffer.pop()\n }\n return super.next()\n }\n\n /**\n * Implements rules outlined in https://github.com/ipld/specs/pull/356\n *\n * @returns {Token}\n */\n next () {\n const token = this._next()\n\n if (Type.equals(token.type, Type.map)) {\n const keyToken = this._next()\n if (Type.equals(keyToken.type, Type.string) && keyToken.value === '/') {\n const valueToken = this._next()\n if (Type.equals(valueToken.type, Type.string)) { // *must* be a CID\n const breakToken = this._next() // swallow the end-of-map token\n if (!Type.equals(breakToken.type, Type.break)) {\n throw new Error('Invalid encoded CID form')\n }\n this.tokenBuffer.push(valueToken) // CID.parse will pick this up after our tag token\n return new Token(Type.tag, 42, 0)\n }\n if (Type.equals(valueToken.type, Type.map)) {\n const innerKeyToken = this._next()\n if (Type.equals(innerKeyToken.type, Type.string) && innerKeyToken.value === 'bytes') {\n const innerValueToken = this._next()\n if (Type.equals(innerValueToken.type, Type.string)) { // *must* be Bytes\n for (let i = 0; i < 2; i++) {\n const breakToken = this._next() // swallow two end-of-map tokens\n if (!Type.equals(breakToken.type, Type.break)) {\n throw new Error('Invalid encoded Bytes form')\n }\n }\n const bytes = base64.decode(`m${innerValueToken.value}`)\n return new Token(Type.bytes, bytes, innerValueToken.value.length)\n }\n this.tokenBuffer.push(innerValueToken) // bail\n }\n this.tokenBuffer.push(innerKeyToken) // bail\n }\n this.tokenBuffer.push(valueToken) // bail\n }\n this.tokenBuffer.push(keyToken) // bail\n }\n return token\n }\n}\n\nconst decodeOptions = {\n allowIndefinite: false,\n allowUndefined: false,\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 {{ [tagNumber: number]: import('cborg').TagDecoder }} */\n tags: {\n // TAG(42)STRING(\"bafy...\") from the tokenizer, decode to get the string\n 42: (decode) => CID.parse(/** @type {string} */ (decode()))\n }\n}\n\nexport const name = 'dag-json'\nexport const code = 0x0129\n\n/**\n * @template T\n * @param {T} node\n * @returns {ByteView<T>}\n */\nexport const encode = (node) => cborgJson.encode(node, encodeOptions)\n\n/**\n * @template T\n * @param {ByteView<T> | ArrayBufferView<T>} data\n * @returns {T}\n */\nexport const decode = (data) => {\n const buf = toByteView(data)\n // the tokenizer is stateful so we need a single instance of it\n const options = Object.assign(decodeOptions, { tokenizer: new DagJsonTokenizer(buf, decodeOptions) })\n return cborgJson.decode(buf, options)\n}\n\n/**\n * @template T\n * @param {T} node\n * @returns {ToString<T>}\n */\nexport const format = (node) => utf8Decoder.decode(encode(node))\nexport { format as stringify }\nconst utf8Decoder = new TextDecoder()\n\n/**\n * @template T\n * @param {ToString<T>} data\n * @returns {T}\n */\nexport const parse = (data) => decode(utf8Encoder.encode(data))\nconst utf8Encoder = new TextEncoder()\n", "import { Type } from '../token.js'\nimport { encodeCustom } from '../encode.js'\nimport { encodeErrPrefix } from '../common.js'\nimport { asU8A, fromString } from '../byte-utils.js'\n\n/**\n * @typedef {import('../../interface.js').EncodeOptions} EncodeOptions\n * @typedef {import('../../interface.js').ByteWriter} ByteWriter\n * @typedef {import('../token.js').Token} Token\n */\n\nclass JSONEncoder extends Array {\n constructor () {\n super()\n /** @type {{type:Type,elements:number}[]} */\n this.inRecursive = []\n }\n\n /**\n * @param {ByteWriter} buf\n */\n prefix (buf) {\n const recurs = this.inRecursive[this.inRecursive.length - 1]\n if (recurs) {\n if (Type.equals(recurs.type, Type.array)) {\n recurs.elements++\n if (recurs.elements !== 1) { // >first\n buf.push([44]) // ','\n }\n }\n if (Type.equals(recurs.type, Type.map)) {\n recurs.elements++\n if (recurs.elements !== 1) { // >first\n if (recurs.elements % 2 === 1) { // key\n buf.push([44]) // ','\n } else {\n buf.push([58]) // ':'\n }\n }\n }\n }\n }\n\n /**\n * @param {ByteWriter} buf\n * @param {Token} token\n */\n [Type.uint.major] (buf, token) {\n this.prefix(buf)\n const is = String(token.value)\n const isa = []\n for (let i = 0; i < is.length; i++) {\n isa[i] = is.charCodeAt(i)\n }\n buf.push(isa)\n }\n\n /**\n * @param {ByteWriter} buf\n * @param {Token} token\n */\n [Type.negint.major] (buf, token) {\n // @ts-ignore hack\n this[Type.uint.major](buf, token)\n }\n\n /**\n * @param {ByteWriter} _buf\n * @param {Token} _token\n */\n [Type.bytes.major] (_buf, _token) {\n throw new Error(`${encodeErrPrefix} unsupported type: Uint8Array`)\n }\n\n /**\n * @param {ByteWriter} buf\n * @param {Token} token\n */\n [Type.string.major] (buf, token) {\n this.prefix(buf)\n // buf.push(34) // '\"'\n // encodeUtf8(token.value, byts)\n // buf.push(34) // '\"'\n const byts = fromString(JSON.stringify(token.value))\n buf.push(byts.length > 32 ? asU8A(byts) : byts)\n }\n\n /**\n * @param {ByteWriter} buf\n * @param {Token} _token\n */\n [Type.array.major] (buf, _token) {\n this.prefix(buf)\n this.inRecursive.push({ type: Type.array, elements: 0 })\n buf.push([91]) // '['\n }\n\n /**\n * @param {ByteWriter} buf\n * @param {Token} _token\n */\n [Type.map.major] (buf, _token) {\n this.prefix(buf)\n this.inRecursive.push({ type: Type.map, elements: 0 })\n buf.push([123]) // '{'\n }\n\n /**\n * @param {ByteWriter} _buf\n * @param {Token} _token\n */\n [Type.tag.major] (_buf, _token) {}\n\n /**\n * @param {ByteWriter} buf\n * @param {Token} token\n */\n [Type.float.major] (buf, token) {\n if (token.type.name === 'break') {\n const recurs = this.inRecursive.pop()\n if (recurs) {\n if (Type.equals(recurs.type, Type.array)) {\n buf.push([93]) // ']'\n } else if (Type.equals(recurs.type, Type.map)) {\n buf.push([125]) // '}'\n /* c8 ignore next 3 */\n } else {\n throw new Error('Unexpected recursive type; this should not happen!')\n }\n return\n }\n /* c8 ignore next 2 */\n throw new Error('Unexpected break; this should not happen!')\n }\n if (token.value === undefined) {\n throw new Error(`${encodeErrPrefix} unsupported type: undefined`)\n }\n\n this.prefix(buf)\n if (token.type.name === 'true') {\n buf.push([116, 114, 117, 101]) // 'true'\n return\n } else if (token.type.name === 'false') {\n buf.push([102, 97, 108, 115, 101]) // 'false'\n return\n } else if (token.type.name === 'null') {\n buf.push([110, 117, 108, 108]) // 'null'\n return\n }\n\n // number\n const is = String(token.value)\n const isa = []\n let dp = false\n for (let i = 0; i < is.length; i++) {\n isa[i] = is.charCodeAt(i)\n if (!dp && (isa[i] === 46 || isa[i] === 101 || isa[i] === 69)) { // '[.eE]'\n dp = true\n }\n }\n if (!dp) { // need a decimal point for floats\n isa.push(46) // '.'\n isa.push(48) // '0'\n }\n buf.push(isa)\n }\n}\n\n// The below code is mostly taken and modified from https://github.com/feross/buffer\n// Licensed MIT. Copyright (c) Feross Aboukhadijeh\n// function encodeUtf8 (string, byts) {\n// let codePoint\n// const length = string.length\n// let leadSurrogate = null\n\n// for (let i = 0; i < length; ++i) {\n// codePoint = string.charCodeAt(i)\n\n// // is surrogate component\n// if (codePoint > 0xd7ff && codePoint < 0xe000) {\n// // last char was a lead\n// if (!leadSurrogate) {\n// // no lead yet\n// /* c8 ignore next 9 */\n// if (codePoint > 0xdbff) {\n// // unexpected trail\n// byts.push(0xef, 0xbf, 0xbd)\n// continue\n// } else if (i + 1 === length) {\n// // unpaired lead\n// byts.push(0xef, 0xbf, 0xbd)\n// continue\n// }\n\n// // valid lead\n// leadSurrogate = codePoint\n\n// continue\n// }\n\n// // 2 leads in a row\n// /* c8 ignore next 5 */\n// if (codePoint < 0xdc00) {\n// byts.push(0xef, 0xbf, 0xbd)\n// leadSurrogate = codePoint\n// continue\n// }\n\n// // valid surrogate pair\n// codePoint = (leadSurrogate - 0xd800 << 10 | codePoint - 0xdc00) + 0x10000\n// /* c8 ignore next 4 */\n// } else if (leadSurrogate) {\n// // valid bmp char, but last char was a lead\n// byts.push(0xef, 0xbf, 0xbd)\n// }\n\n// leadSurrogate = null\n\n// // encode utf8\n// if (codePoint < 0x80) {\n// // special JSON escapes\n// switch (codePoint) {\n// case 8: // '\\b'\n// byts.push(92, 98) // '\\\\b'\n// continue\n// case 9: // '\\t'\n// byts.push(92, 116) // '\\\\t'\n// continue\n// case 10: // '\\n'\n// byts.push(92, 110) // '\\\\n'\n// continue\n// case 12: // '\\f'\n// byts.push(92, 102) // '\\\\f'\n// continue\n// case 13: // '\\r'\n// byts.push(92, 114) // '\\\\r'\n// continue\n// case 34: // '\"'\n// byts.push(92, 34) // '\\\\\"'\n// continue\n// case 92: // '\\\\'\n// byts.push(92, 92) // '\\\\\\\\'\n// continue\n// }\n\n// byts.push(codePoint)\n// } else if (codePoint < 0x800) {\n// /* c8 ignore next 1 */\n// byts.push(\n// codePoint >> 0x6 | 0xc0,\n// codePoint & 0x3f | 0x80\n// )\n// } else if (codePoint < 0x10000) {\n// /* c8 ignore next 1 */\n// byts.push(\n// codePoint >> 0xc | 0xe0,\n// codePoint >> 0x6 & 0x3f | 0x80,\n// codePoint & 0x3f | 0x80\n// )\n// /* c8 ignore next 9 */\n// } else if (codePoint < 0x110000) {\n// byts.push(\n// codePoint >> 0x12 | 0xf0,\n// codePoint >> 0xc & 0x3f | 0x80,\n// codePoint >> 0x6 & 0x3f | 0x80,\n// codePoint & 0x3f | 0x80\n// )\n// } else {\n// /* c8 ignore next 2 */\n// throw new Error('Invalid code point')\n// }\n// }\n// }\n\n/**\n * @param {(Token|Token[])[]} e1\n * @param {(Token|Token[])[]} e2\n * @returns {number}\n */\nfunction mapSorter (e1, e2) {\n if (Array.isArray(e1[0]) || Array.isArray(e2[0])) {\n throw new Error(`${encodeErrPrefix} complex map keys are not supported`)\n }\n const keyToken1 = e1[0]\n const keyToken2 = e2[0]\n if (keyToken1.type !== Type.string || keyToken2.type !== Type.string) {\n throw new Error(`${encodeErrPrefix} non-string map keys are not supported`)\n }\n if (keyToken1 < keyToken2) {\n return -1\n }\n if (keyToken1 > keyToken2) {\n return 1\n }\n /* c8 ignore next 1 */\n throw new Error(`${encodeErrPrefix} unexpected duplicate map keys, this is not supported`)\n}\n\nconst defaultEncodeOptions = { addBreakTokens: true, mapSorter }\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 // @ts-ignore TokenTypeEncoder[] requires compareTokens() on each encoder, we don't use them here\n return encodeCustom(data, new JSONEncoder(), options)\n}\n\nexport { encode }\n", "import { decode as _decode, decodeFirst as _decodeFirst } from '../decode.js'\nimport { Token, Type } from '../token.js'\nimport { decodeCodePointsArray } from '../byte-utils.js'\nimport { decodeErrPrefix } from '../common.js'\n\n/**\n * @typedef {import('../../interface.js').DecodeOptions} DecodeOptions\n * @typedef {import('../../interface.js').DecodeTokenizer} DecodeTokenizer\n */\n\n/**\n * @implements {DecodeTokenizer}\n */\nclass Tokenizer {\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 /** @type {string[]} */\n this.modeStack = ['value']\n this.lastToken = ''\n }\n\n pos () {\n return this._pos\n }\n\n /**\n * @returns {boolean}\n */\n done () {\n return this._pos >= this.data.length\n }\n\n /**\n * @returns {number}\n */\n ch () {\n return this.data[this._pos]\n }\n\n /**\n * @returns {string}\n */\n currentMode () {\n return this.modeStack[this.modeStack.length - 1]\n }\n\n skipWhitespace () {\n let c = this.ch()\n // @ts-ignore\n while (c === 32 /* ' ' */ || c === 9 /* '\\t' */ || c === 13 /* '\\r' */ || c === 10 /* '\\n' */) {\n c = this.data[++this._pos]\n }\n }\n\n /**\n * @param {number[]} str\n */\n expect (str) {\n if (this.data.length - this._pos < str.length) {\n throw new Error(`${decodeErrPrefix} unexpected end of input at position ${this._pos}`)\n }\n for (let i = 0; i < str.length; i++) {\n if (this.data[this._pos++] !== str[i]) {\n throw new Error(`${decodeErrPrefix} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...str)}'`)\n }\n }\n }\n\n parseNumber () {\n const startPos = this._pos\n let negative = false\n let float = false\n\n /**\n * @param {number[]} chars\n */\n const swallow = (chars) => {\n while (!this.done()) {\n const ch = this.ch()\n if (chars.includes(ch)) {\n this._pos++\n } else {\n break\n }\n }\n }\n\n // lead\n if (this.ch() === 45) { // '-'\n negative = true\n this._pos++\n }\n if (this.ch() === 48) { // '0'\n this._pos++\n if (this.ch() === 46) { // '.'\n this._pos++\n float = true\n } else {\n return new Token(Type.uint, 0, this._pos - startPos)\n }\n }\n swallow([48, 49, 50, 51, 52, 53, 54, 55, 56, 57]) // DIGIT\n if (negative && this._pos === startPos + 1) {\n throw new Error(`${decodeErrPrefix} unexpected token at position ${this._pos}`)\n }\n if (!this.done() && this.ch() === 46) { // '.'\n if (float) {\n throw new Error(`${decodeErrPrefix} unexpected token at position ${this._pos}`)\n }\n float = true\n this._pos++\n swallow([48, 49, 50, 51, 52, 53, 54, 55, 56, 57]) // DIGIT\n }\n if (!this.done() && (this.ch() === 101 || this.ch() === 69)) { // '[eE]'\n float = true\n this._pos++\n if (!this.done() && (this.ch() === 43 || this.ch() === 45)) { // '+', '-'\n this._pos++\n }\n swallow([48, 49, 50, 51, 52, 53, 54, 55, 56, 57]) // DIGIT\n }\n // @ts-ignore\n const numStr = String.fromCharCode.apply(null, this.data.subarray(startPos, this._pos))\n const num = parseFloat(numStr)\n if (float) {\n return new Token(Type.float, num, this._pos - startPos)\n }\n if (this.options.allowBigInt !== true || Number.isSafeInteger(num)) {\n return new Token(num >= 0 ? Type.uint : Type.negint, num, this._pos - startPos)\n }\n return new Token(num >= 0 ? Type.uint : Type.negint, BigInt(numStr), this._pos - startPos)\n }\n\n /**\n * @returns {Token}\n */\n parseString () {\n /* c8 ignore next 4 */\n if (this.ch() !== 34) { // '\"'\n // this would be a programming error\n throw new Error(`${decodeErrPrefix} unexpected character at position ${this._pos}; this shouldn't happen`)\n }\n this._pos++\n\n // check for simple fast-path, all printable ascii, no escapes\n // >0x10000 elements may fail fn.apply() (http://stackoverflow.com/a/22747272/680742)\n for (let i = this._pos, l = 0; i < this.data.length && l < 0x10000; i++, l++) {\n const ch = this.data[i]\n if (ch === 92 || ch < 32 || ch >= 128) { // '\\', ' ', control-chars or non-trivial\n break\n }\n if (ch === 34) { // '\"'\n // @ts-ignore\n const str = String.fromCharCode.apply(null, this.data.subarray(this._pos, i))\n this._pos = i + 1\n return new Token(Type.string, str, l)\n }\n }\n\n const startPos = this._pos\n const chars = []\n\n const readu4 = () => {\n if (this._pos + 4 >= this.data.length) {\n throw new Error(`${decodeErrPrefix} unexpected end of unicode escape sequence at position ${this._pos}`)\n }\n let u4 = 0\n for (let i = 0; i < 4; i++) {\n let ch = this.ch()\n if (ch >= 48 && ch <= 57) { // '0' && '9'\n ch -= 48\n } else if (ch >= 97 && ch <= 102) { // 'a' && 'f'\n ch = ch - 97 + 10\n } else if (ch >= 65 && ch <= 70) { // 'A' && 'F'\n ch = ch - 65 + 10\n } else {\n throw new Error(`${decodeErrPrefix} unexpected unicode escape character at position ${this._pos}`)\n }\n u4 = u4 * 16 + ch\n this._pos++\n }\n return u4\n }\n\n // mostly taken from feross/buffer and adjusted to fit\n const readUtf8Char = () => {\n const firstByte = this.ch()\n let codePoint = null\n /* c8 ignore next 1 */\n let bytesPerSequence = (firstByte > 0xef) ? 4 : (firstByte > 0xdf) ? 3 : (firstByte > 0xbf) ? 2 : 1\n\n if (this._pos + bytesPerSequence > this.data.length) {\n throw new Error(`${decodeErrPrefix} unexpected unicode sequence at position ${this._pos}`)\n }\n\n let secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n /* c8 ignore next 6 */\n // this case is dealt with by the caller function\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = this.data[this._pos + 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 = this.data[this._pos + 1]\n thirdByte = this.data[this._pos + 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 = this.data[this._pos + 1]\n thirdByte = this.data[this._pos + 2]\n fourthByte = this.data[this._pos + 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 /* 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 chars.push(codePoint >>> 10 & 0x3ff | 0xd800)\n codePoint = 0xdc00 | codePoint & 0x3ff\n }\n\n chars.push(codePoint)\n this._pos += bytesPerSequence\n }\n\n // TODO: could take the approach of a quick first scan for special chars like encoding/json/decode.go#unquoteBytes\n // and converting all of the ascii chars from the base array in bulk\n while (!this.done()) {\n const ch = this.ch()\n let ch1\n switch (ch) {\n case 92: // '\\'\n this._pos++\n if (this.done()) {\n throw new Error(`${decodeErrPrefix} unexpected string termination at position ${this._pos}`)\n }\n ch1 = this.ch()\n this._pos++\n switch (ch1) {\n case 34: // '\"'\n case 39: // '\\''\n case 92: // '\\'\n case 47: // '/'\n chars.push(ch1)\n break\n case 98: // 'b'\n chars.push(8)\n break\n case 116: // 't'\n chars.push(9)\n break\n case 110: // 'n'\n chars.push(10)\n break\n case 102: // 'f'\n chars.push(12)\n break\n case 114: // 'r'\n chars.push(13)\n break\n case 117: // 'u'\n chars.push(readu4())\n break\n default:\n throw new Error(`${decodeErrPrefix} unexpected string escape character at position ${this._pos}`)\n }\n break\n case 34: // '\"'\n this._pos++\n return new Token(Type.string, decodeCodePointsArray(chars), this._pos - startPos)\n default:\n if (ch < 32) { // ' '\n throw new Error(`${decodeErrPrefix} invalid control character at position ${this._pos}`)\n } else if (ch < 0x80) {\n chars.push(ch)\n this._pos++\n } else {\n readUtf8Char()\n }\n }\n }\n\n throw new Error(`${decodeErrPrefix} unexpected end of string at position ${this._pos}`)\n }\n\n /**\n * @returns {Token}\n */\n parseValue () {\n switch (this.ch()) {\n case 123: // '{'\n this.modeStack.push('obj-start')\n this._pos++\n return new Token(Type.map, Infinity, 1)\n case 91: // '['\n this.modeStack.push('array-start')\n this._pos++\n return new Token(Type.array, Infinity, 1)\n case 34: { // '\"'\n return this.parseString()\n }\n case 110: // 'n' / null\n this.expect([110, 117, 108, 108]) // 'null'\n return new Token(Type.null, null, 4)\n case 102: // 'f' / // false\n this.expect([102, 97, 108, 115, 101]) // 'false'\n return new Token(Type.false, false, 5)\n case 116: // 't' / // true\n this.expect([116, 114, 117, 101]) // 'true'\n return new Token(Type.true, true, 4)\n case 45: // '-'\n case 48: // '0'\n case 49: // '1'\n case 50: // '2'\n case 51: // '3'\n case 52: // '4'\n case 53: // '5'\n case 54: // '6'\n case 55: // '7'\n case 56: // '8'\n case 57: // '9'\n return this.parseNumber()\n default:\n throw new Error(`${decodeErrPrefix} unexpected character at position ${this._pos}`)\n }\n }\n\n /**\n * @returns {Token}\n */\n next () {\n this.skipWhitespace()\n switch (this.currentMode()) {\n case 'value':\n this.modeStack.pop()\n return this.parseValue()\n case 'array-value': {\n this.modeStack.pop()\n if (this.ch() === 93) { // ']'\n this._pos++\n this.skipWhitespace()\n return new Token(Type.break, undefined, 1)\n }\n if (this.ch() !== 44) { // ','\n throw new Error(`${decodeErrPrefix} unexpected character at position ${this._pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`)\n }\n this._pos++\n this.modeStack.push('array-value')\n this.skipWhitespace()\n return this.parseValue()\n }\n case 'array-start': {\n this.modeStack.pop()\n if (this.ch() === 93) { // ']'\n this._pos++\n this.skipWhitespace()\n return new Token(Type.break, undefined, 1)\n }\n this.modeStack.push('array-value')\n this.skipWhitespace()\n return this.parseValue()\n }\n // @ts-ignore\n case 'obj-key':\n if (this.ch() === 125) { // '}'\n this.modeStack.pop()\n this._pos++\n this.skipWhitespace()\n return new Token(Type.break, undefined, 1)\n }\n if (this.ch() !== 44) { // ','\n throw new Error(`${decodeErrPrefix} unexpected character at position ${this._pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`)\n }\n this._pos++\n this.skipWhitespace()\n case 'obj-start': { // eslint-disable-line no-fallthrough\n this.modeStack.pop()\n if (this.ch() === 125) { // '}'\n this._pos++\n this.skipWhitespace()\n return new Token(Type.break, undefined, 1)\n }\n const token = this.parseString()\n this.skipWhitespace()\n if (this.ch() !== 58) { // ':'\n throw new Error(`${decodeErrPrefix} unexpected character at position ${this._pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`)\n }\n this._pos++\n this.modeStack.push('obj-value')\n return token\n }\n case 'obj-value': {\n this.modeStack.pop()\n this.modeStack.push('obj-key')\n this.skipWhitespace()\n return this.parseValue()\n }\n /* c8 ignore next 2 */\n default:\n throw new Error(`${decodeErrPrefix} unexpected parse state at position ${this._pos}; this shouldn't happen`)\n }\n }\n}\n\n/**\n * @param {Uint8Array} data\n * @param {DecodeOptions} [options]\n * @returns {any}\n */\nfunction decode (data, options) {\n options = Object.assign({ tokenizer: new Tokenizer(data, options) }, options)\n return _decode(data, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {DecodeOptions} [options]\n * @returns {[any, Uint8Array]}\n */\nfunction decodeFirst (data, options) {\n options = Object.assign({ tokenizer: new Tokenizer(data, options) }, options)\n return _decodeFirst(data, options)\n}\n\nexport { decode, decodeFirst, Tokenizer }\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", "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", "export function isPromise <T> (p?: any): p is Promise<T> {\n return p?.then != null\n}\n", "import { UnknownCodecError } from '@helia/interface'\nimport * as dagCbor from '@ipld/dag-cbor'\nimport * as dagJson from '@ipld/dag-json'\nimport * as dagPb from '@ipld/dag-pb'\nimport * as json from 'multiformats/codecs/json'\nimport * as raw from 'multiformats/codecs/raw'\nimport { isPromise } from './is-promise.ts'\nimport type { CodecLoader } from '@helia/interface'\nimport type { BlockCodec } from 'multiformats/codecs/interface'\n\nexport function getCodec (initialCodecs: Array<BlockCodec<any, any>> = [], loadCodec?: CodecLoader): CodecLoader {\n const codecs: Record<number, BlockCodec<any, any>> = {\n [dagPb.code]: dagPb,\n [raw.code]: raw,\n [dagCbor.code]: dagCbor,\n [dagJson.code]: dagJson,\n [json.code]: json\n }\n\n initialCodecs.forEach(codec => {\n codecs[codec.code] = codec\n })\n\n return async (code) => {\n let codec = codecs[code]\n\n if (codec == null && loadCodec != null) {\n const res = loadCodec(code)\n\n if (isPromise(res)) {\n codec = await res\n } else {\n codec = res\n }\n\n codecs[codec.code] = codec\n }\n\n if (codec != null) {\n return codec\n }\n\n throw new UnknownCodecError(`Could not load codec for ${code}`)\n }\n}\n", "import { UnknownCryptoError } from '@helia/interface'\nimport { ecdsaCrypto, ed25519Crypto, rsaCrypto } from '@ipshipyard/crypto'\nimport { isPromise } from './is-promise.ts'\nimport type { CryptoLoader } from '@helia/interface'\nimport type { Crypto } from '@ipshipyard/crypto'\n\nexport function getCrypto (initialCryptos: Array<Crypto> = [], loadCrypto?: CryptoLoader): CryptoLoader {\n const cryptos: Record<string | number, Crypto> = {}\n\n initialCryptos = [\n ecdsaCrypto(),\n ed25519Crypto(),\n rsaCrypto(),\n ...initialCryptos\n ]\n\n initialCryptos.forEach(crypto => {\n cryptos[crypto.type] = crypto\n cryptos[crypto.code] = crypto\n })\n\n return async (nameOrCode) => {\n let crypto = cryptos[nameOrCode]\n\n if (crypto == null && loadCrypto != null) {\n const res = loadCrypto(nameOrCode)\n\n if (isPromise(res)) {\n crypto = await res\n } else {\n crypto = res\n }\n\n cryptos[crypto.type] = crypto\n cryptos[crypto.code] = crypto\n }\n\n if (crypto != null) {\n return crypto\n }\n\n throw new UnknownCryptoError(`Could not load crypto for ${crypto}`)\n }\n}\n", "import { UnknownHashAlgorithmError } from '@helia/interface'\nimport { identity } from 'multiformats/hashes/identity'\nimport { sha256, sha512 } from 'multiformats/hashes/sha2'\nimport { isPromise } from './is-promise.ts'\nimport type { HasherLoader } from '@helia/interface'\nimport type { MultihashHasher } from 'multiformats/hashes/interface'\n\nexport function getHasher (initialHashers: MultihashHasher[] = [], loadHasher?: HasherLoader): HasherLoader {\n const hashers: Record<number, MultihashHasher> = {\n [sha256.code]: sha256,\n [sha512.code]: sha512,\n [identity.code]: identity\n }\n\n initialHashers.forEach(hasher => {\n hashers[hasher.code] = hasher\n })\n\n return async (code) => {\n let hasher = hashers[code]\n\n if (hasher == null && loadHasher != null) {\n const res = loadHasher(code)\n\n if (isPromise(res)) {\n hasher = await res\n } else {\n hasher = res\n }\n\n hashers[hasher.code] = hasher\n }\n\n if (hasher != null) {\n return hasher\n }\n\n throw new UnknownHashAlgorithmError(`No hasher configured for multihash code 0x${code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`)\n }\n}\n", "import { NotFoundError } from 'interface-store'\nimport { BaseBlockstore } from './base.ts'\nimport type { AbortOptions } from 'abort-error'\nimport type { Blockstore, Pair } from 'interface-blockstore'\nimport type { CID } from 'multiformats/cid'\n\n// https://github.com/multiformats/multicodec/blob/d06fc6194710e8909bac64273c43f16b56ca4c34/table.csv#L2\nconst IDENTITY_CODEC = 0x00\n\nclass IdentityHashDigestTooLongError extends Error {\n static name = 'IdentityHashDigestTooLongError'\n name = 'IdentityHashDigestTooLongError'\n}\n\nexport interface IdentityBlockstoreInit {\n maxDigestLength?: number\n}\n\nexport class IdentityBlockstore extends BaseBlockstore {\n private readonly child?: Blockstore\n private readonly maxDigestLength?: number\n\n constructor (child?: Blockstore, init?: IdentityBlockstoreInit) {\n super()\n\n this.child = child\n this.maxDigestLength = init?.maxDigestLength\n }\n\n put (key: CID, block: Uint8Array | Iterable<Uint8Array> | AsyncIterable<Uint8Array>, options?: AbortOptions): CID | Promise<CID> {\n if (key.multihash.code === IDENTITY_CODEC) {\n if (this.maxDigestLength != null && key.multihash.digest.byteLength > this.maxDigestLength) {\n throw new IdentityHashDigestTooLongError(`Identity digest too long - ${key.multihash.digest.byteLength} > this.maxDigestLength`)\n }\n\n options?.signal?.throwIfAborted()\n return key\n }\n\n if (this.child == null) {\n options?.signal?.throwIfAborted()\n return key\n }\n\n return this.child.put(key, block, options)\n }\n\n async * get (key: CID, options?: AbortOptions): AsyncGenerator<Uint8Array> {\n if (key.multihash.code === IDENTITY_CODEC) {\n if (this.maxDigestLength != null && key.multihash.digest.byteLength > this.maxDigestLength) {\n throw new IdentityHashDigestTooLongError(`Identity digest too long - ${key.multihash.digest.byteLength} > this.maxDigestLength`)\n }\n\n options?.signal?.throwIfAborted()\n yield key.multihash.digest\n return\n }\n\n if (this.child == null) {\n options?.signal?.throwIfAborted()\n throw new NotFoundError()\n }\n\n yield * this.child.get(key, options)\n }\n\n has (key: CID, options?: AbortOptions): boolean | Promise<boolean> {\n if (key.multihash.code === IDENTITY_CODEC) {\n if (this.maxDigestLength != null && key.multihash.digest.byteLength > this.maxDigestLength) {\n throw new IdentityHashDigestTooLongError(`Identity digest too long - ${key.multihash.digest.byteLength} > this.maxDigestLength`)\n }\n\n options?.signal?.throwIfAborted()\n return true\n }\n\n if (this.child == null) {\n options?.signal?.throwIfAborted()\n return false\n }\n\n return this.child.has(key, options)\n }\n\n delete (key: CID, options?: AbortOptions): void | Promise<void> {\n if (key.code === IDENTITY_CODEC) {\n if (this.maxDigestLength != null && key.multihash.digest.byteLength > this.maxDigestLength) {\n throw new IdentityHashDigestTooLongError(`Identity digest too long - ${key.multihash.digest.byteLength} > this.maxDigestLength`)\n }\n\n options?.signal?.throwIfAborted()\n return\n }\n\n if (this.child != null) {\n return this.child.delete(key, options)\n }\n }\n\n async * getAll (options?: AbortOptions): AsyncGenerator<Pair> {\n if (this.child != null) {\n yield * this.child.getAll(options)\n }\n\n options?.signal?.throwIfAborted()\n }\n}\n", "/**\n * @packageDocumentation\n *\n * Calls a function for each value in an (async)iterable.\n *\n * The function can be sync or async.\n *\n * Async functions can be awaited on so may slow down processing of the (async)iterable.\n *\n * @example\n *\n * ```javascript\n * import each from 'it-foreach'\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 * // prints [0, 0], [1, 1], [2, 2], [3, 3], [4, 4]\n * const arr = drain(\n * each(values, console.info)\n * )\n * ```\n *\n * Async sources and callbacks must be awaited:\n *\n * ```javascript\n * import each from 'it-foreach'\n * import drain from 'it-drain'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * // prints [0, 0], [1, 1], [2, 2], [3, 3], [4, 4]\n * const arr = await drain(\n * each(values(), console.info)\n * )\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\nfunction isPromise <T = unknown> (thing: any): thing is Promise<T> {\n return thing?.then != null\n}\n\n/**\n * Invokes the passed function for each item in an iterable\n */\nfunction forEach <T> (source: Iterable<T>, fn: (thing: T, index: number) => Promise<void>): AsyncGenerator<T, void, undefined>\nfunction forEach <T> (source: Iterable<T>, fn: (thing: T, index: number) => void): Generator<T, void, undefined>\nfunction forEach <T> (source: Iterable<T> | AsyncIterable<T>, fn: (thing: T, index: number) => void | Promise<void>): AsyncGenerator<T, void, undefined>\nfunction forEach <T> (source: Iterable<T> | AsyncIterable<T>, fn: (thing: T, index: number) => void | Promise<void>): AsyncGenerator<T, void, undefined> | Generator<T, void, undefined> {\n let index = 0\n\n if (isAsyncIterable(source)) {\n return (async function * () {\n for await (const val of source) {\n const res = fn(val, index++)\n\n if (isPromise(res)) {\n await res\n }\n\n yield val\n }\n })()\n }\n\n // if fn 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 = fn(value, index++)\n\n if (typeof res?.then === 'function') {\n return (async function * () {\n await res\n yield value\n\n for (const val of peekable) {\n const res = fn(val, index++)\n\n if (isPromise(res)) {\n await res\n }\n\n yield val\n }\n })()\n }\n\n const func = fn as (val: T, index: number) => void\n\n return (function * () {\n yield value\n\n for (const val of peekable) {\n func(val, index++)\n yield val\n }\n })()\n}\n\nexport default forEach\n", "import { InvalidMultihashError, InvalidParametersError, setMaxListeners } from '@libp2p/interface'\nimport { anySignal } from 'any-signal'\nimport { IdentityBlockstore } from 'blockstore-core/identity'\nimport filter from 'it-filter'\nimport forEach from 'it-foreach'\nimport { CustomProgressEvent } from 'progress-events'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { BlockNotFoundWhileOfflineError, InvalidConfigurationError, LoadBlockFailedError } from '../errors.ts'\nimport { isPromise } from './is-promise.ts'\nimport type { HasherLoader } from '@helia/interface'\nimport type { BlockBroker, Pair, DeleteManyBlocksProgressEvents, DeleteBlockProgressEvents, GetBlockProgressEvents, GetManyBlocksProgressEvents, PutManyBlocksProgressEvents, PutBlockProgressEvents, GetAllBlocksProgressEvents, GetOfflineOptions, BlockRetrievalOptions } from '@helia/interface'\nimport type { AbortOptions, ComponentLogger, Logger, LoggerOptions } from '@libp2p/interface'\nimport type { Blockstore, InputPair } from 'interface-blockstore'\nimport type { CID } from 'multiformats/cid'\nimport type { MultihashDigest, MultihashHasher } from 'multiformats/hashes/interface'\nimport type { ProgressEvent, ProgressOptions } from 'progress-events'\n\nexport interface StorageComponents<Broker extends BlockBroker<ProgressEvent<any, any>, ProgressEvent<any, any>>> {\n blockstore: Blockstore\n logger: ComponentLogger\n blockBrokers: Broker[]\n getHasher: HasherLoader\n}\n\nexport interface StorageInit {\n maxIdentityHashDigestLength?: number\n}\n\nconst DEFAULT_MAX_IDENTITY_HASH_DIGEST_LENGTH = 128\n\nexport class Storage <Broker extends BlockBroker<ProgressEvent<any, any>, ProgressEvent<any, any>>> implements Blockstore {\n protected readonly child: Blockstore\n protected readonly getHasher: HasherLoader\n protected log: Logger\n protected readonly logger: ComponentLogger\n protected readonly blockBrokers: Broker[]\n\n /**\n * Create a new BlockStorage\n */\n constructor (components: StorageComponents<Broker>, init: StorageInit = {}) {\n this.log = components.logger.forComponent('helia:networked-storage')\n this.logger = components.logger\n this.blockBrokers = components.blockBrokers\n this.child = new IdentityBlockstore(components.blockstore, {\n maxDigestLength: init.maxIdentityHashDigestLength ?? DEFAULT_MAX_IDENTITY_HASH_DIGEST_LENGTH\n })\n this.getHasher = components.getHasher\n }\n\n /**\n * Put a block to the underlying datastore\n */\n async put (cid: CID, block: Uint8Array, options: AbortOptions & ProgressOptions<PutBlockProgressEvents> = {}): Promise<CID> {\n if (await this.child.has(cid, options)) {\n options.onProgress?.(new CustomProgressEvent<CID>('blocks:put:duplicate', cid))\n return cid\n }\n\n options.onProgress?.(new CustomProgressEvent<CID>('blocks:put:providers:notify', cid))\n\n await Promise.all(\n this.blockBrokers.map(async broker => broker.announce?.(cid, options))\n )\n\n options.onProgress?.(new CustomProgressEvent<CID>('blocks:put:blockstore:put', cid))\n\n return this.child.put(cid, block, options)\n }\n\n /**\n * Put a multiple blocks to the underlying datastore\n */\n async * putMany (blocks: Iterable<InputPair> | AsyncIterable<InputPair>, options: AbortOptions & ProgressOptions<PutManyBlocksProgressEvents> = {}): AsyncGenerator<CID> {\n const missingBlocks = filter(blocks, async ({ cid }): Promise<boolean> => {\n const has = await this.child.has(cid, options)\n\n if (has) {\n options.onProgress?.(new CustomProgressEvent<CID>('blocks:put-many:duplicate', cid))\n }\n\n return !has\n })\n\n const notifyEach = forEach(missingBlocks, async ({ cid }): Promise<void> => {\n options.onProgress?.(new CustomProgressEvent<CID>('blocks:put-many:providers:notify', cid))\n await Promise.all(\n this.blockBrokers.map(async broker => broker.announce?.(cid, options))\n )\n })\n\n options.onProgress?.(new CustomProgressEvent('blocks:put-many:blockstore:put-many'))\n yield * this.child.putMany(notifyEach, options)\n }\n\n /**\n * Get a block by cid\n */\n async * get (cid: CID, options: GetOfflineOptions & AbortOptions & ProgressOptions<GetBlockProgressEvents> = {}): AsyncGenerator<Uint8Array> {\n const has = await this.child.has(cid, options)\n const offline = options.offline === true\n\n if (!has) {\n if (offline) {\n throw new BlockNotFoundWhileOfflineError('The block was present in the blockstore and the node is running offline so cannot fetch it')\n }\n\n const hasher = await this.getHasher(cid.multihash.code)\n options?.signal?.throwIfAborted()\n\n // we do not have the block locally, get it from a block provider\n\n options.onProgress?.(new CustomProgressEvent<CID>('blocks:get:providers:get', cid))\n const block = await raceBlockRetrievers(cid, this.blockBrokers, hasher, {\n ...options,\n log: this.log\n })\n options.onProgress?.(new CustomProgressEvent<CID>('blocks:get:blockstore:put', cid))\n await this.child.put(cid, block, options)\n\n // notify other block providers of the new block\n options.onProgress?.(new CustomProgressEvent<CID>('blocks:get:providers:notify', cid))\n await Promise.all(\n this.blockBrokers.map(async broker => broker.announce?.(cid, options))\n )\n\n yield block\n return\n }\n\n options.onProgress?.(new CustomProgressEvent<CID>('blocks:get:blockstore:get', cid))\n\n yield * this.child.get(cid, options)\n }\n\n /**\n * Get multiple blocks back from an (async) iterable of cids\n */\n async * getMany (cids: Iterable<CID> | AsyncIterable<CID>, options: GetOfflineOptions & AbortOptions & ProgressOptions<GetManyBlocksProgressEvents> = {}): AsyncGenerator<Pair> {\n options.onProgress?.(new CustomProgressEvent('blocks:get-many:blockstore:get-many'))\n\n yield * this.child.getMany(forEach(cids, async (cid): Promise<void> => {\n const has = await this.child.has(cid, options)\n const offline = options.offline === true\n\n if (!has) {\n if (offline) {\n throw new BlockNotFoundWhileOfflineError('The block was present in the blockstore and the node is running offline so cannot fetch it')\n }\n\n const hasher = await this.getHasher(cid.multihash.code)\n options?.signal?.throwIfAborted()\n\n // we do not have the block locally, get it from a block provider\n options.onProgress?.(new CustomProgressEvent<CID>('blocks:get-many:providers:get', cid))\n const block = await raceBlockRetrievers(cid, this.blockBrokers, hasher, {\n ...options,\n log: this.log\n })\n options.onProgress?.(new CustomProgressEvent<CID>('blocks:get-many:blockstore:put', cid))\n await this.child.put(cid, block, options)\n\n // notify other block providers of the new block\n options.onProgress?.(new CustomProgressEvent<CID>('blocks:get-many:providers:notify', cid))\n await Promise.all(\n this.blockBrokers.map(async broker => broker.announce?.(cid, options))\n )\n }\n }))\n }\n\n /**\n * Delete a block from the blockstore\n */\n async delete (cid: CID, options: AbortOptions & ProgressOptions<DeleteBlockProgressEvents> = {}): Promise<void> {\n options.onProgress?.(new CustomProgressEvent<CID>('blocks:delete:blockstore:delete', cid))\n\n await this.child.delete(cid, options)\n }\n\n /**\n * Delete multiple blocks from the blockstore\n */\n async * deleteMany (cids: Iterable<CID> | AsyncIterable<CID>, options: AbortOptions & ProgressOptions<DeleteManyBlocksProgressEvents> = {}): AsyncGenerator<CID> {\n options.onProgress?.(new CustomProgressEvent('blocks:delete-many:blockstore:delete-many'))\n yield * this.child.deleteMany((async function * (): AsyncGenerator<CID> {\n for await (const cid of cids) {\n yield cid\n }\n }()), options)\n }\n\n async has (cid: CID, options: AbortOptions = {}): Promise<boolean> {\n return this.child.has(cid, options)\n }\n\n async * getAll (options: AbortOptions & ProgressOptions<GetAllBlocksProgressEvents> = {}): AsyncGenerator<Pair> {\n options.onProgress?.(new CustomProgressEvent('blocks:get-all:blockstore:get-many'))\n yield * this.child.getAll(options)\n }\n}\n\n/**\n * Race block providers cancelling any pending requests once the block has been\n * found.\n */\nasync function raceBlockRetrievers (cid: CID, blockBrokers: BlockBroker[], hasher: MultihashHasher, options: AbortOptions & LoggerOptions): Promise<Uint8Array> {\n const validateFn = getCidBlockVerifierFunction(cid, hasher)\n\n const controller = new AbortController()\n const signal = anySignal([controller.signal, options.signal])\n setMaxListeners(Infinity, controller.signal, signal)\n\n const retrievers: Array<Required<Pick<BlockBroker, 'name' | 'retrieve'>>> = []\n\n for (const broker of blockBrokers) {\n if (isRetrievingBlockBroker(broker)) {\n retrievers.push(broker)\n }\n }\n\n if (retrievers.length === 0) {\n throw new InvalidConfigurationError(`No block brokers capable of retrieving blocks are configured, the CID ${cid} cannot be fetched from the network`)\n }\n\n try {\n return await Promise.any(\n retrievers\n .map(async retriever => {\n try {\n let blocksWereValidated = false\n const block = await retriever.retrieve(cid, {\n ...options,\n signal,\n validateFn: async (block: Uint8Array): Promise<void> => {\n await validateFn(block)\n options.signal?.throwIfAborted()\n blocksWereValidated = true\n }\n })\n\n if (!blocksWereValidated) {\n // the blockBroker either did not throw an error when attempting to validate the block\n // or did not call the validateFn at all. We should validate the block ourselves\n await validateFn(block)\n options.signal?.throwIfAborted()\n }\n\n return block\n } catch (err) {\n options.log.error('could not retrieve verified block for %c from %s - %e', cid, retriever.name, err)\n throw err\n }\n })\n )\n } catch (err: any) {\n throw new LoadBlockFailedError(err.errors, `Failed to load block for ${cid}`)\n } finally {\n // we have the block from the fastest block retriever, abort any still\n // in-flight retrieve attempts\n controller.abort()\n signal.clear()\n }\n}\n\nfunction isRetrievingBlockBroker (broker: BlockBroker): broker is Required<Pick<BlockBroker, 'name' | 'retrieve'>> {\n return typeof broker.retrieve === 'function'\n}\n\nexport const getCidBlockVerifierFunction = (cid: CID, hasher: MultihashHasher): Required<BlockRetrievalOptions>['validateFn'] => {\n if (hasher == null) {\n throw new InvalidParametersError(`No hasher configured for multihash code 0x${cid.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`)\n }\n\n return async (block: Uint8Array): Promise<void> => {\n // verify block\n let hash: MultihashDigest<number>\n const res = hasher.digest(block, {\n // support truncated hashes where they are truncated\n truncate: cid.multihash.digest.byteLength\n })\n\n if (isPromise(res)) {\n hash = await res\n } else {\n hash = res\n }\n\n if (!uint8ArrayEquals(hash.digest, cid.multihash.digest)) {\n // if a hash mismatch occurs for a TrustlessGatewayBlockBroker, we should try another gateway\n throw new InvalidMultihashError('Hash of downloaded block did not match multihash from passed CID')\n }\n }\n}\n", "import { setMaxListeners } from '@libp2p/interface'\nimport { anySignal } from 'any-signal'\nimport { Storage } from './storage.ts'\nimport type { StorageComponents } from './storage.ts'\nimport type { Pair, DeleteManyBlocksProgressEvents, DeleteBlockProgressEvents, GetBlockProgressEvents, GetManyBlocksProgressEvents, PutManyBlocksProgressEvents, PutBlockProgressEvents, GetAllBlocksProgressEvents, GetOfflineOptions, SessionBlockstore, SessionBlockBroker } from '@helia/interface'\nimport type { AbortOptions } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { InputPair } from 'interface-blockstore'\nimport type { CID } from 'multiformats/cid'\nimport type { ProgressOptions } from 'progress-events'\n\nexport interface SessionStorageInit {\n root: CID\n}\n\n/**\n * Storage subclass that can cancel any ongoing operation at any point.\n */\nexport class SessionStorage extends Storage<SessionBlockBroker> implements SessionBlockstore {\n private readonly closeController: AbortController\n\n constructor (components: StorageComponents<SessionBlockBroker>, init: SessionStorageInit) {\n super(components)\n\n // because brokers are allowed to continue searching for providers after the\n // session has been created, we need a way to tell them that the user has\n // finished using the session any in-flight requests should be cancelled\n this.closeController = new AbortController()\n setMaxListeners(Infinity, this.closeController.signal)\n\n this.log = components.logger.forComponent(`helia:session-storage:${init.root}`)\n }\n\n close (): void {\n this.closeController.abort()\n }\n\n async addPeer (peer: CID | Multiaddr | Multiaddr[], options?: AbortOptions): Promise<void> {\n await Promise.all(\n this.blockBrokers\n .map(broker => broker.addPeer(peer, options))\n )\n }\n\n /**\n * Put a block to the underlying datastore\n */\n async put (cid: CID, block: Uint8Array, options: AbortOptions & ProgressOptions<PutBlockProgressEvents> = {}): Promise<CID> {\n const signal = anySignal([this.closeController.signal, options.signal])\n setMaxListeners(Infinity, signal)\n\n try {\n return await super.put(cid, block, {\n ...options,\n signal\n })\n } finally {\n signal.clear()\n }\n }\n\n /**\n * Put a multiple blocks to the underlying datastore\n */\n async * putMany (blocks: Iterable<InputPair> | AsyncIterable<InputPair>, options: AbortOptions & ProgressOptions<PutManyBlocksProgressEvents> = {}): AsyncGenerator<CID> {\n const signal = anySignal([this.closeController.signal, options.signal])\n setMaxListeners(Infinity, signal)\n\n try {\n yield * super.putMany(blocks, {\n ...options,\n signal\n })\n } finally {\n signal.clear()\n }\n }\n\n /**\n * Get a block by cid\n */\n async * get (cid: CID, options: GetOfflineOptions & AbortOptions & ProgressOptions<GetBlockProgressEvents> = {}): AsyncGenerator<Uint8Array> {\n const signal = anySignal([this.closeController.signal, options.signal])\n setMaxListeners(Infinity, signal)\n\n try {\n yield * super.get(cid, {\n ...options,\n signal\n })\n } finally {\n signal.clear()\n }\n }\n\n /**\n * Get multiple blocks back from an (async) iterable of cids\n */\n async * getMany (cids: Iterable<CID> | AsyncIterable<CID>, options: GetOfflineOptions & AbortOptions & ProgressOptions<GetManyBlocksProgressEvents> = {}): AsyncGenerator<Pair> {\n const signal = anySignal([this.closeController.signal, options.signal])\n setMaxListeners(Infinity, signal)\n\n try {\n yield * super.getMany(cids, {\n ...options,\n signal\n })\n } finally {\n signal.clear()\n }\n }\n\n /**\n * Delete a block from the blockstore\n */\n async delete (cid: CID, options: AbortOptions & ProgressOptions<DeleteBlockProgressEvents> = {}): Promise<void> {\n const signal = anySignal([this.closeController.signal, options.signal])\n setMaxListeners(Infinity, signal)\n\n try {\n await super.delete(cid, {\n ...options,\n signal\n })\n } finally {\n signal.clear()\n }\n }\n\n /**\n * Delete multiple blocks from the blockstore\n */\n async * deleteMany (cids: Iterable<CID> | AsyncIterable<CID>, options: AbortOptions & ProgressOptions<DeleteManyBlocksProgressEvents> = {}): AsyncGenerator<CID> {\n const signal = anySignal([this.closeController.signal, options.signal])\n setMaxListeners(Infinity, signal)\n\n try {\n yield * super.deleteMany(cids, {\n ...options,\n signal\n })\n } finally {\n signal.clear()\n }\n }\n\n async has (cid: CID, options: AbortOptions = {}): Promise<boolean> {\n const signal = anySignal([this.closeController.signal, options.signal])\n setMaxListeners(Infinity, signal)\n\n try {\n return await super.has(cid, {\n ...options,\n signal\n })\n } finally {\n signal.clear()\n }\n }\n\n async * getAll (options: AbortOptions & ProgressOptions<GetAllBlocksProgressEvents> = {}): AsyncGenerator<Pair> {\n const signal = anySignal([this.closeController.signal, options.signal])\n setMaxListeners(Infinity, signal)\n\n try {\n yield * super.getAll({\n ...options,\n signal\n })\n } finally {\n signal.clear()\n }\n }\n}\n", "import { start, stop } from '@libp2p/interface'\nimport { InvalidConfigurationError } from '../errors.ts'\nimport { SessionStorage } from './session-storage.ts'\nimport { Storage } from './storage.ts'\nimport type { StorageComponents, StorageInit } from './storage.ts'\nimport type { BlockBroker, Blocks, CreateSessionOptions, SessionBlockstore } from '@helia/interface'\nimport type { Startable } from '@libp2p/interface'\nimport type { AbortOptions } from 'abort-error'\nimport type { Blockstore } from 'interface-blockstore'\nimport type { CID } from 'multiformats/cid'\n\nexport interface GetOptions extends AbortOptions {\n progress?(evt: Event): void\n}\n\nexport type NetworkedStorageComponents = StorageComponents<BlockBroker>\n\n/**\n * Networked storage wraps a regular blockstore - when getting blocks if the\n * blocks are not present, the configured BlockBrokers will be used to fetch them.\n */\nexport class NetworkedStorage extends Storage<BlockBroker> implements Blocks, Startable {\n private started: boolean\n\n /**\n * Create a new BlockStorage\n */\n constructor (components: NetworkedStorageComponents, init: StorageInit = {}) {\n super(components, init)\n\n this.started = false\n }\n\n isStarted (): boolean {\n return this.started\n }\n\n async start (): Promise<void> {\n await start(this.child, ...this.blockBrokers)\n this.started = true\n }\n\n async stop (): Promise<void> {\n await stop(this.child, ...this.blockBrokers)\n this.started = false\n }\n\n unwrap (): Blockstore {\n return this.child\n }\n\n createSession (root: CID, options?: CreateSessionOptions): SessionBlockstore {\n if (this.blockBrokers.length === 0) {\n throw new InvalidConfigurationError('No block brokers configured')\n }\n\n const blockBrokers = this.blockBrokers\n .map(broker => broker.createSession?.(options))\n .filter(broker => broker != null)\n\n if (blockBrokers.length === 0) {\n throw new InvalidConfigurationError(`No configured block brokers support sessions - tried ${this.blockBrokers.map(b => b.name).join(', ')}`)\n }\n\n return new SessionStorage({\n blockstore: this.child,\n blockBrokers,\n getHasher: this.getHasher,\n logger: this.logger\n }, {\n root\n })\n }\n}\n", "import { DEFAULT_SESSION_MIN_PROVIDERS, DEFAULT_SESSION_MAX_PROVIDERS, DEFAULT_CID_PEER_FILTER_SIZE, InsufficientProvidersError } from '@helia/interface'\nimport { AbortError, TypedEventEmitter, setMaxListeners } from '@libp2p/interface'\nimport { createScalableCuckooFilter, Queue } from '@libp2p/utils'\nimport { base64 } from 'multiformats/bases/base64'\nimport pDefer from 'p-defer'\nimport { raceSignal } from 'race-signal'\nimport type { BlockBroker, BlockRetrievalOptions, CreateSessionOptions } from '@helia/interface'\nimport type { AbortOptions, ComponentLogger, Logger } from '@libp2p/interface'\nimport type { Filter } from '@libp2p/utils'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { CID } from 'multiformats/cid'\nimport type { DeferredPromise } from 'p-defer'\nimport type { ProgressEvent } from 'progress-events'\n\nexport interface AbstractSessionComponents {\n logger: ComponentLogger\n}\n\nexport interface AbstractCreateSessionOptions extends CreateSessionOptions {\n name: string\n}\n\nexport interface BlockstoreSessionEvents<Provider> {\n provider: CustomEvent<Provider>\n}\n\ninterface Request {\n promise: Promise<Uint8Array>\n observers: number\n queryFilter: Filter\n}\n\nexport abstract class AbstractSession<Provider, RetrieveBlockProgressEvents extends ProgressEvent> extends TypedEventEmitter<BlockstoreSessionEvents<Provider>> implements BlockBroker<RetrieveBlockProgressEvents> {\n public abstract name: string\n private initialPeerSearchComplete?: Promise<void>\n private readonly requests: Map<string, Request>\n private readonly logName: string\n protected log: Logger\n protected logger: ComponentLogger\n private readonly minProviders: number\n private readonly maxProviders: number\n public readonly providers: Provider[]\n private readonly evictionFilter: Filter\n private readonly initialProviders: Array<CID | Multiaddr | Multiaddr[]>\n private readonly cidPeerFilterSize: number\n\n constructor (components: AbstractSessionComponents, init: AbstractCreateSessionOptions) {\n super()\n\n setMaxListeners(Infinity, this)\n this.logName = init.name\n this.logger = components.logger\n this.log = components.logger.forComponent(this.logName)\n this.requests = new Map()\n this.minProviders = init.minProviders ?? DEFAULT_SESSION_MIN_PROVIDERS\n this.maxProviders = init.maxProviders ?? DEFAULT_SESSION_MAX_PROVIDERS\n this.cidPeerFilterSize = init.cidPeerFilterSize ?? DEFAULT_CID_PEER_FILTER_SIZE\n this.providers = []\n this.evictionFilter = createScalableCuckooFilter(this.maxProviders)\n this.initialProviders = [...(init.providers ?? [])]\n }\n\n async retrieve (cid: CID, options: BlockRetrievalOptions<RetrieveBlockProgressEvents> = {}): Promise<Uint8Array> {\n // see if we are already requesting this CID in this session\n const cidStr = base64.encode(cid.multihash.bytes)\n const existingJob = this.requests.get(cidStr)\n\n if (existingJob != null) {\n this.log('join existing request for %c', cid)\n existingJob.observers++\n return existingJob.promise\n }\n\n const deferred: DeferredPromise<Uint8Array> = pDefer()\n const request = {\n promise: deferred.promise,\n observers: 1,\n queryFilter: createScalableCuckooFilter(this.cidPeerFilterSize)\n }\n this.requests.set(cidStr, request)\n\n // if this is the first time this session has been used\n let first = false\n\n if (this.initialPeerSearchComplete == null) {\n first = true\n this.log = this.logger.forComponent(`${this.logName}:${cid}`)\n this.initialPeerSearchComplete = this.findProviders(cid, this.minProviders, options)\n }\n\n let foundBlock = false\n\n // this queue manages outgoing requests - as new peers are added to the\n // session they will be added to the queue so we can request the current\n // block from multiple peers as they are discovered\n const queue = new Queue<Uint8Array, { provider: Provider, priority?: number } & AbortOptions>({\n concurrency: this.maxProviders\n })\n queue.addEventListener('failure', (evt) => {\n this.log.error('error querying provider %s, evicting from session - %e', evt.detail.job.options.provider, evt.detail.error)\n this.evict(evt.detail.job.options.provider)\n })\n queue.addEventListener('success', (evt) => {\n // peer has sent block, return it to the caller\n foundBlock = true\n deferred.resolve(evt.detail.result)\n })\n queue.addEventListener('idle', () => {\n if (foundBlock) {\n this.log.trace('session idle, found block')\n // we either found the block or the user gave up\n return\n }\n\n if (options.signal?.aborted === true) {\n this.log.trace('session idle, signal aborted')\n return\n }\n\n // find more session peers and retry\n Promise.resolve()\n .then(async () => {\n this.log('no session peers had block for for %c, finding new providers', cid)\n\n // evict this.minProviders random providers to make room for more\n for (let i = 0; i < this.minProviders; i++) {\n if (this.providers.length === 0) {\n break\n }\n\n const provider = this.providers[Math.floor(Math.random() * this.providers.length)]\n this.evict(provider)\n }\n\n // find new providers for the CID\n await this.findProviders(cid, this.minProviders, options)\n\n // keep trying until the abort signal fires\n this.log('found new providers re-retrieving %c', cid)\n this.requests.delete(cidStr)\n deferred.resolve(await this.retrieve(cid, options))\n })\n .catch(err => {\n this.log.error('could not find new providers for %c - %e', cid, err)\n deferred.reject(err)\n })\n })\n\n const peerAddedToSessionListener = (event: CustomEvent<Provider>): void => {\n const filterKey = this.toFilterKey(event.detail)\n\n if (request.queryFilter.has(filterKey)) {\n return\n }\n\n request.queryFilter.add(filterKey)\n\n // dispatch progress notification\n this.emitFoundProviderProgressEvent(cid, event.detail, options)\n\n queue.add(async () => {\n return this.queryProvider(cid, event.detail, options)\n }, {\n provider: event.detail\n })\n .catch(err => {\n if (options.signal?.aborted === true) {\n // skip logging error if signal was aborted because abort can happen\n // on success (e.g. another session found the block)\n return\n }\n\n this.log.error('error retrieving session block for %c - %e', cid, err)\n })\n }\n\n // add new session peers to query as they are discovered\n this.addEventListener('provider', peerAddedToSessionListener)\n\n if (first) {\n try {\n await raceSignal(this.initialPeerSearchComplete, options.signal)\n\n if (first) {\n this.log('found initial session peers for %c', cid)\n }\n } catch (err) {\n if (first) {\n this.log('failed to find initial session peers for %c - %e', cid, err)\n }\n\n this.requests.delete(cidStr)\n\n if (request.observers > 1) {\n // only need to reject request if another context is now also waiting\n // for the result - otherwise we can end up with an unhandled promise\n // rejection\n deferred.reject(err)\n }\n\n throw err\n }\n }\n\n // query each session peer directly\n Promise.all(\n [...this.providers]\n .filter(provider => {\n const filterKey = this.toFilterKey(provider)\n const has = request.queryFilter.has(filterKey)\n\n if (!has) {\n request.queryFilter.add(this.toFilterKey(provider))\n }\n\n return !has\n })\n .map(async (provider) => {\n return queue.add(async () => this.queryProvider(cid, provider, options), {\n provider\n })\n })\n )\n .catch(err => {\n if (options.signal?.aborted === true) {\n // skip logging error if signal was aborted because abort can happen\n // on success (e.g. another session found the block)\n return\n }\n\n this.log.error('error retrieving session block for %c - %e', cid, err)\n })\n\n const signalAbortedListener = (): void => {\n deferred.reject(new AbortError(options.signal?.reason ?? 'Session aborted'))\n queue.abort()\n }\n\n options.signal?.addEventListener('abort', signalAbortedListener)\n\n try {\n return await deferred.promise\n } finally {\n this.removeEventListener('provider', peerAddedToSessionListener)\n options.signal?.removeEventListener('abort', signalAbortedListener)\n queue.clear()\n this.requests.delete(cidStr)\n }\n }\n\n evict (provider: Provider): void {\n this.evictionFilter.add(this.toFilterKey(provider))\n const index = this.providers.findIndex(prov => this.equals(prov, provider))\n\n if (index === -1) {\n return\n }\n\n this.providers.splice(index, 1)\n }\n\n isEvicted (provider: Provider): boolean {\n return this.evictionFilter.has(this.toFilterKey(provider))\n }\n\n hasProvider (provider: Provider): boolean {\n // dedupe existing gateways\n if (this.providers.find(prov => this.equals(prov, provider)) != null) {\n return true\n }\n\n // dedupe failed session peers\n if (this.isEvicted(provider)) {\n return true\n }\n\n return false\n }\n\n async addPeer (peer: CID | Multiaddr | Multiaddr[], options?: AbortOptions): Promise<void> {\n const provider = await this.convertToProvider(peer, 'manually-added', options)\n\n if (provider == null || this.hasProvider(provider)) {\n return\n }\n\n this.providers.push(provider)\n\n // let the new peer join current queries\n this.safeDispatchEvent('provider', {\n detail: provider\n })\n }\n\n private async findProviders (cid: CID, count: number, options: BlockRetrievalOptions<RetrieveBlockProgressEvents>): Promise<void> {\n const deferred: DeferredPromise<void> = pDefer()\n let found = 0\n\n // run async to resolve the deferred promise when `count` providers are\n // found but continue util this.providers reaches this.maxProviders\n void Promise.resolve()\n .then(async () => {\n this.log('finding %d-%d new provider(s) for %c - %d initial providers', count, this.maxProviders, cid, this.initialProviders.length)\n\n const self = this\n\n // process any specific providers for this session\n const initialProviders = async function * (): AsyncGenerator<Provider> {\n while (self.initialProviders.length > 0) {\n const initialProvider = self.initialProviders.pop()\n\n if (initialProvider == null) {\n continue\n }\n\n const provider = await self.convertToProvider(initialProvider, 'manual', options)\n\n if (provider == null) {\n continue\n }\n\n yield provider\n }\n }\n\n const providers = async function * (): AsyncGenerator<Provider> {\n yield * initialProviders()\n yield * self.findNewProviders(cid, options)\n }\n\n // still not got enough providers, search routing for more\n for await (const provider of providers()) {\n if (this.providers.length === this.maxProviders || options.signal?.aborted === true) {\n break\n }\n\n if (this.hasProvider(provider)) {\n continue\n }\n\n this.log('found %d providers, %d in session', found, this.providers.length)\n this.providers.push(provider)\n\n // let the new peer join current queries\n this.safeDispatchEvent('provider', {\n detail: provider\n })\n\n found++\n\n if (this.providers.length === count) {\n this.log('session is ready with %d peer(s), new peers present', this.providers.length)\n deferred.resolve()\n // continue finding peers until we reach this.maxProviders\n }\n\n if (this.providers.length === this.maxProviders) {\n this.log('found max session peers %d', this.providers.length)\n break\n }\n }\n\n this.log('found %d new session peers while trying to find %d, %d in session', found, count, this.providers.length)\n\n if (this.providers.length < count) {\n throw new InsufficientProvidersError(`Found ${found} of ${count} ${this.name} providers for ${cid}, ${this.providers.length} in session after evictions`)\n }\n })\n .catch(err => {\n this.log.error('error searching routing for potential session peers for %c - %e', cid, err)\n deferred.reject(err)\n })\n\n return deferred.promise\n }\n\n /**\n * If this session was created with specific providers, convert one of them\n * into the format required or return `undefined` if the provider is not\n * compatible with this session implementation\n */\n abstract convertToProvider (provider: CID | Multiaddr | Multiaddr[], routing: string, options?: AbortOptions): Promise<Provider | undefined>\n\n /**\n * This method should search for new providers and yield them.\n */\n abstract findNewProviders (cid: CID, options: BlockRetrievalOptions<RetrieveBlockProgressEvents>): AsyncGenerator<Provider>\n\n /**\n * The subclass should contact the provider and request the block from it.\n *\n * If the provider cannot provide the block an error should be thrown.\n *\n * The provider will then be excluded from ongoing queries.\n */\n abstract queryProvider (cid: CID, provider: Provider, options: AbortOptions): Promise<Uint8Array>\n\n /**\n * Turn a provider into a concise Uint8Array representation for use in a Bloom\n * or Cuckoo filter\n */\n abstract toFilterKey (provider: Provider): Uint8Array | string\n\n /**\n * Return `true` if we consider one provider to be the same as another\n */\n abstract equals (providerA: Provider, providerB: Provider): boolean\n\n /**\n * Invoke the progress handler with the session-specific found provider event\n */\n abstract emitFoundProviderProgressEvent (cid: CID, provider: Provider, options: BlockRetrievalOptions<RetrieveBlockProgressEvents>): void\n}\n", "import { CID } from 'multiformats/cid'\n\nexport function isCID (obj?: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AA2B,iBAAkBC,CAAG,CAAC,CAC5E,CAEJ,GAAC,CAAG,CAAC,CACP,SACEN,EAAW,CACb,CAEA,KAAK,IAAI,aAAa,CACxB",
6
6
  "names": ["require_truncate", "__commonJSMin", "exports", "module", "isHighSurrogate", "codePoint", "isLowSurrogate", "getLength", "string", "byteLength", "charLength", "curByteLength", "segment", "i", "require_browser", "__commonJSMin", "exports", "module", "isHighSurrogate", "codePoint", "isLowSurrogate", "string", "charLength", "byteLength", "prevCodePoint", "i", "require_browser", "__commonJSMin", "exports", "module", "truncate", "getLength", "require_sanitize_filename", "__commonJSMin", "exports", "module", "truncate", "illegalRe", "controlRe", "reservedRe", "windowsReservedRe", "replaceTrailingDotsAndSpaces", "str", "replacement", "end", "sanitize", "input", "sanitized", "options", "output", "require_eventemitter3", "__commonJSMin", "exports", "module", "has", "prefix", "Events", "EE", "fn", "context", "once", "addListener", "emitter", "event", "listener", "evt", "clearEvent", "EventEmitter", "names", "events", "name", "handlers", "l", "ee", "listeners", "a1", "a2", "a3", "a4", "a5", "len", "args", "i", "length", "j", "require_hashlru", "__commonJSMin", "exports", "module", "max", "size", "cache", "_cache", "update", "key", "value", "v", "index_exports", "__export", "AbstractSession", "Helia", "breadthFirstWalker", "depthFirstWalker", "isCID", "naturalOrderWalker", "alloc", "size", "allocUnsafe", "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", "isArrayBufferBacked", "arr", "withArrayBuffer", "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", "withArrayBuffer", "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", "empty", "equals", "aa", "bb", "ii", "coerce", "o", "toArrayBufferBackedArray", "fromString", "str", "toString", "b", "isByteArrayWithArrayBuffer", "toArrayBufferBackedArray", "base", "ALPHABET", "name", "BASE_MAP", "j", "x", "xc", "BASE", "LEADER", "FACTOR", "iFACTOR", "encode", "source", "zeroes", "length", "pbegin", "pend", "size", "b58", "carry", "i", "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", "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", "base32_exports", "__export", "base32", "base32hex", "base32hexpad", "base32hexpadupper", "base32hexupper", "base32pad", "base32padupper", "base32upper", "base32z", "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", "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", "json_exports", "__export", "code", "decode", "encode", "name", "textEncoder", "textDecoder", "node", "data", "raw_exports", "__export", "code", "decode", "encode", "name", "name", "code", "encode", "node", "coerce", "decode", "data", "identity_exports", "__export", "identity", "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", "toArrayBufferBackedArray", "code", "name", "encode", "coerce", "digest", "input", "options", "create", "identity", "sha2_browser_exports", "__export", "sha256", "sha512", "DEFAULT_MIN_DIGEST_LENGTH", "from", "name", "code", "encode", "minDigestLength", "maxDigestLength", "Hasher", "input", "options", "result", "createDigest", "digest", "truncate", "create", "sha", "name", "data", "sha256", "from", "sha512", "format", "link", "base", "bytes", "version", "toStringV0", "baseCache", "base58btc", "toStringV1", "base32", "cache", "baseCache", "cid", "CID", "_CID", "version", "code", "multihash", "bytes", "toArrayBufferBackedArray", "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", "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", "streamMessage", "buf", "codec", "opts", "reader", "createReader", "CODEC_TYPES", "createCodec", "name", "type", "encode", "decode", "stream", "enumeration", "v", "findValue", "val", "encode", "writer", "enumValue", "decode", "reader", "stream", "createCodec", "CODEC_TYPES", "message", "encode", "decode", "stream", "createCodec", "CODEC_TYPES", "KeyType", "__KeyTypeValues", "enumeration", "PublicKeyMessage", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "prefix", "encode", "encodeMessage", "decode", "buf", "decodeMessage", "stream", "streamMessage", "PrivateKeyMessage", "toString", "array", "encoding", "base", "bases_default", "pathSepS", "pathSepB", "pathSep", "Key", "_Key", "s", "clean", "fromString", "encoding", "toString", "list", "other", "bytes", "key", "list1", "list2", "c1", "c2", "ns", "namespaceType", "namespaceValue", "p", "keys", "flatten", "parts", "arr", "import_sanitize_filename", "isByteArrayWithArrayBuffer", "b", "asUint8Array", "buf", "concat", "arrays", "length", "acc", "curr", "output", "allocUnsafe", "offset", "arr", "asUint8Array", "InvalidParametersError", "DecryptionFailedError", "equals", "a", "b", "i", "symbol", "findBufAndOffset", "bufs", "index", "offset", "buf", "bufEnd", "isUint8ArrayList", "value", "Uint8ArrayList", "_Uint8ArrayList", "data", "length", "chunk", "res", "i", "bytes", "beginInclusive", "endExclusive", "concat", "list", "bufStart", "sliceStartInBuf", "sliceEndsInBuf", "start", "search", "needle", "M", "radix", "rightmostPositions", "c", "j", "right", "lastIndex", "lastPatIndex", "skip", "char", "byteOffset", "allocUnsafe", "littleEndian", "alloc", "other", "equals", "acc", "curr", "TAG_MASK", "LONG_LENGTH_MASK", "LONG_LENGTH_BYTES_MASK", "decoders", "readSequence", "readInteger", "readBitString", "readOctetString", "readNull", "readObjectIdentifier", "decodeDer", "buf", "context", "tag", "readLength", "length", "count", "str", "i", "entries", "result", "start", "end", "vals", "finalOffset", "byte", "val1", "val2", "oid", "num", "val", "unusedBits", "bytes", "encodeNumber", "value", "number", "array", "Uint8ArrayList", "encodeLength", "encodeInteger", "contents", "mask", "encodeBitString", "encodeOctetString", "encodeSequence", "values", "output", "withArrayBuffer", "InvalidParametersError", "OID_256", "OID_384", "OID_521", "P_256_KEY_JWK", "P_384_KEY_JWK", "P_521_KEY_JWK", "P_256_KEY_LENGTH", "P_384_KEY_LENGTH", "P_521_KEY_LENGTH", "ECDSAPublicKey", "jwk", "identity", "CID", "base58btc", "PublicKeyMessage", "publicKeyToPKIMessage", "message", "signature", "options", "key", "isValid", "withArrayBuffer", "ECDSAPrivateKey", "publicKey", "PrivateKeyMessage", "privateKeyToPKIMessage", "sig", "ECDSACrypto", "curve", "keyPair", "privateKeyJwk", "publicKeyJwk", "buf", "InvalidParametersError", "pkiToPublicJWK", "pkiMessageToPrivateJWK", "privateJWKToPublicJWK", "ecdsaCrypto", "decodeDer", "privateKey", "d", "base64url", "coordinates", "offset", "x", "y", "encodeSequence", "encodeInteger", "getOID", "encodeBitString", "Uint8ArrayList", "encodeOctetString", "PRIVATE_KEY_LENGTH", "Ed25519PublicKey", "jwk", "identity", "CID", "base58btc", "PublicKeyMessage", "base64url", "message", "signature", "options", "key", "isValid", "withArrayBuffer", "Ed25519PrivateKey", "publicKey", "PrivateKeyMessage", "concat", "sig", "Ed25519Crypto", "keyPair", "privateKeyJwk", "publicKeyJwk", "buf", "InvalidParametersError", "x5519ToPublicJWK", "derivePrivateJWK", "privateJWKToPublicJWK", "ed25519Crypto", "raw", "privateKey", "pkcs8", "convertRawX25519KeyToPKCS", "PKCS8_HEADER", "MAX_RSA_KEY_SIZE", "RSAPublicKey", "jwk", "digest", "rsaKeySize", "InvalidParametersError", "CID", "base36", "publicKeyToProtobuf", "message", "signature", "options", "key", "result", "withArrayBuffer", "RSAPrivateKey", "publicKey", "privateKeyToProtobuf", "sig", "RSACrypto", "modulusLength", "keypair", "jwkPrivateKey", "jwkPublicKey", "publicKeyId", "buf", "PublicKeyMessage", "publicKeyJwk", "pkixMessageToJwk", "PrivateKeyMessage", "pkcs1", "decodeDer", "privateKeyJwk", "pkcs1MessageToJwk", "privateJWKToPublicJWK", "rsaCrypto", "base64url", "jwkToPkcs1", "encodeSequence", "encodeInteger", "RSA_ALGORITHM_IDENTIFIER", "jwkToPkix", "encodeBitString", "cert", "keys", "data", "sha256", "code", "privateKeyFromPEM", "pem", "cipher", "options", "decoded", "base64", "der", "decodeDer", "salt", "iterations", "toNumber", "keyLength", "iv", "keyData", "plainText", "pkcs1", "pb", "PrivateKeyMessage", "rsaCrypto", "buf", "str", "n", "keyPrefix", "infoPrefix", "serviceCapabilities", "KEYCHAIN_DEK_INIT", "fromString", "PRIVATE_KEY_DEK_INIT", "MIN_PASS_LENGTH", "NIST", "KEY_LENGTHS", "validateKeyName", "name", "sanitize", "dsName", "Key", "dsInfoName", "keyId", "key", "options", "pb", "hash", "sha256", "base58btc", "getSalt", "salt", "withArrayBuffer", "Keychain", "components", "init", "InvalidParametersError", "createAESCipher", "batch", "privateKey", "cipher", "result", "cipherText", "concat", "encodedText", "base64", "keyInfo", "keyBuf", "keyText", "toString", "cryptoImpl", "privateKeyFromPEM", "decoded", "iv", "plainText", "PrivateKeyMessage", "DecryptionFailedError", "err", "query", "value", "oldName", "newName", "oldDatastoreName", "newDatastoreName", "oldInfoName", "newInfoName", "pem", "res", "password", "oldCipher", "newCipher", "info", "buf", "PublicKeyMessage", "derivedEmptyPasswordKey", "keychainDekOpts", "privateKeyDekOpts", "keychainDek", "deriveKey", "usages", "opts", "cryptoKey", "pass", "rawKey", "createKeychainDek", "encrypt", "data", "ciphertext", "decrypt", "plaintext", "keychain", "init", "components", "Keychain", "AbortError", "message", "InvalidParametersError", "message", "NotFoundError", "message", "InvalidMultihashError", "message", "isStartable", "obj", "start", "objs", "startables", "s", "stop", "isEventObject", "obj", "isOnce", "options", "TypedEventEmitter", "#listeners", "type", "listeners", "listener", "once", "evt", "list", "callback", "detail", "CustomProgressEvent", "type", "detail", "DNSQueryFailedError", "import_index", "TimeoutError", "_TimeoutError", "message", "options", "getAbortedReason", "signal", "pTimeout", "promise", "milliseconds", "fallback", "customTimers", "timer", "abortHandler", "cancelablePromise", "resolve", "reject", "timeoutError", "error", "lowerBound", "array", "value", "comparator", "first", "count", "step", "it", "compactionThreshold", "PriorityQueue", "#queue", "#head", "run", "options", "priority", "id", "size", "element", "#compact", "index", "lowerBound", "a", "b", "item", "idOrRun", "result", "PQueue", "EventEmitter", "#carryoverIntervalCount", "#isIntervalIgnored", "#intervalCount", "#intervalCap", "#rateLimitedInInterval", "#rateLimitFlushScheduled", "#interval", "#intervalEnd", "#lastExecutionTime", "#intervalId", "#timeoutId", "#strict", "#strictTicks", "#strictTicksStartIndex", "#queue", "#queueClass", "#pending", "#concurrency", "#isPaused", "#idAssigner", "#runningTasks", "#queueAbortListenerCleanupFunctions", "options", "PriorityQueue", "#setupRateLimitTracking", "#cleanupStrictTicks", "now", "oldestTick", "#consumeIntervalSlot", "#rollbackIntervalSlot", "#getActiveTicksCount", "#doesIntervalAllowAnother", "#doesConcurrentAllowAnother", "#next", "#tryToStartAnother", "#onResumeInterval", "#onInterval", "#initializeIntervalIfNeeded", "#isIntervalPausedAt", "delay", "#createIntervalTimeout", "timeSinceLastExecution", "#clearIntervalTimer", "#clearTimeoutTimer", "taskStarted", "canInitializeInterval", "job", "#scheduleRateLimitUpdate", "#processQueue", "newConcurrency", "id", "priority", "function_", "resolve", "reject", "taskSymbol", "cleanupQueueAbortHandler", "run", "eventListener", "error", "#rollbackIntervalConsumption", "operation", "pTimeout", "signal", "_resolve", "result", "removeQueuedTask", "queueAbortHandler", "functions", "#updateRateLimitState", "#onEvent", "limit", "handleError", "event", "filter", "listener", "previous", "count", "shouldBeRateLimited", "task", "getTypes", "types", "DEFAULT_TYPES", "RecordType", "DEFAULT_TTL", "toDNSResponse", "obj", "question", "RecordType", "answer", "toString", "DEFAULT_QUERY_CONCURRENCY", "dnsJsonOverHttps", "url", "init", "httpQueue", "PQueue", "fqdn", "options", "log", "searchParams", "getTypes", "type", "RecordType", "CustomProgressEvent", "response", "res", "toDNSResponse", "defaultResolver", "dnsJsonOverHttps", "import_hashlru", "CachedAnswers", "maxSize", "hashlru", "fqdn", "types", "foundAllAnswers", "answers", "type", "cached", "toDNSResponse", "domain", "key", "cachedAnswers", "entry", "expires", "value", "RecordType", "answer", "DEFAULT_TTL", "cache", "size", "DEFAULT_ANSWER_CACHE_SIZE", "DNS", "init", "cache", "tld", "resolver", "defaultResolver", "domain", "options", "types", "getTypes", "cached", "CustomProgressEvent", "resolvers", "errors", "result", "answer", "err", "DNSQueryFailedError", "RecordType", "dns", "init", "DNS", "ms", "value", "options", "parse", "format", "str", "match", "unit", "n", "matchUnit", "fmtShort", "ms$1", "msAbs", "fmtLong", "plural", "format", "options", "n", "name", "isPlural", "setup", "env", "createDebug", "coerce", "disable", "enable", "enabled", "ms", "destroy", "key", "selectColor", "namespace", "hash", "i", "options", "prevTime", "enableOverride", "namespacesCache", "enabledCache", "debug", "args", "self", "curr", "index", "match", "format", "formatter", "val", "extend", "v", "delimiter", "newDebug", "namespaces", "split", "len", "toNamespace", "name", "regexp", "storage", "localstorage", "colors", "useColors", "formatArgs", "args", "ms", "c", "index", "lastC", "match", "log", "save", "namespaces", "load", "setupFormatters", "formatters", "v", "error", "browser_default", "setup", "src_default", "browser_default", "src_default", "v", "base58btc", "base32", "base36", "base64", "printError", "formatError", "indent", "message", "notEmpty", "stack", "isAggregateError", "err", "output", "createDisabledLogger", "namespace", "logger", "defaultLogger", "options", "name", "logger", "trace", "createDisabledLogger", "src_default", "r", "scope", "notEmpty", "str", "BaseBlockstore", "key", "options", "val", "source", "cid", "bytes", "NotFoundError", "_NotFoundError", "message", "isAsyncIterable", "thing", "all", "source", "arr", "entry", "src_default", "isPromise", "p", "MemoryBlockstore", "BaseBlockstore", "key", "val", "options", "buf", "result", "src_default", "base32", "NotFoundError", "value", "CID", "code", "decode", "src_default", "v", "base58btc", "base32", "base64", "formatError", "indent", "message", "notEmpty", "stack", "isAggregateError", "err", "printError", "output", "createDisabledLogger", "namespace", "logger", "logger", "name", "options", "trace", "createDisabledLogger", "src_default", "r", "scope", "notEmpty", "str", "peekable", "iterable", "iterator", "symbol", "queue", "value", "src_default", "isAsyncIterable", "thing", "filter", "source", "fn", "index", "entry", "peekable", "src_default", "value", "done", "res", "func", "pDefer", "deferred", "resolve", "reject", "defaultTranslate", "signal", "raceSignal", "promise", "opts", "translateError", "listener", "resolve", "reject", "QueuelessPushable", "pDefer", "nextResult", "err", "result", "value", "options", "raceSignal", "queuelessPushable", "isAsyncIterable", "thing", "addAllToPushable", "sources", "output", "signal", "source", "item", "err", "mergeSources", "controller", "queuelessPushable", "mergeSyncSources", "syncSources", "merge", "src_default", "log", "logger", "SHARDING_FN", "isAsyncIterable", "thing", "drain", "source", "_", "src_default", "isAsyncIterable", "thing", "sort", "source", "sorter", "src_default", "isAsyncIterable", "thing", "take", "source", "limit", "items", "entry", "src_default", "BaseDatastore", "key", "val", "options", "source", "value", "puts", "dels", "src_default", "q", "it", "prefix", "e", "f", "offset", "i", "MemoryDatastore", "BaseDatastore", "key", "val", "options", "result", "NotFoundError", "q", "value", "Key", "FixedFIFO", "hwm", "data", "last", "FIFO", "options", "obj", "val", "prev", "next", "AbortError", "message", "code", "pushable", "options", "_pushable", "buffer", "next", "_pushable", "getNext", "options", "onEnd", "buffer", "FIFO", "pushable", "onNext", "ended", "drain", "pDefer", "waitNext", "resolve", "reject", "next", "err", "bufferNext", "bufferError", "push", "value", "end", "_return", "_throw", "signal", "cancel", "listener", "AbortError", "opts", "shardKey", "Key", "SHARDING_FN", "log", "logger", "objectTypeNames", "is", "value", "typeOf", "objectType", "getObjectType", "objectTypeName", "Type", "major", "name", "terminal", "typ", "a", "b", "Token", "type", "value", "encodedLength", "useBuffer", "textEncoder", "isBuffer", "buf", "asU8A", "FROM_STRING_THRESHOLD_BUFFER", "FROM_STRING_THRESHOLD_TEXTENCODER", "fromString", "string", "utf8ToBytes", "fromArray", "arr", "slice", "bytes", "start", "end", "concat", "chunks", "length", "c", "out", "off", "b", "alloc", "size", "compare", "b1", "b2", "isBuffer", "i", "utf8ToBytes", "str", "out", "p", "c", "MAX_ARGUMENTS_LENGTH", "decodeCodePointsArray", "codePoints", "len", "res", "defaultChunkSize", "Bl", "chunkSize", "bytes", "topChunk", "chunkPos", "alloc", "reset", "byts", "chunk", "slice", "concat", "U8Bl", "dest", "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", "writer", "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", "writer", "token", "negint", "unsigned", "encodeUintValue", "uintBoundaries", "tok1", "tok2", "toToken", "data", "pos", "prefix", "length", "assertEnoughData", "buf", "Token", "Type", "decodeBytesCompact", "minor", "_options", "decodeBytes8", "_minor", "options", "readUint8", "decodeBytes16", "readUint16", "decodeBytes32", "readUint32", "decodeBytes64", "l", "readUint64", "decodeErrPrefix", "tokenBytes", "token", "fromString", "encodeBytes", "writer", "bytes", "encodeUintValue", "tok1", "tok2", "compareBytes", "b1", "b2", "compare", "textDecoder", "ASCII_THRESHOLD", "toStr", "bytes", "start", "end", "str", "i", "c", "toToken", "data", "pos", "prefix", "length", "options", "totLength", "assertEnoughData", "tok", "Token", "Type", "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", "writer", "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", "writer", "token", "encodeUintValue", "encodeUint", "decodeTagCompact", "_data", "_pos", "minor", "_options", "Token", "Type", "decodeTag8", "data", "pos", "_minor", "options", "readUint8", "decodeTag16", "readUint16", "decodeTag32", "readUint32", "decodeTag64", "readUint64", "encodeTag", "writer", "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", "writer", "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", "rfc8949EncodeOptions", "rfc8949MapSorter", "makeCborEncoders", "encoders", "Type", "encodeUint", "encodeNegint", "encodeBytes", "encodeString", "encodeArray", "encodeMap", "encodeTag", "encodeFloat", "cborEncoders", "defaultWriter", "Bl", "Ref", "_Ref", "obj", "parent", "p", "stack", "encodeErrPrefix", "simpleTokens", "Token", "typeEncoders", "_typ", "_options", "_refStack", "_obj", "options", "refStack", "entries", "i", "e", "objectToTokens", "typ", "isMap", "keys", "maxLength", "skipUndefined", "key", "value", "sortMapEntries", "is", "customTypeEncoder", "tokens", "typeEncoder", "e1", "e2", "keyToken1", "keyToken2", "major", "tcmp", "t1", "t2", "encodeRfc8949", "compare", "data", "encodeCustom", "tokensToEncoded", "writer", "token", "MAJOR_UINT", "MAJOR_NEGINT", "MAJOR_BYTES", "MAJOR_STRING", "MAJOR_ARRAY", "SIMPLE_FALSE", "MINOR_FALSE", "SIMPLE_TRUE", "MINOR_TRUE", "SIMPLE_NULL", "MINOR_NULL", "SIMPLE_UNDEFINED", "MINOR_UNDEFINED", "neg1b", "pos1b", "canDirectEncode", "directEncode", "customEncoder", "encodeUintValue", "bytes", "fromString", "elem", "destination", "hasDest", "writeTo", "U8Bl", "quickBytes", "encoder", "size", "asU8A", "encode", "defaultDecodeOptions", "Tokeniser", "data", "options", "byt", "token", "quick", "decoder", "jump", "decodeErrPrefix", "minor", "DONE", "BREAK", "tokenToArray", "tokeniser", "arr", "value", "tokensToObject", "tokenToMap", "useMaps", "rejectDuplicateMapKeys", "obj", "m", "i", "key", "tokenToMapEntries", "createTagDecodeControl", "called", "decode", "Type", "entries", "entry", "decodeControl", "result", "decodeFirst", "u8aData", "asU8A", "decoded", "remainder", "Tagged", "_Tagged", "tag", "value", "decode", "tagNumbers", "tags", "AlreadyPinnedError", "BlockPinnedError", "InvalidDatastoreVersionError", "InvalidConfigurationError", "GetFailedError", "LoadBlockFailedError", "BlockNotFoundWhileOfflineError", "FNV_PRIMES", "FNV_OFFSETS", "cachedEncoder", "fnv1aUint8Array", "uint8Array", "size", "fnvPrime", "hash", "index", "fnv1aEncodeInto", "string", "utf8Buffer", "remaining", "result", "fnv1a", "value", "fnv1a", "input", "seed", "numberToBuffer", "num", "hex", "fromString", "MAX_FINGERPRINT_SIZE", "Fingerprint", "buf", "hash", "seed", "fingerprintSize", "fnv", "fp", "alloc", "i", "other", "equals", "getRandomInt", "min", "max", "Bucket", "size", "fingerprint", "Fingerprint", "fp", "i", "getRandomInt", "current", "found", "maxCuckooCount", "CuckooFilter", "init", "fnv1a", "getRandomInt", "item", "fromString", "fingerprint", "Fingerprint", "j", "k", "Bucket", "rand", "i", "n", "swapped", "inJ", "inK", "MAX_LOAD", "calculateBucketSize", "errorRate", "optimize", "maxItems", "bucketSize", "load", "filterSize", "fingerprintSize", "MAX_FINGERPRINT_SIZE", "ScalableCuckooFilter", "init", "fnv1a", "getRandomInt", "CuckooFilter", "item", "fromString", "current", "cuckoo", "curSize", "i", "acc", "curr", "createScalableCuckooFilter", "maxItems", "errorRate", "options", "optimize", "normalizeEmitter", "emitter", "addListener", "removeListener", "pEventMultiple", "event", "options", "cancel", "returnValue", "resolve", "reject", "events", "items", "onItem", "arguments_", "value", "error", "rejectHandler", "rejectionEvent", "timeout", "pTimeout", "pEvent", "arrayPromise", "promise", "array", "debounce", "func", "wait", "timeout", "output", "later", "QueueFullError", "message", "JobRecipient", "options", "pDefer", "AbortError", "randomId", "Job", "fn", "options", "err", "acc", "curr", "AbortError", "recipient", "JobRecipient", "result", "raceSignal", "evt", "Queue", "TypedEventEmitter", "init", "debounce", "job", "j", "i", "fn", "options", "QueueFullError", "Job", "result", "err", "AbortError", "pEvent", "limit", "stream", "pushable", "cleanup", "onQueueJobComplete", "evt", "onQueueFailure", "onQueueIdle", "onSignalAbort", "anySignal", "signals", "controller", "onAbort", "reason", "signal", "clear", "isAsyncIterable", "thing", "toBuffer", "source", "buffer", "buf", "concat", "bufs", "length", "src_default", "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", "depthFirstWalker", "init", "components", "DepthFirstGraphWalker", "breadthFirstWalker", "BreadthFirstGraphWalker", "naturalOrderWalker", "NaturalOrderGraphWalker", "AbstractGraphWalker", "cid", "options", "queue", "gen", "src_default", "node", "finished", "maxDepth", "job", "opts", "bytes", "block", "createUnsafe", "linkedCid", "err", "Queue", "a", "b", "DATASTORE_PIN_PREFIX", "DATASTORE_BLOCK_PREFIX", "DATASTORE_ENCODING", "base36", "toDSKey", "cid", "Key", "PinsImpl", "datastore", "blockstore", "getCodec", "options", "pinKey", "AlreadyPinnedError", "depth", "InvalidParametersError", "walker", "depthFirstWalker", "node", "childCid", "#updatePinnedBlock", "pinnedBlock", "c", "equals", "pin", "encode", "withPinnedBlock", "blockKey", "decode", "err", "CustomProgressEvent", "buf", "key", "value", "CID", "metadata", "InsufficientProvidersError", "message", "NoRoutersAvailableError", "UnknownHashAlgorithmError", "UnknownCodecError", "UnknownCryptoError", "DEFAULT_PROVIDER_LOOKUP_CONCURRENCY", "Routing", "components", "init", "start", "stop", "name", "r", "router", "key", "options", "NoRoutersAvailableError", "queue", "Queue", "foundProviders", "errors", "self", "routersFinished", "routers", "supports", "CustomProgressEvent", "prov", "err", "peer", "src_default", "job", "provider", "value", "result", "GetFailedError", "toString", "id", "source", "NotFoundError", "AbortError", "message", "rest", "raceEvent", "emitter", "eventName", "signal", "opts", "error", "AbortError", "errorEvent", "resolve", "reject", "removeListeners", "removeListener", "abortListener", "eventListener", "errorEventListener", "evt", "err", "addListener", "event", "listener", "isEventTarget", "QueueFullError", "message", "JobRecipient", "signal", "AbortError", "randomId", "Job", "fn", "options", "err", "acc", "curr", "AbortError", "recipient", "JobRecipient", "result", "raceSignal", "debounce", "func", "wait", "timeout", "output", "later", "Queue", "TypedEventEmitter", "init", "debounce", "job", "j", "i", "fn", "options", "QueueFullError", "Job", "result", "err", "AbortError", "raceEvent", "limit", "stream", "pushable", "cleanup", "onQueueJobComplete", "evt", "onQueueError", "onQueueIdle", "onSignalAbort", "WORKER_REQUEST_READ_LOCK", "WORKER_ABORT_READ_LOCK_REQUEST", "WORKER_RELEASE_READ_LOCK", "MASTER_GRANT_READ_LOCK", "MASTER_READ_LOCK_ERROR", "WORKER_REQUEST_WRITE_LOCK", "WORKER_ABORT_WRITE_LOCK_REQUEST", "WORKER_RELEASE_WRITE_LOCK", "MASTER_GRANT_WRITE_LOCK", "MASTER_WRITE_LOCK_ERROR", "WORKER_FINALIZE", "BROADCAST_CHANNEL_NAME", "defaultOptions", "handleChannelWorkerLockRequest", "emitter", "channel", "masterEvent", "abortMasterEvent", "requestType", "abortType", "errorType", "releaseType", "grantType", "event", "requestEvent", "resolve", "releaseEventListener", "releaseEvent", "err", "WORKER_FINALIZE", "nanoid", "size", "MorticeChannelWorker", "name", "BROADCAST_CHANNEL_NAME", "options", "WORKER_REQUEST_READ_LOCK", "WORKER_ABORT_READ_LOCK_REQUEST", "MASTER_GRANT_READ_LOCK", "MASTER_READ_LOCK_ERROR", "WORKER_RELEASE_READ_LOCK", "WORKER_REQUEST_WRITE_LOCK", "WORKER_ABORT_WRITE_LOCK_REQUEST", "MASTER_GRANT_WRITE_LOCK", "MASTER_WRITE_LOCK_ERROR", "WORKER_RELEASE_WRITE_LOCK", "WORKER_FINALIZE", "requestType", "abortType", "grantType", "errorType", "releaseType", "id", "nanoid", "resolve", "reject", "abortListener", "listener", "event", "err", "browser_default", "options", "defaultOptions", "channel", "BROADCAST_CHANNEL_NAME", "emitter", "TypedEventEmitter", "handleChannelWorkerLockRequest", "WORKER_REQUEST_READ_LOCK", "WORKER_ABORT_READ_LOCK_REQUEST", "MASTER_READ_LOCK_ERROR", "WORKER_RELEASE_READ_LOCK", "MASTER_GRANT_READ_LOCK", "WORKER_REQUEST_WRITE_LOCK", "WORKER_ABORT_WRITE_LOCK_REQUEST", "MASTER_WRITE_LOCK_ERROR", "WORKER_RELEASE_WRITE_LOCK", "MASTER_GRANT_WRITE_LOCK", "MorticeChannelWorker", "mutexes", "implementation", "isMortice", "obj", "getImplementation", "opts", "browser_default", "emitter", "event", "mutexName", "identifier", "mutex", "abortController", "abortListener", "release", "err", "createReleasable", "queue", "options", "res", "rej", "p", "resolve", "reject", "listener", "AbortError", "createMutex", "name", "masterQueue", "Queue", "readQueue", "localReadQueue", "readPromise", "defaultOptions", "createMortice", "options", "opts", "createMutex", "BlockStorage", "blockstore", "pins", "routing", "options", "createMortice", "start", "stop", "cid", "block", "releaseLock", "blocks", "cids", "BlockPinnedError", "storage", "root", "DS_VERSION_KEY", "Key", "CURRENT_VERSION", "assertDatastoreVersionIsCurrent", "datastore", "fromString", "buf", "str", "toString", "InvalidDatastoreVersionError", "src_exports", "__export", "code", "decode", "decodeOptions", "encode", "encodeOptions", "name", "toByteView", "CID_CBOR_TAG", "toByteView", "buf", "cidEncoder", "obj", "cid", "CID", "bytes", "Token", "Type", "undefinedEncoder", "numberEncoder", "num", "mapEncoder", "map", "key", "_encodeOptions", "encodeOptions", "cidDecoder", "decode", "_decodeOptions", "decodeOptions", "name", "code", "encode", "node", "data", "src_exports", "__export", "code", "decode", "encode", "format", "name", "parse", "JSONEncoder", "buf", "recurs", "Type", "token", "is", "isa", "i", "_buf", "_token", "encodeErrPrefix", "byts", "fromString", "asU8A", "dp", "mapSorter", "e1", "e2", "keyToken1", "keyToken2", "defaultEncodeOptions", "encode", "data", "options", "encodeCustom", "Tokenizer", "data", "options", "c", "str", "decodeErrPrefix", "i", "startPos", "negative", "float", "swallow", "chars", "ch", "Token", "Type", "numStr", "num", "l", "readu4", "u4", "readUtf8Char", "firstByte", "codePoint", "bytesPerSequence", "secondByte", "thirdByte", "fourthByte", "tempCodePoint", "ch1", "decodeCodePointsArray", "token", "decode", "toByteView", "buf", "cidEncoder", "obj", "cid", "CID", "cidString", "Token", "Type", "bytesEncoder", "bytes", "bytesString", "base64", "taBytesEncoder", "abBytesEncoder", "ab", "undefinedEncoder", "numberEncoder", "num", "encodeOptions", "DagJsonTokenizer", "Tokenizer", "data", "options", "token", "keyToken", "valueToken", "breakToken", "innerKeyToken", "innerValueToken", "i", "decodeOptions", "decode", "name", "code", "encode", "node", "format", "utf8Decoder", "utf8Decoder", "parse", "data", "decode", "utf8Encoder", "src_exports", "__export", "code", "createLink", "createNode", "decode", "encode", "name", "prepare", "validate", "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", "encodeLink", "link", "bytes", "i", "encodeVarint", "nameBytes", "encodeNode", "node", "size", "sizeNode", "index", "sizeLink", "n", "l", "sov", "offset", "v", "base", "x", "len64", "len8tab", "pbNodeProperties", "pbLinkProperties", "textEncoder", "linkComparator", "a", "b", "abuf", "bbuf", "x", "y", "i", "len", "hasOnlyProperties", "node", "properties", "p", "asLink", "link", "Hash", "CID", "pbl", "cid", "e", "prepare", "pbn", "validate", "createNode", "data", "links", "createLink", "name", "size", "toByteView", "buf", "name", "code", "encode", "node", "validate", "pbn", "l", "link", "encodeNode", "decode", "bytes", "buf", "toByteView", "decodeNode", "CID", "isPromise", "p", "getCodec", "initialCodecs", "loadCodec", "codecs", "code", "src_exports", "raw_exports", "json_exports", "codec", "res", "isPromise", "UnknownCodecError", "getCrypto", "initialCryptos", "loadCrypto", "cryptos", "ecdsaCrypto", "ed25519Crypto", "rsaCrypto", "crypto", "nameOrCode", "res", "isPromise", "UnknownCryptoError", "getHasher", "initialHashers", "loadHasher", "hashers", "sha256", "sha512", "identity", "hasher", "code", "res", "isPromise", "UnknownHashAlgorithmError", "IDENTITY_CODEC", "IdentityHashDigestTooLongError", "IdentityBlockstore", "BaseBlockstore", "child", "init", "key", "block", "options", "NotFoundError", "isAsyncIterable", "thing", "isPromise", "forEach", "source", "fn", "index", "val", "res", "peekable", "src_default", "value", "done", "func", "DEFAULT_MAX_IDENTITY_HASH_DIGEST_LENGTH", "Storage", "components", "init", "IdentityBlockstore", "cid", "block", "options", "CustomProgressEvent", "broker", "blocks", "missingBlocks", "src_default", "has", "notifyEach", "offline", "BlockNotFoundWhileOfflineError", "hasher", "raceBlockRetrievers", "cids", "blockBrokers", "validateFn", "getCidBlockVerifierFunction", "controller", "signal", "anySignal", "retrievers", "isRetrievingBlockBroker", "InvalidConfigurationError", "retriever", "blocksWereValidated", "err", "LoadBlockFailedError", "InvalidParametersError", "hash", "res", "isPromise", "equals", "InvalidMultihashError", "SessionStorage", "Storage", "components", "init", "peer", "options", "broker", "cid", "block", "signal", "anySignal", "blocks", "cids", "NetworkedStorage", "Storage", "components", "init", "start", "stop", "root", "options", "InvalidConfigurationError", "blockBrokers", "broker", "b", "SessionStorage", "AbstractSession", "TypedEventEmitter", "components", "init", "createScalableCuckooFilter", "cid", "options", "cidStr", "base64", "existingJob", "deferred", "pDefer", "request", "first", "foundBlock", "queue", "Queue", "evt", "i", "provider", "err", "peerAddedToSessionListener", "event", "filterKey", "raceSignal", "has", "signalAbortedListener", "AbortError", "index", "prov", "peer", "count", "found", "self", "initialProviders", "initialProvider", "providers", "InsufficientProvidersError", "isCID", "obj", "CID", "Helia", "init", "defaultLogger", "getHasher", "getCodec", "getCrypto", "dns", "TypedEventEmitter", "components", "MemoryBlockstore", "MemoryDatastore", "keychain", "Routing", "router", "broker", "networkedStorage", "NetworkedStorage", "PinsImpl", "BlockStorage", "name", "b", "blockBroker", "mixin", "assertDatastoreVersionIsCurrent", "start", "stop", "options", "releaseLock", "helia", "blockstore", "src_default", "cid", "CustomProgressEvent", "err"]
7
7
  }