@helia/ipns 9.2.1-73a28eda → 9.2.1-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
- "sources": ["../../../node_modules/timestamp-nano/dist/timestamp.min.js", "../src/index.ts", "../../../node_modules/multiformats/src/bases/base32.ts", "../../../node_modules/multiformats/src/bytes.ts", "../../../node_modules/multiformats/src/vendor/base-x.js", "../../../node_modules/multiformats/src/bases/base.ts", "../../../node_modules/multiformats/src/bases/base36.ts", "../../../node_modules/multiformats/src/bases/base58.ts", "../../../node_modules/multiformats/src/vendor/varint.js", "../../../node_modules/multiformats/src/varint.ts", "../../../node_modules/multiformats/src/hashes/digest.ts", "../../../node_modules/multiformats/src/cid.ts", "../src/constants.ts", "../src/errors.ts", "../src/selector.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/bases/base16.ts", "../../../node_modules/multiformats/src/bases/base2.ts", "../../../node_modules/multiformats/src/bases/base256emoji.ts", "../../../node_modules/multiformats/src/bases/base64.ts", "../../../node_modules/multiformats/src/bases/base8.ts", "../../../node_modules/multiformats/src/bases/identity.ts", "../../../node_modules/multiformats/src/codecs/json.ts", "../../../node_modules/multiformats/src/hashes/identity.ts", "../../../node_modules/multiformats/src/hashes/sha2-browser.ts", "../../../node_modules/multiformats/src/hashes/hasher.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", "../src/pb/ipns.ts", "../../../node_modules/uint8arrays/src/util/as-uint8array.ts", "../../../node_modules/uint8arrays/src/concat.ts", "../../../node_modules/uint8arrays/src/equals.ts", "../../../node_modules/@ipshipyard/crypto/src/index.ts", "../../../node_modules/@libp2p/interface/src/errors.ts", "../../../node_modules/main-event/src/index.ts", "../../../node_modules/cborg/lib/is.js", "../../../node_modules/cborg/lib/token.js", "../../../node_modules/cborg/lib/byte-utils.js", "../../../node_modules/cborg/lib/bl.js", "../../../node_modules/cborg/lib/common.js", "../../../node_modules/cborg/lib/0uint.js", "../../../node_modules/cborg/lib/1negint.js", "../../../node_modules/cborg/lib/2bytes.js", "../../../node_modules/cborg/lib/3string.js", "../../../node_modules/cborg/lib/4array.js", "../../../node_modules/cborg/lib/5map.js", "../../../node_modules/cborg/lib/6tag.js", "../../../node_modules/cborg/lib/7float.js", "../../../node_modules/cborg/lib/jump.js", "../../../node_modules/cborg/lib/encode.js", "../../../node_modules/cborg/lib/decode.js", "../../../node_modules/cborg/lib/tagged.js", "../../../node_modules/uint8arrays/src/to-string.ts", "../../../node_modules/interface-datastore/src/key.ts", "../src/utils.ts", "../src/validator.ts", "../src/ipns/resolver.ts", "../../../node_modules/progress-events/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/@libp2p/logger/src/index.ts", "../src/records.ts", "../src/ipns/publisher.ts", "../../../node_modules/p-defer/index.js", "../../../node_modules/it-pushable/src/fifo.ts", "../../../node_modules/it-pushable/src/index.ts", "../../../node_modules/p-timeout/index.js", "../../../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/race-signal/src/index.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/@libp2p/utils/src/repeating-task.ts", "../src/ipns/republisher.ts", "../../../node_modules/@libp2p/record/node_modules/protons-runtime/src/utils/float.ts", "../../../node_modules/@libp2p/record/node_modules/protons-runtime/src/utils/longbits.ts", "../../../node_modules/@libp2p/record/node_modules/protons-runtime/src/utils/utf8.ts", "../../../node_modules/@libp2p/record/node_modules/protons-runtime/src/utils/reader.ts", "../../../node_modules/@libp2p/record/node_modules/protons-runtime/src/decode.ts", "../../../node_modules/@libp2p/record/node_modules/protons-runtime/src/utils/pool.ts", "../../../node_modules/@libp2p/record/node_modules/protons-runtime/src/utils/writer.ts", "../../../node_modules/@libp2p/record/node_modules/protons-runtime/src/encode.ts", "../../../node_modules/@libp2p/record/node_modules/protons-runtime/src/stream.ts", "../../../node_modules/@libp2p/record/node_modules/protons-runtime/src/codec.ts", "../../../node_modules/@libp2p/record/node_modules/protons-runtime/src/codecs/message.ts", "../../../node_modules/@libp2p/record/src/record.ts", "../../../node_modules/@libp2p/record/src/utils.ts", "../../../node_modules/@libp2p/record/src/index.ts", "../../../node_modules/@libp2p/kad-dht/src/index.ts", "../src/pb/metadata.ts", "../src/local-store.ts", "../src/routing/helia.ts", "../src/routing/local-store.ts", "../src/ipns.ts"],
4
- "sourcesContent": ["var Timestamp=function(){\"undefined\"!=typeof module&&(module.exports=d);var l=86400,s=3200,T=146097*s/400,e=l*T,f=1e3*e,c=864e13,g=4294967296,h=1e6,u=\"000000000\",m=Math.trunc||function(n){var t=n-n%1;return 0==t&&(n<0||0===n&&1/n!=1/0)?-0:t},n=d.prototype,o=(d.fromDate=function(n){return new d(+n)},d.fromInt64BE=r(0,1,2,3,0,4),d.fromInt64LE=r(3,2,1,0,4,0),d.fromString=function(n){var e,r=new d,n=(n+=\"\").replace(/^\\s*[+\\-]?\\d+/,function(n){var n=+n,t=1970+(n-1970)%400;return r.year=n-t,t}).replace(/(?:Z|([+\\-]\\d{2}):?(\\d{2}))$/,function(n,t,r){return t<0&&(r*=-1),e=6e4*(60*+t+ +r),\"\"}).replace(/\\.\\d+$/,function(n){return r.nano=+(n+u).substr(1,9),\"\"}).split(/\\D+/);1<n.length?n[1]--:n[1]=0;if(r.time=e=Date.UTC.apply(Date,n)-(e||0),isNaN(e))throw new TypeError(\"Invalid Date\");return p(r)},d.fromTimeT=function(n){return y(n,0)},n.year=0,n.time=0,n.nano=0,n.addNano=function(n){return this.nano+=+n||0,this},n.getNano=function(){var n=p(this);return(n.time%1e3*h+ +n.nano+1e9)%1e9},n.getTimeT=function(){var n=p(this),t=Math.floor(n.time/1e3),n=n.year;n&&(t+=n*T*l/s);return t},n.getYear=function(){return this.toDate().getUTCFullYear()+this.year},n.toDate=function(){return M(p(this).time)},n.toJSON=function(){return this.toString().replace(/0{1,6}Z$/,\"Z\")},n.toString=function(n){var t=this,r=t.toDate(),u={H:function(){return C(r.getUTCHours())},L:function(){return D(r.getUTCMilliseconds(),3)},M:function(){return C(r.getUTCMinutes())},N:function(){return D(t.getNano(),9)},S:function(){return C(r.getUTCSeconds())},Y:function(){var n=t.getYear();return 999999<n?\"+\"+n:9999<n?\"+\"+D(n,6):0<=n?D(n,4):-999999<=n?\"-\"+D(-n,6):n},a:function(){return a[r.getUTCDay()]},b:function(){return i[r.getUTCMonth()]},d:function(){return C(r.getUTCDate())},e:function(){return function(n){return(9<n?\"\":\" \")+(0|n)}(r.getUTCDate())},m:function(){return C(r.getUTCMonth()+1)}};return function e(n){return n.replace(/%./g,function(n){var t=n[1],r=v[t],t=u[t];return r?e(r):t?t():n})}(n||o)},n.writeInt64BE=t(0,1,2,3,0,4),n.writeInt64LE=t(3,2,1,0,4,0),\"%Y-%m-%dT%H:%M:%S.%NZ\"),i=[\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"],a=[\"Sun\",\"Mon\",\"Tue\",\"Wed\",\"Thu\",\"Fri\",\"Sat\"],v={\"%\":\"%\",F:\"%Y-%m-%d\",n:\"\\n\",R:\"%H:%M\",T:\"%H:%M:%S\",t:\"\\t\",X:\"%T\",Z:\"GMT\",z:\"+0000\"};return d;function d(n,t,r){var e=this;if(!(e instanceof d))return new d(n,t,r);e.time=+n||0,e.nano=+t||0,e.year=+r||0,p(e)}function p(n){var t,r,e,u=n.year,o=n.time,i=n.nano,a=((i<0||h<=i)&&(i-=(r=Math.floor(i/h))*h,o+=r,r=1),u%s);return(o<-c||c<o||a)&&((t=m(o/f))&&(u+=t*s,o-=t*f),(e=M(o)).setUTCFullYear(a+e.getUTCFullYear()),e=(o=+e)+(t=m((u-=a)/s))*f,t&&-c<=e&&e<=c&&(u-=t*s,o=e),r=1),r&&(n.year=u,n.time=o,n.nano=i),n}function M(n){var t=new Date(0);return t.setTime(n),t}function y(n,t){n=+n||0;var r=m((t=(t|0)*g)/e)+m(n/e),t=t%e+n%e,n=m(t/e);return n&&(r+=n,t-=n*e),new d(1e3*t,0,r*s)}function t(e,u,o,i,a,f){return function(n,t){var r=p(this);n=n||new Array(8);w(n,t|=0);var e=Math.floor(r.time/1e3),r=r.year*(T*l/s),u=m(r/g)+m(e/g),r=r%g+e%g,e=Math.floor(r/g);e&&(u+=e,r-=e*g);return c(n,t+a,u),c(n,t+f,r),n};function c(n,t,r){n[t+e]=r>>24&255,n[t+u]=r>>16&255,n[t+o]=r>>8&255,n[t+i]=255&r}}function r(r,e,u,o,i,a){return function(n,t){w(n,t|=0);var r=f(n,t+i);return y(f(n,t+a),r)};function f(n,t){return 16777216*n[t+r]+(n[t+e]<<16|n[t+u]<<8|n[t+o])}}function w(n,t){n=n&&n.length;if(null==n)throw new TypeError(\"Invalid Buffer\");if(n<t+8)throw new RangeError(\"Out of range\")}function C(n){return(9<n?\"\":\"0\")+(0|n)}function D(n,t){return(u+(0|n)).substr(-t)}}();", "/**\n * @packageDocumentation\n *\n * [IPNS](https://docs.ipfs.tech/concepts/ipns/) operations using a Helia node\n *\n * @example Getting started\n *\n * With {@link IPNSRouting} routers:\n *\n * ```TypeScript\n * import { createHelia } from 'helia'\n * import { ipns } from '@helia/ipns'\n * import { unixfs } from '@helia/unixfs'\n *\n * const helia = await createHelia()\n * const name = ipns(helia)\n *\n * // store some data to publish\n * const fs = unixfs(helia)\n * const cid = await fs.addBytes(Uint8Array.from([0, 1, 2, 3, 4]))\n *\n * // publish the name\n * const { publicKey } = await name.publish('key-1', cid)\n *\n * // resolve the name\n * for await (const result of name.resolve(publicKey)) {\n * console.info(result.record.value) // /ipfs/QmFoo\n * }\n * ```\n *\n * @example Publishing a recursive record\n *\n * A recursive record is a one that points to another record rather than to a\n * value.\n *\n * ```TypeScript\n * import { createHelia } from 'helia'\n * import { ipns } from '@helia/ipns'\n * import { unixfs } from '@helia/unixfs'\n * import { generateKeyPair } from '@libp2p/crypto/keys'\n *\n * const helia = await createHelia()\n * const name = ipns(helia)\n *\n * // store some data to publish\n * const fs = unixfs(helia)\n * const cid = await fs.addBytes(Uint8Array.from([0, 1, 2, 3, 4]))\n *\n * // publish the name\n * const { publicKey } = await name.publish('key-1', cid)\n *\n * // publish the recursive name\n * const { publicKey: recursivePublicKey } = await name.publish('key-2', publicKey)\n *\n * // resolve the name recursively - it resolves until a CID is found\n * for await (const result of name.resolve(recursivePublicKey)) {\n * console.info(result.record.value) // /ipfs/QmFoo../foo.txt\n * }\n * ```\n *\n * @example Publishing a record with a path\n *\n * It is possible to publish CIDs with an associated path.\n *\n * ```TypeScript\n * import { createHelia } from 'helia'\n * import { ipns } from '@helia/ipns'\n * import { unixfs } from '@helia/unixfs'\n * import { generateKeyPair } from '@libp2p/crypto/keys'\n *\n * const helia = await createHelia()\n * const name = ipns(helia)\n *\n * // store some data to publish\n * const fs = unixfs(helia)\n * const fileCid = await fs.addBytes(Uint8Array.from([0, 1, 2, 3, 4]))\n *\n * // store the file in a directory\n * const dirCid = await fs.addDirectory()\n * const finalDirCid = await fs.cp(fileCid, dirCid, '/foo.txt')\n *\n * // publish the name\n * const { publicKey } = await name.publish('key-1', `/ipfs/${finalDirCid}/foo.txt`)\n *\n * // resolve the name\n * for await (const result of name.resolve(publicKey)) {\n * console.info(result.record.value) // /ipfs/QmFoo../foo.txt\n * }\n * ```\n *\n * @example Using custom PubSub router\n *\n * Additional IPNS routers can be configured - these enable alternative means to\n * publish and resolve IPNS names.\n *\n * One example is the PubSub router - this requires an instance of Helia with\n * libp2p PubSub configured.\n *\n * It works by subscribing to a pubsub topic for each IPNS name that we try to\n * resolve. Updated IPNS records are shared on these topics so an update must\n * occur before the name is resolvable.\n *\n * This router is only suitable for networks where IPNS updates are frequent\n * and multiple peers are listening on the topic(s), otherwise update messages\n * may fail to be published with \"Insufficient peers\" errors.\n *\n * ```TypeScript\n * import { createHelia, libp2pDefaults } from 'helia'\n * import { ipns } from '@helia/ipns'\n * import { pubsub } from '@helia/ipns/routing'\n * import { unixfs } from '@helia/unixfs'\n * import { floodsub } from '@libp2p/floodsub'\n * import { generateKeyPair } from '@libp2p/crypto/keys'\n * import type { PubSub } from '@helia/ipns/routing'\n * import type { Libp2p } from '@libp2p/interface'\n * import type { DefaultLibp2pServices } from 'helia'\n *\n * const libp2pOptions = libp2pDefaults()\n * libp2pOptions.services.pubsub = floodsub()\n *\n * const helia = await createHelia<Libp2p<DefaultLibp2pServices & { pubsub: PubSub }>>({\n * libp2p: libp2pOptions\n * })\n * const name = ipns(helia, {\n * routers: [\n * pubsub(helia)\n * ]\n * })\n *\n *\n * // store some data to publish\n * const fs = unixfs(helia)\n * const cid = await fs.addBytes(Uint8Array.from([0, 1, 2, 3, 4]))\n *\n * // publish the name\n * const { publicKey } = await name.publish('key-1', cid)\n *\n * // resolve the name\n * for await (const result of name.resolve(publicKey)) {\n * console.info(result.record.value)\n * }\n * ```\n */\n\nimport { CID } from 'multiformats/cid'\nimport { IPNSResolver as IPNSResolverClass } from './ipns/resolver.ts'\nimport { IPNS as IPNSClass } from './ipns.ts'\nimport { localStore } from './local-store.ts'\nimport { helia } from './routing/index.ts'\nimport { localStoreRouting } from './routing/local-store.ts'\nimport type { IPNSResolverComponents } from './ipns/resolver.ts'\nimport type { IPNSRecord } from './records.ts'\nimport type { IPNSRouting, IPNSRoutingProgressEvents } from './routing/index.ts'\nimport type { Routing, HeliaEvents, Keychain, PublicKey } from '@helia/interface'\nimport type { ComponentLogger, TypedEventEmitter } from '@libp2p/interface'\nimport type { AbortOptions } from 'abort-error'\nimport type { Datastore } from 'interface-datastore'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\nimport type { ProgressEvent, ProgressOptions } from 'progress-events'\n\nexport type PublishProgressEvents =\n ProgressEvent<'ipns:publish:start'> |\n ProgressEvent<'ipns:publish:success', IPNSRecord> |\n ProgressEvent<'ipns:publish:error', Error>\n\nexport type ResolveProgressEvents =\n ProgressEvent<'ipns:resolve:start', unknown> |\n ProgressEvent<'ipns:resolve:success', IPNSRecord> |\n ProgressEvent<'ipns:resolve:error', Error>\n\nexport type DatastoreProgressEvents =\n ProgressEvent<'ipns:routing:datastore:put'> |\n ProgressEvent<'ipns:routing:datastore:get'> |\n ProgressEvent<'ipns:routing:datastore:list'> |\n ProgressEvent<'ipns:routing:datastore:error', Error>\n\nexport interface PublishOptions extends AbortOptions, ProgressOptions<PublishProgressEvents | IPNSRoutingProgressEvents> {\n /**\n * Time duration of the signature validity in ms\n *\n * @default 172_800_000\n */\n lifetime?: number\n\n /**\n * Only publish to a local datastore\n *\n * @default false\n */\n offline?: boolean\n\n /**\n * By default a IPNS V1 and a V2 signature is added to every record. Pass\n * false here to only add a V2 signature.\n *\n * @default true\n */\n v1Compatible?: boolean\n\n /**\n * The TTL of the record in ms\n *\n * @default 300_000\n */\n ttl?: number\n}\n\nexport interface IPNSRecordMetadata {\n keyName: string\n lifetime: number\n}\n\nexport interface ResolveOptions extends AbortOptions, ProgressOptions<ResolveProgressEvents | IPNSRoutingProgressEvents> {\n /**\n * Do not query the network for the IPNS record\n *\n * @default false\n */\n offline?: boolean\n\n /**\n * Do not use cached IPNS Record entries\n *\n * @default false\n */\n nocache?: boolean\n}\n\nexport interface ResolveResult {\n /**\n * The resolved record\n */\n record: IPNSRecord\n}\n\nexport interface PublishResult {\n /**\n * The published record\n */\n record: IPNSRecord\n\n /**\n * The IPNS name that can be used to resolve this record\n */\n name: string\n\n /**\n * The public key that was used to sign and publish the record\n */\n publicKey: PublicKey\n}\n\nexport interface IPNSResolver {\n /**\n * Accepts a libp2p public key, a CID with the libp2p-key codec and either the\n * identity hash (for Ed25519 and secp256k1 public keys) or a SHA256 hash (for\n * RSA public keys), or the multihash of a libp2p-key encoded CID, or a\n * Ed25519, secp256k1 or RSA PeerId and recursively resolves the IPNS record\n * corresponding to that key until a value is found.\n */\n resolve(key: CID<unknown, 0x72> | MultihashDigest, options?: ResolveOptions): AsyncGenerator<ResolveResult>\n}\n\nexport interface IPNS {\n /**\n * Configured routing subsystems used to publish/resolve IPNS names\n */\n routers: IPNSRouting[]\n\n /**\n * Creates and publishes an IPNS record that will resolve the passed value\n * signed by a key stored in the libp2p keychain under the passed key name.\n *\n * If the key does not exist, a new Ed25519 key will be created. To use a\n * different key types, ensure the key is created and stored in the keychain\n * before invoking this method.\n *\n * It is possible to create a recursive IPNS record by passing:\n *\n * - A CID with the libp2p-key codec\n * - A Multihash\n * - A string IPNS key (e.g. `/ipns/Qmfoo`)\n *\n * @example\n *\n * ```TypeScript\n * import { createHelia } from 'helia'\n * import { ipns } from '@helia/ipns'\n *\n * const helia = await createHelia()\n * const name = ipns(helia)\n *\n * const result = await name.publish('my-key-name', cid, {\n * signal: AbortSignal.timeout(5_000)\n * })\n *\n * console.info(result) // { answer: ... }\n * ```\n */\n publish(keyName: string, value: CID | PublicKey | MultihashDigest | string, options?: PublishOptions): Promise<PublishResult>\n\n /**\n * Accepts a multihash of a public key, a libp2p-key CID containing the\n * multihash of a public key, or an IPNS name in it's string representation\n * and recursively resolves IPNS records until a non-recursive record is found\n * (e.g. the value can be parsed as a string that does not start with\n * `/ipns/`).\n */\n resolve(name: CID<unknown, 0x72> | PublicKey | MultihashDigest | string, options?: ResolveOptions): AsyncGenerator<ResolveResult>\n\n /**\n * Stop republishing of an IPNS record\n *\n * This will delete the last signed IPNS record from the datastore.\n *\n * Note that the record may still be resolved by other peers until it expires\n * or is otherwise no longer valid.\n */\n unpublish(keyName: string, options?: AbortOptions): Promise<void>\n}\n\nexport type { IPNSRouting } from './routing/index.ts'\nexport type { IPNSRecord } from './records.ts'\n\nexport interface IPNSComponents {\n datastore: Datastore\n routing: Routing\n logger: ComponentLogger\n keychain: Keychain\n events: TypedEventEmitter<HeliaEvents> // Helia event bus\n}\n\nexport interface IPNSOptions {\n /**\n * Different routing systems for IPNS publishing/resolving\n */\n routers?: IPNSRouting[]\n\n /**\n * How often to check if published records have expired and need republishing\n * in ms\n *\n * @default 3_600_000\n */\n republishInterval?: number\n\n /**\n * How many IPNS records to republish at once\n *\n * @default 5\n */\n republishConcurrency?: number\n}\n\nexport interface IPNSResolverOptions {\n /**\n * Different routing systems for IPNS publishing/resolving\n */\n routers?: IPNSRouting[]\n}\n\nexport function ipns (components: IPNSComponents, options: IPNSOptions = {}): IPNS {\n return new IPNSClass(components, options)\n}\n\nexport function ipnsResolver (components: IPNSResolverComponents, options: IPNSResolverOptions = {}): IPNSResolver {\n const store = localStore(components.datastore, components.logger.forComponent('helia:ipns:local-store'))\n const routers = [\n localStoreRouting(store),\n helia(components.routing),\n ...(options.routers ?? [])\n ]\n\n return new IPNSResolverClass(components, {\n routers,\n localStore: store\n })\n}\n\nexport type { IPNSRoutingProgressEvents }\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", "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 { 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", "/* 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 { 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", "const MINUTE = 60 * 1000\nconst HOUR = 60 * MINUTE\n\nexport const DEFAULT_LIFETIME_MS = 48 * HOUR\n\n/**\n * The default DHT record expiry\n */\nexport const DHT_EXPIRY_MS = 48 * HOUR\n\n/**\n * How often to run the republish loop\n */\nexport const DEFAULT_REPUBLISH_INTERVAL_MS = HOUR\n\n/**\n * Republish IPNS records when the expiry of our provider records is within this\n * threshold\n */\nexport const REPUBLISH_THRESHOLD = 24 * HOUR\n\nexport const DEFAULT_TTL_NS = BigInt(MINUTE) * 5_000_000n // 5 minutes\n\nexport const DEFAULT_REPUBLISH_CONCURRENCY = 5\n", "export class RecordsFailedValidationError extends Error {\n static name = 'RecordsFailedValidationError'\n name = 'RecordsFailedValidationError'\n}\n\nexport class UnsupportedMultibasePrefixError extends Error {\n static name = 'UnsupportedMultibasePrefixError'\n name = 'UnsupportedMultibasePrefixError'\n}\n\nexport class UnsupportedMultihashCodecError extends Error {\n static name = 'UnsupportedMultihashCodecError'\n name = 'UnsupportedMultihashCodecError'\n}\n\nexport class InvalidValueError extends Error {\n static name = 'InvalidValueError'\n name = 'InvalidValueError'\n}\n\nexport class InvalidTopicError extends Error {\n static name = 'InvalidTopicError'\n name = 'InvalidTopicError'\n}\n\nexport class RecordNotFoundError extends Error {\n static name = 'RecordNotFoundError'\n name = 'RecordNotFoundError'\n}\n\nexport class SignatureCreationError extends Error {\n static name = 'SignatureCreationError'\n name = 'SignatureCreationError'\n}\n\nexport class SignatureVerificationError extends Error {\n static name = 'SignatureVerificationError'\n name = 'SignatureVerificationError'\n}\n\nexport class RecordExpiredError extends Error {\n static name = 'RecordExpiredError'\n name = 'RecordExpiredError'\n}\n\nexport class UnsupportedValidityError extends Error {\n static name = 'UnsupportedValidityError'\n name = 'UnsupportedValidityError'\n}\n\nexport class RecordTooLargeError extends Error {\n static name = 'RecordTooLargeError'\n name = 'RecordTooLargeError'\n}\n\nexport class InvalidRecordDataError extends Error {\n static name = 'InvalidRecordDataError'\n name = 'InvalidRecordDataError'\n}\n\nexport class InvalidEmbeddedPublicKeyError extends Error {\n static name = 'InvalidEmbeddedPublicKeyError'\n name = 'InvalidEmbeddedPublicKeyError'\n}\n", "import NanoDate from 'timestamp-nano'\nimport { IpnsEntry } from './pb/ipns.ts'\nimport type { IPNSRecord } from './records.ts'\n\n/**\n * Selects the latest valid IPNS record from an array of marshalled IPNS records.\n *\n * Records are sorted by:\n * 1. Sequence number (higher takes precedence)\n * 2. Validity time for EOL records with same sequence number (longer lived record takes precedence)\n *\n * @param key - The routing key for the IPNS record\n * @param data - Array of marshalled IPNS records to select from\n * @returns The index of the most valid record from the input array\n */\nexport function ipnsSelector (key: Uint8Array, data: IPNSRecord[]): number {\n const entries = data.map((record, index) => ({\n record,\n index\n }))\n\n entries.sort((a, b) => {\n // Before we'd sort based on the signature version. Unmarshal now fails if\n // a record does not have SignatureV2, so that is no longer needed. V1-only\n // records haven't been issues in a long time.\n\n const aSeq = a.record.sequence\n const bSeq = b.record.sequence\n\n // choose later sequence number\n if (aSeq > bSeq) {\n return -1\n } else if (aSeq < bSeq) {\n return 1\n }\n\n if (a.record.validityType === IpnsEntry.ValidityType.EOL && b.record.validityType === IpnsEntry.ValidityType.EOL) {\n // choose longer lived record if sequence numbers the same\n const recordAValidityDate = NanoDate.fromString(a.record.validity).toDate()\n const recordBValidityDate = NanoDate.fromString(b.record.validity).toDate()\n\n if (recordAValidityDate.getTime() > recordBValidityDate.getTime()) {\n return -1\n }\n\n if (recordAValidityDate.getTime() < recordBValidityDate.getTime()) {\n return 1\n }\n }\n\n return 0\n })\n\n return entries[0].index\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", "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 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 * 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", "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 * 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 interface IpnsEntry {\n value?: Uint8Array\n signatureV1?: Uint8Array\n validityType?: IpnsEntry.ValidityType\n validity?: Uint8Array\n sequence?: bigint\n ttl?: bigint\n publicKey?: Uint8Array\n signatureV2?: Uint8Array\n data?: Uint8Array\n}\n\nexport namespace IpnsEntry {\n export enum ValidityType {\n EOL = 'EOL'\n }\n\n enum __ValidityTypeValues {\n EOL = 0\n }\n\n export namespace ValidityType {\n export const codec = (): Codec<ValidityType> => {\n return enumeration<ValidityType>(__ValidityTypeValues)\n }\n }\n\n let _codec: Codec<IpnsEntry>\n\n export const codec = (): Codec<IpnsEntry> => {\n if (_codec == null) {\n _codec = message<IpnsEntry>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.value != null) {\n w.uint32(10)\n w.bytes(obj.value)\n }\n\n if (obj.signatureV1 != null) {\n w.uint32(18)\n w.bytes(obj.signatureV1)\n }\n\n if (obj.validityType != null) {\n w.uint32(24)\n IpnsEntry.ValidityType.codec().encode(obj.validityType, w)\n }\n\n if (obj.validity != null) {\n w.uint32(34)\n w.bytes(obj.validity)\n }\n\n if (obj.sequence != null) {\n w.uint32(40)\n w.uint64(obj.sequence)\n }\n\n if (obj.ttl != null) {\n w.uint32(48)\n w.uint64(obj.ttl)\n }\n\n if (obj.publicKey != null) {\n w.uint32(58)\n w.bytes(obj.publicKey)\n }\n\n if (obj.signatureV2 != null) {\n w.uint32(66)\n w.bytes(obj.signatureV2)\n }\n\n if (obj.data != null) {\n w.uint32(74)\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.value = reader.bytes()\n break\n }\n case 2: {\n obj.signatureV1 = reader.bytes()\n break\n }\n case 3: {\n obj.validityType = IpnsEntry.ValidityType.codec().decode(reader)\n break\n }\n case 4: {\n obj.validity = reader.bytes()\n break\n }\n case 5: {\n obj.sequence = reader.uint64()\n break\n }\n case 6: {\n obj.ttl = reader.uint64()\n break\n }\n case 7: {\n obj.publicKey = reader.bytes()\n break\n }\n case 8: {\n obj.signatureV2 = reader.bytes()\n break\n }\n case 9: {\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}.value`,\n value: reader.bytes()\n }\n break\n }\n case 2: {\n yield {\n field: `${prefix}.signatureV1`,\n value: reader.bytes()\n }\n break\n }\n case 3: {\n yield {\n field: `${prefix}.validityType`,\n value: IpnsEntry.ValidityType.codec().decode(reader)\n }\n break\n }\n case 4: {\n yield {\n field: `${prefix}.validity`,\n value: reader.bytes()\n }\n break\n }\n case 5: {\n yield {\n field: `${prefix}.sequence`,\n value: reader.uint64()\n }\n break\n }\n case 6: {\n yield {\n field: `${prefix}.ttl`,\n value: reader.uint64()\n }\n break\n }\n case 7: {\n yield {\n field: `${prefix}.publicKey`,\n value: reader.bytes()\n }\n break\n }\n case 8: {\n yield {\n field: `${prefix}.signatureV2`,\n value: reader.bytes()\n }\n break\n }\n case 9: {\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 IpnsEntryValueFieldEvent {\n field: '$.value'\n value: Uint8Array\n }\n\n export interface IpnsEntrySignatureV1FieldEvent {\n field: '$.signatureV1'\n value: Uint8Array\n }\n\n export interface IpnsEntryValidityTypeFieldEvent {\n field: '$.validityType'\n value: IpnsEntry.ValidityType\n }\n\n export interface IpnsEntryValidityFieldEvent {\n field: '$.validity'\n value: Uint8Array\n }\n\n export interface IpnsEntrySequenceFieldEvent {\n field: '$.sequence'\n value: bigint\n }\n\n export interface IpnsEntryTtlFieldEvent {\n field: '$.ttl'\n value: bigint\n }\n\n export interface IpnsEntryPublicKeyFieldEvent {\n field: '$.publicKey'\n value: Uint8Array\n }\n\n export interface IpnsEntrySignatureV2FieldEvent {\n field: '$.signatureV2'\n value: Uint8Array\n }\n\n export interface IpnsEntryDataFieldEvent {\n field: '$.data'\n value: Uint8Array\n }\n\n export function encode (obj: Partial<IpnsEntry>): Uint8Array<ArrayBuffer> {\n return encodeMessage(obj, IpnsEntry.codec())\n }\n\n export function decode (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<IpnsEntry>): IpnsEntry {\n return decodeMessage(buf, IpnsEntry.codec(), opts)\n }\n\n export function stream (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<IpnsEntry>): Generator<IpnsEntryValueFieldEvent | IpnsEntrySignatureV1FieldEvent | IpnsEntryValidityTypeFieldEvent | IpnsEntryValidityFieldEvent | IpnsEntrySequenceFieldEvent | IpnsEntryTtlFieldEvent | IpnsEntryPublicKeyFieldEvent | IpnsEntrySignatureV2FieldEvent | IpnsEntryDataFieldEvent> {\n return streamMessage(buf, IpnsEntry.codec(), opts)\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", "/**\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 * WebCrypto-based implementations of ECDSA, Ed25519, and RSA cryptography.\n */\nimport type { AbortOptions } from 'abort-error'\nimport type { CID, MultihashDigest } from 'multiformats/cid'\n\nexport { ecdsaCrypto } from './ecdsa.ts'\nexport { ed25519Crypto } from './ed25519.ts'\nexport { rsaCrypto } from './rsa.ts'\n\nexport interface PublicKey {\n /**\n * The type of the crypto implementation, e.g. `Ed15519`\n */\n readonly type: string\n\n /**\n * The code that is used as the `Type` field in the protobuf representation of\n * the public/private keys\n */\n readonly code: number\n\n /**\n * Return a MultihashDigest that represents this key\n */\n toMultihash (): MultihashDigest\n\n /**\n * Return the libp2p-key CID that represents this key\n */\n toCID (): CID<unknown, 0x72, number, 1>\n\n /**\n * Return this key encoded as a protobuf PublicKey message\n */\n toProtobuf (): Uint8Array<ArrayBuffer>\n\n /**\n * Return this key as a RFC 7517 Json Web Key\n */\n toJWK (): JsonWebKey\n\n /**\n * Verify the passed message against it's signature\n */\n verify(message: Uint8Array, signature: Uint8Array, options?: AbortOptions): boolean | Promise<boolean>\n}\n\nexport function isPublicKey (obj?: any): obj is PublicKey {\n if (obj == null) {\n return false\n }\n\n return typeof obj.type === 'string' && typeof obj.code === 'number' && typeof obj.verify === 'function'\n}\n\nexport interface PrivateKey {\n /**\n * The type of the crypto implementation, e.g. `Ed15519`\n */\n readonly type: string\n\n /**\n * The code that is used as the `Type` field in the protobuf representation of\n * the public/private keys\n */\n readonly code: number\n\n /**\n * The public key that corresponds to this private key\n */\n readonly publicKey: PublicKey\n\n /**\n * Return this key encoded as a protobuf PrivateKey message\n */\n toProtobuf (): Uint8Array<ArrayBuffer>\n\n /**\n * Return this key as a RFC 7517 Json Web Key\n */\n toJWK (): JsonWebKey\n\n /**\n * Sign the passed message and return a signature\n */\n sign(message: Uint8Array, options?: AbortOptions): Uint8Array<ArrayBuffer> | Promise<Uint8Array<ArrayBuffer>>\n}\n\nexport function isPrivateKey (obj?: any): obj is PrivateKey {\n if (obj == null) {\n return false\n }\n\n return typeof obj.type === 'string' && typeof obj.code === 'number' && typeof obj.sign === 'function' && isPublicKey(obj.publicKey)\n}\n\nexport interface Crypto {\n /**\n * The type of the crypto implementation, e.g. `Ed15519`\n */\n type: string\n\n /**\n * The code that is used as the `Type` field in the protobuf representation of\n * the public/private keys\n */\n code: number\n\n /**\n * Create a new private key\n */\n generatePrivateKey(options?: AbortOptions & Record<string, any>): Promise<PrivateKey>\n\n /**\n * Convert the passed bytes into a public key. The bytes come from the `.Data`\n * field of a `PublicKey` protobuf message.\n */\n publicKeyFromProtobuf(buf: Uint8Array, options?: AbortOptions): PublicKey | Promise<PublicKey>\n\n /**\n * Convert the passed bytes into a public key. The bytes come from the `.Data`\n * field of a `PublicKey` protobuf message.\n */\n privateKeyFromProtobuf(buf: Uint8Array, options?: AbortOptions): PrivateKey | Promise<PrivateKey>\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 * @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", "// 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", "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 { isPublicKey } from '@helia/interface'\nimport { InvalidParametersError } from '@libp2p/interface'\nimport * as cborg from 'cborg'\nimport { Key } from 'interface-datastore'\nimport { base36 } from 'multiformats/bases/base36'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { DHT_EXPIRY_MS, REPUBLISH_THRESHOLD } from './constants.ts'\nimport { InvalidEmbeddedPublicKeyError, InvalidRecordDataError, InvalidValueError, RecordTooLargeError, SignatureVerificationError, UnsupportedValidityError } from './errors.ts'\nimport { IpnsEntry } from './pb/ipns.ts'\nimport type { IPNSRecord, IPNSRecordV2, IPNSRecordData } from './records.ts'\nimport type { PublicKey, Keychain } from '@helia/interface'\nimport type { AbortOptions } from '@libp2p/interface'\nimport type { MultibaseDecoder } from 'multiformats/cid'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nexport const LIBP2P_KEY_CODEC = 0x72\nexport const IDENTITY_CODEC = 0x0\nexport const SHA2_256_CODEC = 0x12\n\n/**\n * Limit valid IPNS record sizes to 10kb\n */\nconst MAX_RECORD_SIZE = 1024 * 10\n\nconst IPNS_PREFIX = uint8ArrayFromString('/ipns/')\nexport const IPNS_STRING_PREFIX = '/ipns/'\n\nexport function isCodec <T extends number> (digest: MultihashDigest, codec: T): digest is MultihashDigest<T> {\n return digest.code === codec\n}\n\nexport const DHT_RECORD_PREFIX = '/dht/record/'\nexport const IPNS_METADATA_PREFIX = '/ipns/metadata/'\n\nexport function dhtRoutingKey (key: Uint8Array): Key {\n return new Key(DHT_RECORD_PREFIX + uint8ArrayToString(key, 'base32'), false)\n}\n\n/**\n * Calculate the datastore key for IPNS record metadata\n *\n * @param key - The DHT routing key for the IPNS record as defined in\n * https://specs.ipfs.tech/ipns/ipns-record/#routing-record\n *\n * @example\n *\n * ```ts\n * const key = multihashToIPNSRoutingKey(privKey.publicKey.toMultihash())\n * const metadataKey = ipnsMetadataKey(key)\n * ```\n * @returns The local storage key for IPNS record metadata\n */\nexport function ipnsMetadataKey (key: Uint8Array): Key {\n return new Key(IPNS_METADATA_PREFIX + uint8ArrayToString(key, 'base32'), false)\n}\n\nexport function shouldRepublish (ipnsRecord: IPNSRecord, created: Date): boolean {\n const now = Date.now()\n const dhtExpiry = created.getTime() + DHT_EXPIRY_MS\n const recordExpiry = new Date(ipnsRecord.validity).getTime()\n\n // If the DHT expiry is within the threshold, republish it\n if (dhtExpiry - now < REPUBLISH_THRESHOLD) {\n return true\n }\n\n // If the record expiry (based on validity/lifetime) is within the threshold, republish it\n if (recordExpiry - now < REPUBLISH_THRESHOLD) {\n return true\n }\n\n return false\n}\n\nfunction isCID (obj?: any): obj is CID {\n return obj?.asCID === obj\n}\n\nexport function isLibp2pCID (obj?: any): obj is CID<unknown, 0x72, 0x00 | 0x12, 1> {\n if (!isCID(obj)) {\n return false\n }\n\n if (obj.code !== LIBP2P_KEY_CODEC) {\n throw new InvalidParametersError(`CID codec ${obj.code} was not libp2p-key`)\n }\n\n if (obj.multihash.code !== IDENTITY_CODEC && obj.multihash.code !== SHA2_256_CODEC) {\n throw new InvalidParametersError(`Multihash algorithm codec ${obj.multihash.code} was not Identity or SHA256 hash`)\n }\n\n return true\n}\n\n/**\n * Utility for creating the record data for being signed\n */\nexport function ipnsRecordDataForV1Sig (value: string, validityType: IpnsEntry.ValidityType, validity: Uint8Array): Uint8Array {\n const validityTypeBuffer = uint8ArrayFromString(validityType)\n const valueBytes = uint8ArrayFromString(value)\n\n return uint8ArrayConcat([\n valueBytes,\n validity,\n validityTypeBuffer\n ], valueBytes.byteLength + validity.byteLength + validityTypeBuffer.byteLength)\n}\n\n/**\n * Utility for creating the record data for being signed\n */\nexport function ipnsRecordDataForV2Sig (data: Uint8Array): Uint8Array {\n const entryData = uint8ArrayFromString('ipns-signature:')\n\n return uint8ArrayConcat([entryData, data])\n}\n\nexport function marshalIPNSRecord (obj: IPNSRecord | IPNSRecordV2): Uint8Array {\n let publicKey: Uint8Array | undefined = obj.publicKey?.toProtobuf()\n\n // do not embed public keys whose multihash is an identity hash as these can\n // be derived from the routing key\n if (obj.publicKey?.toMultihash().code === 0x00) {\n publicKey = undefined\n }\n\n if ('signatureV1' in obj) {\n return IpnsEntry.encode({\n value: uint8ArrayFromString(obj.value),\n signatureV1: obj.signatureV1,\n validityType: obj.validityType,\n validity: uint8ArrayFromString(obj.validity),\n sequence: obj.sequence,\n ttl: obj.ttl,\n publicKey,\n signatureV2: obj.signatureV2,\n data: obj.data\n })\n } else {\n return IpnsEntry.encode({\n publicKey,\n signatureV2: obj.signatureV2,\n data: obj.data\n })\n }\n}\n\nfunction valueToString (value: Uint8Array): string {\n // handle legacy case where record value is raw CID bytes\n try {\n const cid = CID.decode(value)\n return `/ipfs/${cid}`\n } catch {\n // ignore error\n }\n\n return uint8ArrayToString(value)\n}\n\nexport async function unmarshalIPNSRecord (routingKey: Uint8Array, marshalledRecord: Uint8Array, keychain: Keychain, options?: AbortOptions): Promise<IPNSRecord> {\n if (marshalledRecord.byteLength > MAX_RECORD_SIZE) {\n throw new RecordTooLargeError('The record is too large')\n }\n\n const message = IpnsEntry.decode(marshalledRecord)\n\n // Check if we have the data field. If we don't, we fail. We've been producing\n // V1+V2 records for quite a while and we don't support V1-only records during\n // validation any more\n if (message.signatureV2 == null || message.data == null) {\n throw new SignatureVerificationError('Missing data or signatureV2')\n }\n\n const data = parseCborData(message.data)\n const validity = uint8ArrayToString(data.Validity)\n\n let publicKey: PublicKey | undefined\n\n // try to extract public key from routing key\n const routingMultihash = multihashFromIPNSRoutingKey(routingKey)\n\n // identity hash\n if (isCodec(routingMultihash, 0x0)) {\n publicKey = await keychain.loadPublicKeyFromProtobuf(routingMultihash.digest, options)\n }\n\n // otherwise try to load key from message\n if (publicKey == null && message.publicKey != null) {\n publicKey = await keychain.loadPublicKeyFromProtobuf(message.publicKey, options)\n }\n\n if (publicKey == null) {\n throw new InvalidEmbeddedPublicKeyError('Could not extract public key from IPNS record or routing key')\n }\n\n if (message.value != null && message.signatureV1 != null) {\n // V1+V2\n validateCborDataMatchesPbData(message)\n\n return {\n value: valueToString(data.Value),\n validityType: IpnsEntry.ValidityType.EOL,\n validity,\n sequence: data.Sequence,\n ttl: data.TTL,\n publicKey,\n signatureV1: message.signatureV1,\n signatureV2: message.signatureV2,\n data: message.data,\n bytes: marshalledRecord\n }\n } else if (message.signatureV2 != null) {\n // V2-only\n return {\n value: valueToString(data.Value),\n validityType: IpnsEntry.ValidityType.EOL,\n validity,\n sequence: data.Sequence,\n ttl: data.TTL,\n publicKey,\n signatureV2: message.signatureV2,\n data: message.data,\n bytes: marshalledRecord\n }\n } else {\n throw new Error('invalid record: does not include signatureV1 or signatureV2')\n }\n}\n\nexport function multihashToIPNSRoutingKey (digest: MultihashDigest): Uint8Array {\n return uint8ArrayConcat([\n IPNS_PREFIX,\n digest.bytes\n ])\n}\n\nexport function multihashFromIPNSRoutingKey (key: Uint8Array): MultihashDigest {\n return Digest.decode(key.slice(IPNS_PREFIX.length))\n}\n\nexport function createCborData (value: string, validityType: IpnsEntry.ValidityType, validity: Uint8Array, sequence: bigint, ttl: bigint): Uint8Array {\n let ValidityType\n\n if (validityType === IpnsEntry.ValidityType.EOL) {\n ValidityType = 0\n } else {\n throw new UnsupportedValidityError('The validity type is unsupported')\n }\n\n const data = {\n Value: uint8ArrayFromString(value),\n Validity: validity,\n ValidityType,\n Sequence: sequence,\n TTL: ttl\n }\n\n return cborg.encode(data)\n}\n\nexport function parseCborData (buf: Uint8Array): IPNSRecordData {\n const data = cborg.decode(buf)\n\n if (data.ValidityType === 0) {\n data.ValidityType = IpnsEntry.ValidityType.EOL\n } else {\n throw new UnsupportedValidityError('The validity type is unsupported')\n }\n\n if (Number.isInteger(data.Sequence)) {\n // sequence must be a BigInt, but DAG-CBOR doesn't preserve this for Numbers within the safe-integer range\n data.Sequence = BigInt(data.Sequence)\n }\n\n if (Number.isInteger(data.TTL)) {\n // ttl must be a BigInt, but DAG-CBOR doesn't preserve this for Numbers within the safe-integer range\n data.TTL = BigInt(data.TTL)\n }\n\n return data\n}\n\n/**\n * Normalizes the given record value. It ensures it is a PeerID, a CID or a\n * string starting with '/'. PeerIDs become `/ipns/${cidV1Libp2pKey}`,\n * CIDs become `/ipfs/${cidAsV1}`.\n */\nexport function normalizeValue (value?: PublicKey | CID | MultihashDigest | string): string {\n if (value != null) {\n if (isPublicKey(value)) {\n return `/ipns/${value.toCID().toV1().toString(base36)}`\n }\n\n const cid = asCID(value)\n\n // if we have a CID, turn it into an ipfs path\n if (cid != null) {\n // PeerID encoded as a CID\n if (cid.code === LIBP2P_KEY_CODEC) {\n return `/ipns/${cid.toV1().toString(base36)}`\n }\n\n return `/ipfs/${cid.toV1()}`\n }\n\n if (hasBytes(value)) {\n return `/ipns/${base36.encode(value.bytes)}`\n }\n\n // if we have a path, check it is a valid path\n const string = value.toString().trim()\n\n if (string.startsWith('/ipfs/')) {\n const [, name, ...rest] = string.split('/')\n .filter(component => component.trim() !== '')\n\n return `/ipfs/${CID.parse(name).toV1()}${rest.length > 0 ? `/${rest.join('/')}` : ''}`\n }\n\n if (string.startsWith('/') && string.length > 1) {\n return string\n }\n }\n\n throw new InvalidValueError('Value must be a valid content path starting with /')\n}\n\nfunction isMultihashDigest (obj: any): obj is MultihashDigest {\n return typeof obj.code === 'number' && obj.digest instanceof Uint8Array && typeof obj.size === 'number' && obj.bytes instanceof Uint8Array\n}\n\nexport function normalizeKey (key?: PublicKey | CID<unknown, 0x72> | MultihashDigest | string): { digest: MultihashDigest, path: string } {\n if (key != null) {\n if (isPublicKey(key)) {\n return {\n digest: key.toMultihash(),\n path: '/'\n }\n }\n\n const cid = asCID(key)\n\n // if we have a CID, turn it into an ipfs path\n if (cid != null) {\n // PeerID encoded as a CID\n if (cid.code !== LIBP2P_KEY_CODEC) {\n throw new InvalidValueError('CIDs must have the `libp2p-key` codec')\n }\n\n return {\n digest: cid.multihash,\n path: '/'\n }\n }\n\n if (isMultihashDigest(key)) {\n return {\n digest: key,\n path: '/'\n }\n }\n\n key = key.toString()\n\n if (key.startsWith('/ipns/')) {\n let [,, name, ...rest] = key.split('/')\n let codec: MultibaseDecoder<any> = base36\n\n // base58btc encoded public key hash or protobuf in identity hash\n if (name.startsWith('1') || name.startsWith('Q')) {\n name = `z${name}`\n codec = base58btc\n }\n\n const buf = codec.decode(name)\n let digest: MultihashDigest\n\n try {\n digest = CID.decode(buf).multihash\n } catch {\n digest = Digest.decode(buf)\n }\n\n return {\n digest,\n path: `/${rest.join('/')}`\n }\n }\n }\n\n throw new InvalidValueError('Value must be a valid IPNS path starting with /')\n}\n\nfunction validateCborDataMatchesPbData (entry: IpnsEntry): void {\n if (entry.data == null) {\n throw new InvalidRecordDataError('Record data is missing')\n }\n\n const data = parseCborData(entry.data)\n\n if (!uint8ArrayEquals(data.Value, entry.value ?? new Uint8Array(0))) {\n throw new SignatureVerificationError('Field \"value\" did not match between protobuf and CBOR')\n }\n\n if (!uint8ArrayEquals(data.Validity, entry.validity ?? new Uint8Array(0))) {\n throw new SignatureVerificationError('Field \"validity\" did not match between protobuf and CBOR')\n }\n\n if (data.ValidityType !== entry.validityType) {\n throw new SignatureVerificationError('Field \"validityType\" did not match between protobuf and CBOR')\n }\n\n if (data.Sequence !== entry.sequence) {\n throw new SignatureVerificationError('Field \"sequence\" did not match between protobuf and CBOR')\n }\n\n if (data.TTL !== entry.ttl) {\n throw new SignatureVerificationError('Field \"ttl\" did not match between protobuf and CBOR')\n }\n}\n\nfunction hasBytes (obj?: any): obj is { bytes: Uint8Array } {\n return obj.bytes instanceof Uint8Array\n}\n\nfunction hasToCID (obj?: any): obj is { toCID(): CID } {\n return typeof obj?.toCID === 'function'\n}\n\nfunction asCID (obj?: any): CID | null {\n if (hasToCID(obj)) {\n return obj.toCID()\n }\n\n // try parsing as a CID string\n try {\n return CID.parse(obj)\n } catch {\n // fall through\n }\n\n return CID.asCID(obj)\n}\n", "import NanoDate from 'timestamp-nano'\nimport { InvalidEmbeddedPublicKeyError, RecordExpiredError, SignatureVerificationError, UnsupportedValidityError } from './errors.ts'\nimport { IpnsEntry } from './pb/ipns.ts'\nimport { ipnsRecordDataForV2Sig } from './utils.ts'\nimport type { IPNSRecord } from './index.ts'\nimport type { AbortOptions } from '@libp2p/interface'\n\n/**\n * Validate the given IPNS record against the given routing key.\n *\n * @see https://specs.ipfs.tech/ipns/ipns-record/#routing-record for the binary\n * format of the routing key\n */\nexport async function ipnsValidator (record: IPNSRecord, options?: AbortOptions): Promise<void> {\n if (record.publicKey == null) {\n throw new InvalidEmbeddedPublicKeyError('The record had no public key associated with it')\n }\n\n // Validate Signature V2\n let isValid\n\n try {\n const dataForSignature = ipnsRecordDataForV2Sig(record.data)\n isValid = await record.publicKey.verify(dataForSignature, record.signatureV2, options)\n } catch {\n isValid = false\n }\n\n if (!isValid) {\n throw new SignatureVerificationError('Record signature verification failed')\n }\n\n // Validate according to the validity type\n if (record.validityType === IpnsEntry.ValidityType.EOL) {\n if (NanoDate.fromString(record.validity).toDate().getTime() < Date.now()) {\n throw new RecordExpiredError('record has expired')\n }\n } else if (record.validityType != null) {\n throw new UnsupportedValidityError('The validity type is unsupported')\n }\n}\n\n/**\n * Returns the number of milliseconds until the record expires.\n * If the record is already expired, returns 0.\n *\n * @param record - The IPNS record to validate.\n * @returns The number of milliseconds until the record expires, or 0 if the record is already expired.\n */\nexport function validFor (record: IPNSRecord): number {\n if (record.validityType !== IpnsEntry.ValidityType.EOL) {\n throw new UnsupportedValidityError()\n }\n\n if (record.validity == null) {\n throw new UnsupportedValidityError()\n }\n\n const validUntil = NanoDate.fromString(record.validity).toDate().getTime()\n const now = Date.now()\n\n if (validUntil < now) {\n return 0\n }\n\n return validUntil - now\n}\n", "import { DEFAULT_TTL_NS } from '../constants.ts'\nimport { RecordNotFoundError, RecordsFailedValidationError } from '../errors.ts'\nimport { ipnsSelector } from '../selector.ts'\nimport { multihashToIPNSRoutingKey, unmarshalIPNSRecord, normalizeKey, IPNS_STRING_PREFIX } from '../utils.ts'\nimport { ipnsValidator } from '../validator.ts'\nimport type { IPNSRecord, ResolveOptions, ResolveResult } from '../index.ts'\nimport type { LocalStore } from '../local-store.ts'\nimport type { IPNSRouting } from '../routing/index.ts'\nimport type { Routing, Keychain } from '@helia/interface'\nimport type { ComponentLogger, Logger } from '@libp2p/interface'\nimport type { Datastore } from 'interface-datastore'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nexport interface IPNSResolverComponents {\n datastore: Datastore\n routing: Routing\n logger: ComponentLogger\n keychain: Keychain\n}\n\nexport interface IPNResolverInit {\n localStore: LocalStore\n routers: IPNSRouting[]\n}\n\nexport class IPNSResolver {\n public readonly routers: IPNSRouting[]\n private readonly localStore: LocalStore\n private readonly log: Logger\n private keychain: Keychain\n\n constructor (components: IPNSResolverComponents, init: IPNResolverInit) {\n this.log = components.logger.forComponent('helia:ipns')\n this.localStore = init.localStore\n this.routers = init.routers\n this.keychain = components.keychain\n }\n\n async * resolve (key: MultihashDigest, options: ResolveOptions = {}): AsyncGenerator<ResolveResult> {\n let { digest } = normalizeKey(key)\n\n while (true) {\n const routingKey = multihashToIPNSRoutingKey(digest)\n const record = await this.#findIpnsRecord(routingKey, options)\n\n yield {\n record\n }\n\n if (!record.value.startsWith(IPNS_STRING_PREFIX)) {\n // not a recursive record\n break\n }\n\n ({ digest } = normalizeKey(record.value))\n }\n }\n\n async #findIpnsRecord (routingKey: Uint8Array, options: ResolveOptions = {}): Promise<IPNSRecord> {\n const records: IPNSRecord[] = []\n const cached = await this.localStore.has(routingKey, options)\n\n if (cached) {\n this.log('record is present in the cache')\n\n if (options.nocache !== true) {\n try {\n // check the local cache first\n const { record: marshaledIPNSRecord, created } = await this.localStore.get(routingKey, options)\n\n this.log('record retrieved from cache')\n\n // unmarshal the record\n const ipnsRecord = await unmarshalIPNSRecord(routingKey, marshaledIPNSRecord, this.keychain, options)\n\n // validate the record\n await ipnsValidator(ipnsRecord, options)\n\n this.log('record was valid')\n\n // check the TTL\n\n // IPNS TTL is in nanoseconds, convert to milliseconds, default to one\n // hour\n const ttlMs = Number((ipnsRecord.ttl ?? DEFAULT_TTL_NS) / 1_000_000n)\n const ttlExpires = created.getTime() + ttlMs\n\n if (ttlExpires > Date.now()) {\n // the TTL has not yet expired, return the cached record\n this.log('record TTL was valid')\n return ipnsRecord\n }\n\n if (options.offline === true) {\n // the TTL has expired but we are skipping the routing search\n this.log('record TTL has been reached but we are resolving offline-only, returning record')\n return ipnsRecord\n }\n\n this.log('record TTL has been reached, searching routing for updates')\n\n // add the local record to our list of resolved record, and also\n // search the routing for updates - the most up to date record will be\n // returned\n records.push(ipnsRecord)\n } catch (err) {\n this.log('cached record was invalid - %e', err)\n await this.localStore.delete(routingKey, options)\n }\n } else {\n this.log('ignoring local cache due to nocache=true option')\n }\n }\n\n if (options.offline === true) {\n throw new RecordNotFoundError('Record was not present in the cache or has expired')\n }\n\n this.log('did not have record locally')\n\n let foundInvalid = 0\n const errors: Error[] = []\n\n await Promise.all(\n this.routers.map(async (router) => {\n let marshaledIPNSRecord: Uint8Array\n\n try {\n marshaledIPNSRecord = await router.get(routingKey, {\n ...options,\n validate: false\n })\n } catch (err: any) {\n this.log.error('error finding IPNS record using router %s - %e', router.toString(), err)\n errors.push(err)\n\n return\n }\n\n try {\n // unmarshal ensures that (1) SignatureV2 and Data are present, (2) that ValidityType\n // and Validity are of valid types and have a value, (3) that CBOR data matches protobuf\n // if it's a V1+V2 record\n const record = await unmarshalIPNSRecord(routingKey, marshaledIPNSRecord, this.keychain, options)\n\n await ipnsValidator(record, options)\n\n records.push(record)\n } catch (err) {\n // we found a record, but the validator rejected it\n foundInvalid++\n this.log.error('error validating IPNS record from router %s - %e', router.toString(), err)\n }\n })\n )\n\n if (records.length === 0) {\n if (foundInvalid > 0) {\n throw new RecordsFailedValidationError(`${foundInvalid > 1 ? `${foundInvalid} records` : 'Record'} found for routing key ${foundInvalid > 1 ? 'were' : 'was'} invalid`)\n }\n\n throw new RecordNotFoundError('Could not find record for routing key')\n }\n\n const record = records[ipnsSelector(routingKey, records)]\n\n await this.localStore.put(routingKey, record.bytes, options)\n\n return record\n }\n}\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", "//#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 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 { 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): debug.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\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: debug.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", "import { logger } from '@libp2p/logger'\nimport NanoDate from 'timestamp-nano'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { SignatureCreationError } from './errors.ts'\nimport { IpnsEntry } from './pb/ipns.ts'\nimport { createCborData, ipnsRecordDataForV1Sig, ipnsRecordDataForV2Sig, marshalIPNSRecord } from './utils.ts'\nimport type { PrivateKey, PublicKey } from '@helia/interface'\nimport type { AbortOptions } from 'abort-error'\nimport type { Key } from 'interface-datastore/key'\n\nconst log = logger('ipns')\nconst DEFAULT_TTL_NS = 5 * 60 * 1e+9 // 5 Minutes or 300 Seconds, as suggested by https://specs.ipfs.tech/ipns/ipns-record/#ttl-uint64\n\nexport const namespace = '/ipns/'\nexport const namespaceLength = namespace.length\n\nexport interface IPNSRecordV1V2 {\n /**\n * value of the record\n */\n value: string\n\n /**\n * signature of the record\n */\n signatureV1: Uint8Array\n\n /**\n * Type of validation being used\n */\n validityType: IpnsEntry.ValidityType\n\n /**\n * expiration datetime for the record in RFC3339 format\n */\n validity: string\n\n /**\n * number representing the version of the record\n */\n sequence: bigint\n\n /**\n * ttl in nanoseconds\n */\n ttl?: bigint\n\n /**\n * the public portion of the key that signed this record\n */\n publicKey: PublicKey\n\n /**\n * the v2 signature of the record\n */\n signatureV2: Uint8Array\n\n /**\n * extensible data\n */\n data: Uint8Array\n\n /**\n * The marshalled record\n */\n bytes: Uint8Array\n}\n\nexport interface IPNSRecordV2 {\n /**\n * value of the record\n */\n value: string\n\n /**\n * the v2 signature of the record\n */\n signatureV2: Uint8Array\n\n /**\n * Type of validation being used\n */\n validityType: IpnsEntry.ValidityType\n\n /**\n * If the validity type is EOL, this is the expiration datetime for the record\n * in RFC3339 format\n */\n validity: string\n\n /**\n * number representing the version of the record\n */\n sequence: bigint\n\n /**\n * ttl in nanoseconds\n */\n ttl?: bigint\n\n /**\n * the public portion of the key that signed this record\n */\n publicKey: PublicKey\n\n /**\n * extensible data\n */\n data: Uint8Array\n\n /**\n * The marshalled record\n */\n bytes: Uint8Array\n}\n\nexport type IPNSRecord = IPNSRecordV1V2 | IPNSRecordV2\n\nexport interface IPNSRecordData {\n Value: Uint8Array\n Validity: Uint8Array\n ValidityType: IpnsEntry.ValidityType\n Sequence: bigint\n TTL: bigint\n}\n\nexport interface IDKeys {\n routingPubKey: Key\n pkKey: Key\n routingKey: Key\n ipnsKey: Key\n}\n\nexport interface CreateOptions extends AbortOptions {\n ttlNs?: number | bigint\n v1Compatible?: boolean\n}\n\nexport interface CreateV2OrV1Options extends AbortOptions {\n v1Compatible: true\n}\n\nexport interface CreateV2Options extends AbortOptions {\n v1Compatible: false\n}\n\nconst defaultCreateOptions: CreateOptions = {\n v1Compatible: true,\n ttlNs: DEFAULT_TTL_NS\n}\n\n/**\n * Creates a new IPNS record and signs it with the given private key.\n * The IPNS Record validity should follow the [RFC3339]{@link https://www.ietf.org/rfc/rfc3339.txt} with nanoseconds precision.\n * Note: This function does not embed the public key. If you want to do that, use `EmbedPublicKey`.\n *\n * The passed value can be a CID, a PublicKey or an arbitrary string path e.g. `/ipfs/...` or `/ipns/...`.\n *\n * CIDs will be converted to v1 and stored in the record as a string similar to: `/ipfs/${cid}`\n * PublicKeys will create recursive records, eg. the record value will be `/ipns/${cidV1Libp2pKey}`\n * String paths will be stored in the record as-is, but they must start with `\"/\"`\n *\n * @param {PrivateKey} privateKey - the private key for signing the record.\n * @param {CID | PublicKey | string} value - content to be stored in the record.\n * @param {number | bigint} seq - number representing the current version of the record.\n * @param {number} lifetime - lifetime of the record (in milliseconds).\n * @param {CreateOptions} options - additional create options.\n */\nexport async function createIPNSRecord (privateKey: PrivateKey, value: string, seq: number | bigint, lifetime: number, options?: CreateV2OrV1Options): Promise<IPNSRecordV1V2>\nexport async function createIPNSRecord (privateKey: PrivateKey, value: string, seq: number | bigint, lifetime: number, options: CreateV2Options): Promise<IPNSRecordV2>\nexport async function createIPNSRecord (privateKey: PrivateKey, value: string, seq: number | bigint, lifetime: number, options: CreateOptions): Promise<IPNSRecordV1V2>\nexport async function createIPNSRecord (privateKey: PrivateKey, value: string, seq: number | bigint, lifetime: number, options: CreateOptions = defaultCreateOptions): Promise<IPNSRecord> {\n // Validity in ISOString with nanoseconds precision and validity type EOL\n const expirationDate = new NanoDate(Date.now() + Number(lifetime))\n const validityType = IpnsEntry.ValidityType.EOL\n const ttlNs = BigInt(options.ttlNs ?? DEFAULT_TTL_NS)\n\n return _create(privateKey, value, seq, validityType, expirationDate.toString(), ttlNs, options)\n}\n\n/**\n * Same as create(), but instead of generating a new Date, it receives the intended expiration time\n * WARNING: nano precision is not standard, make sure the value in seconds is 9 orders of magnitude lesser than the one provided.\n *\n * The passed value can be a CID, a PublicKey or an arbitrary string path e.g. `/ipfs/...` or `/ipns/...`.\n *\n * CIDs will be converted to v1 and stored in the record as a string similar to: `/ipfs/${cid}`\n * PublicKeys will create recursive records, eg. the record value will be `/ipns/${cidV1Libp2pKey}`\n * String paths will be stored in the record as-is, but they must start with `\"/\"`\n *\n * @param {PrivateKey} privateKey - the private key for signing the record.\n * @param {CID | PublicKey | string} value - content to be stored in the record.\n * @param {number | bigint} seq - number representing the current version of the record.\n * @param {string} expiration - expiration datetime for record in the [RFC3339]{@link https://www.ietf.org/rfc/rfc3339.txt} with nanoseconds precision.\n * @param {CreateOptions} options - additional creation options.\n */\nexport async function createIPNSRecordWithExpiration (privateKey: PrivateKey, value: string, seq: number | bigint, expiration: string, options?: CreateV2OrV1Options): Promise<IPNSRecordV1V2>\nexport async function createIPNSRecordWithExpiration (privateKey: PrivateKey, value: string, seq: number | bigint, expiration: string, options: CreateV2Options): Promise<IPNSRecordV2>\nexport async function createIPNSRecordWithExpiration (privateKey: PrivateKey, value: string, seq: number | bigint, expiration: string, options: CreateOptions): Promise<IPNSRecordV1V2>\nexport async function createIPNSRecordWithExpiration (privateKey: PrivateKey, value: string, seq: number | bigint, expiration: string, options: CreateOptions = defaultCreateOptions): Promise<IPNSRecord> {\n const expirationDate = NanoDate.fromString(expiration)\n const validityType = IpnsEntry.ValidityType.EOL\n const ttlNs = BigInt(options.ttlNs ?? DEFAULT_TTL_NS)\n\n return _create(privateKey, value, seq, validityType, expirationDate.toString(), ttlNs, options)\n}\n\nconst _create = async (privateKey: PrivateKey, value: string, seq: number | bigint, validityType: IpnsEntry.ValidityType, validity: string, ttl: bigint, options: CreateOptions = defaultCreateOptions): Promise<IPNSRecord> => {\n seq = BigInt(seq)\n const isoValidity = uint8ArrayFromString(validity)\n const data = createCborData(value, validityType, isoValidity, seq, ttl)\n const sigData = ipnsRecordDataForV2Sig(data)\n const signatureV2 = await privateKey.sign(sigData, options)\n const publicKey = shouldEmbedPublicKey(privateKey.publicKey) ? privateKey.publicKey : undefined\n let record: any\n\n if (options.v1Compatible === true) {\n const signatureV1 = await signLegacyV1(privateKey, value, validityType, isoValidity)\n\n record = {\n value,\n signatureV1,\n validity,\n validityType,\n sequence: seq,\n ttl,\n signatureV2,\n data,\n publicKey\n }\n } else {\n record = {\n value,\n validity,\n validityType,\n sequence: seq,\n ttl,\n signatureV2,\n data,\n publicKey\n }\n }\n\n record.bytes = marshalIPNSRecord(record)\n\n return record\n}\n\nexport { unmarshalIPNSRecord } from './utils.ts'\nexport { marshalIPNSRecord } from './utils.ts'\nexport { multihashToIPNSRoutingKey } from './utils.ts'\nexport { multihashFromIPNSRoutingKey } from './utils.ts'\n\n/**\n * Sign ipns record data using the legacy V1 signature scheme\n */\nconst signLegacyV1 = async (privateKey: PrivateKey, value: string, validityType: IpnsEntry.ValidityType, validity: Uint8Array, options?: AbortOptions): Promise<Uint8Array> => {\n try {\n const dataForSignature = ipnsRecordDataForV1Sig(value, validityType, validity)\n\n return await privateKey.sign(dataForSignature, options)\n } catch (error: any) {\n log.error('record signature creation failed', error)\n throw new SignatureCreationError('Record signature creation failed')\n }\n}\n\n/**\n * Returns true if the public key multihash is not an identity hash\n */\nfunction shouldEmbedPublicKey (key: PublicKey): boolean {\n return key.toMultihash().code !== 0\n}\n", "import { base36 } from 'multiformats/bases/base36'\nimport { CustomProgressEvent } from 'progress-events'\nimport { DEFAULT_LIFETIME_MS, DEFAULT_TTL_NS } from '../constants.ts'\nimport { createIPNSRecord } from '../records.ts'\nimport { marshalIPNSRecord, multihashToIPNSRoutingKey, unmarshalIPNSRecord } from '../utils.ts'\nimport type { PublishResult, PublishOptions } from '../index.ts'\nimport type { LocalStore } from '../local-store.ts'\nimport type { IPNSRouting } from '../routing/index.ts'\nimport type { Keychain, PrivateKey } from '@helia/interface'\nimport type { AbortOptions, ComponentLogger } from '@libp2p/interface'\nimport type { Datastore } from 'interface-datastore'\n\nexport interface IPNSPublisherComponents {\n datastore: Datastore\n logger: ComponentLogger\n keychain: Keychain\n}\n\nexport interface IPNSPublisherInit {\n localStore: LocalStore\n routers: IPNSRouting[]\n}\n\nexport class IPNSPublisher {\n public readonly routers: IPNSRouting[]\n private readonly localStore: LocalStore\n private readonly keychain: Keychain\n\n constructor (components: IPNSPublisherComponents, init: IPNSPublisherInit) {\n this.keychain = components.keychain\n this.localStore = init.localStore\n this.routers = init.routers\n }\n\n async publish (keyName: string, value: string, options: PublishOptions = {}): Promise<PublishResult> {\n try {\n const key = await this.#loadOrCreateKey(keyName, options)\n const digest = key.publicKey.toMultihash()\n const routingKey = multihashToIPNSRoutingKey(digest)\n let sequenceNumber = 1n\n\n if (await this.localStore.has(routingKey, options)) {\n // if we have published under this key before, increment the sequence number\n const { record } = await this.localStore.get(routingKey, options)\n const existingRecord = await unmarshalIPNSRecord(routingKey, record, this.keychain, options)\n sequenceNumber = existingRecord.sequence + 1n\n }\n\n // convert ttl from milliseconds to nanoseconds as createIPNSRecord expects\n const ttlNs = options.ttl != null ? BigInt(options.ttl) * 1_000_000n : DEFAULT_TTL_NS\n const lifetime = options.lifetime ?? DEFAULT_LIFETIME_MS\n const record = await createIPNSRecord(key, value, sequenceNumber, lifetime, { ...options, ttlNs })\n const marshaledRecord = marshalIPNSRecord(record)\n\n if (options.offline === true) {\n // only store record locally\n await this.localStore.put(routingKey, marshaledRecord, { ...options, metadata: { keyName, lifetime } })\n } else {\n // publish record to routing (including the local store)\n await Promise.all(this.routers.map(async r => {\n await r.put(routingKey, marshaledRecord, { ...options, metadata: { keyName, lifetime } })\n }))\n }\n\n return {\n record: {\n ...record,\n publicKey: key.publicKey\n },\n name: `/ipns/${key.publicKey.toCID().toString(base36)}`,\n publicKey: key.publicKey\n }\n } catch (err: any) {\n options.onProgress?.(new CustomProgressEvent<Error>('ipns:publish:error', err))\n throw err\n }\n }\n\n /**\n * Create the private key if it is not in the keychain already, defaulting to\n * Ed25519 keys\n */\n async #loadOrCreateKey (keyName: string, options?: AbortOptions): Promise<PrivateKey> {\n try {\n return await this.keychain.exportKey(keyName, options)\n } catch (err: any) {\n if (err.name === 'NotFoundError') {\n // create a new key\n return this.keychain.generateKey(keyName, options)\n } else {\n throw err\n }\n }\n }\n\n async unpublish (keyName: string, options?: AbortOptions): Promise<void> {\n const key = await this.keychain.exportKey(keyName, options)\n const digest = key.publicKey.toMultihash()\n const routingKey = multihashToIPNSRoutingKey(digest)\n await this.localStore.delete(routingKey, options)\n }\n}\n", "export default function pDefer() {\n\tconst deferred = {};\n\n\tdeferred.promise = new Promise((resolve, reject) => {\n\t\tdeferred.resolve = resolve;\n\t\tdeferred.reject = reject;\n\t});\n\n\treturn deferred;\n}\n", "// 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", "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", "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", "/**\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", "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.js'\nimport { QueueFullError } from '../errors.js'\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", "import { anySignal } from 'any-signal'\nimport { setMaxListeners } from 'main-event'\nimport { debounce } from './debounce.ts'\nimport type { AbortOptions } from '@libp2p/interface'\n\nexport interface RepeatingTask {\n /**\n * Update the interval after which the next iteration of the task will run.\n *\n * This is useful if, for example, you want to retry a task with a short rest\n * duration until it succeeds, then periodically after that.\n *\n * This only affects the next iteration of the task, if it is currently\n * running, that run will not be interrupted.\n *\n * Setting the interval to the current value has no effect.\n */\n setInterval(ms: number): void\n\n /**\n * Update the amount of time a task will run before the passed abort signal\n * will fire.\n *\n * This only affects the next iteration of the task, if it is currently\n * running, that run will not be interrupted.\n */\n setTimeout(ms: number): void\n\n /**\n * Schedule the task to be run immediately - if the task is not running it\n * will run after a short delay in order to debounce multiple `.run()`\n * invocations.\n */\n run(): void\n\n /**\n * Start the task running\n */\n start(): void\n\n /**\n * Stop the task running\n */\n stop(): void\n}\n\nexport interface RepeatingTaskOptions {\n /**\n * How long the task is allowed to run before the passed AbortSignal fires an\n * abort event\n */\n timeout?: number\n\n /**\n * Whether to schedule the task to run immediately\n *\n * @default false\n */\n runImmediately?: boolean\n\n /**\n * When `.run()` is called to run the task outside of the current interval,\n * debounce repeated calls to `.run()` by this amount.\n *\n * @default 100\n */\n debounce?: number\n}\n\nexport function repeatingTask (fn: (options?: AbortOptions) => void | Promise<void>, interval: number, options?: RepeatingTaskOptions): RepeatingTask {\n let timeout: ReturnType<typeof setTimeout>\n let shutdownController: AbortController\n let running = false\n\n function runTask (): void {\n const opts: AbortOptions = {\n signal: shutdownController.signal\n }\n\n let signal: ReturnType<typeof anySignal> | undefined\n\n if (options?.timeout != null) {\n signal = anySignal([shutdownController.signal, AbortSignal.timeout(options.timeout)])\n setMaxListeners(Infinity, signal)\n\n opts.signal = signal\n }\n\n running = true\n\n Promise.resolve().then(async () => {\n await fn(opts)\n })\n .catch(() => {})\n .finally(() => {\n if (signal != null) {\n if (signal.aborted) {\n signal.clear()\n } else {\n // Clear listeners once this per-run signal eventually aborts\n signal.addEventListener('abort', () => {\n signal.clear()\n }, { once: true })\n }\n }\n\n running = false\n\n if (shutdownController.signal.aborted) {\n // task has been cancelled, bail\n return\n }\n\n // reschedule\n timeout = setTimeout(runTask, interval)\n })\n }\n\n const runTaskDebounced = debounce(runTask, options?.debounce ?? 100)\n\n let started = false\n\n return {\n setInterval: (ms): void => {\n if (interval === ms) {\n // already running at this interval, nothing to do\n return\n }\n\n interval = ms\n\n // maybe reschedule\n if (timeout != null) {\n clearTimeout(timeout)\n timeout = setTimeout(runTask, interval)\n }\n },\n setTimeout: (ms): void => {\n options ??= {}\n options.timeout = ms\n },\n run: (): void => {\n if (running) {\n return\n }\n\n clearTimeout(timeout)\n runTaskDebounced()\n },\n start: (): void => {\n if (started) {\n return\n }\n\n started = true\n shutdownController = new AbortController()\n setMaxListeners(Infinity, shutdownController.signal)\n\n // run now\n if (options?.runImmediately === true) {\n queueMicrotask(() => {\n runTask()\n })\n } else {\n // run later\n timeout = setTimeout(runTask, interval)\n }\n },\n stop: (): void => {\n clearTimeout(timeout)\n shutdownController?.abort()\n started = false\n }\n }\n}\n", "import { Queue, repeatingTask } from '@libp2p/utils'\nimport { DEFAULT_REPUBLISH_CONCURRENCY, DEFAULT_REPUBLISH_INTERVAL_MS, DEFAULT_TTL_NS } from '../constants.ts'\nimport { createIPNSRecord } from '../records.ts'\nimport { marshalIPNSRecord, unmarshalIPNSRecord } from '../utils.ts'\nimport { shouldRepublish } from '../utils.ts'\nimport type { IPNSRecord } from '../index.ts'\nimport type { LocalStore } from '../local-store.ts'\nimport type { IPNSRouting } from '../routing/index.ts'\nimport type { Keychain, PrivateKey } from '@helia/interface'\nimport type { AbortOptions, ComponentLogger, Logger } from '@libp2p/interface'\nimport type { RepeatingTask } from '@libp2p/utils'\n\nexport interface IPNSRepublisherComponents {\n logger: ComponentLogger\n keychain: Keychain\n}\n\nexport interface IPNSRepublisherInit {\n republishConcurrency?: number\n republishInterval?: number\n routers: IPNSRouting[]\n localStore: LocalStore\n}\n\nexport class IPNSRepublisher {\n public readonly routers: IPNSRouting[]\n private readonly localStore: LocalStore\n private readonly republishTask: RepeatingTask\n private readonly log: Logger\n private readonly keychain: Keychain\n private started: boolean = false\n private readonly republishConcurrency: number\n\n constructor (components: IPNSRepublisherComponents, init: IPNSRepublisherInit) {\n this.log = components.logger.forComponent('helia:ipns')\n this.localStore = init.localStore\n this.keychain = components.keychain\n this.republishConcurrency = init.republishConcurrency || DEFAULT_REPUBLISH_CONCURRENCY\n this.started = false\n this.routers = init.routers ?? []\n\n this.republishTask = repeatingTask(this.#republish.bind(this), init.republishInterval ?? DEFAULT_REPUBLISH_INTERVAL_MS, {\n runImmediately: true\n })\n\n if (this.started) {\n this.republishTask.start()\n }\n }\n\n start (): void {\n if (this.started) {\n return\n }\n\n this.started = true\n this.republishTask.start()\n }\n\n stop (): void {\n if (!this.started) {\n return\n }\n\n this.started = false\n this.republishTask.stop()\n }\n\n async #republish (options: AbortOptions = {}): Promise<void> {\n if (!this.started) {\n return\n }\n\n this.log('starting ipns republish records loop')\n\n const queue = new Queue({\n concurrency: this.republishConcurrency\n })\n\n try {\n const recordsToRepublish: Array<{ routingKey: Uint8Array, record: IPNSRecord }> = []\n let listed = 0\n\n // Find all records using the localStore.list method\n for await (const { routingKey, record, metadata, created } of this.localStore.list(options)) {\n listed++\n\n if (metadata == null) {\n // Skip if no metadata is found from before we started\n // storing metadata or for records republished without a key\n this.log('no metadata found for record %b, skipping', routingKey)\n continue\n }\n let ipnsRecord: IPNSRecord\n try {\n ipnsRecord = await unmarshalIPNSRecord(routingKey, record, this.keychain, options)\n } catch (err: any) {\n this.log.error('error unmarshaling record - %e', err)\n continue\n }\n\n // Only republish records that are within the DHT or record expiry threshold\n if (!shouldRepublish(ipnsRecord, created)) {\n this.log.trace('skipping record %b within republish threshold', routingKey)\n continue\n }\n const sequenceNumber = ipnsRecord.sequence + 1n\n const ttlNs = ipnsRecord.ttl ?? DEFAULT_TTL_NS\n let privKey: PrivateKey\n\n try {\n privKey = await this.keychain.exportKey(metadata.keyName)\n } catch (err: any) {\n this.log.error('missing key %s, skipping republishing record - %e', metadata.keyName, err)\n continue\n }\n\n try {\n const updatedRecord = await createIPNSRecord(privKey, ipnsRecord.value, sequenceNumber, metadata.lifetime, {\n ...options,\n ttlNs\n })\n recordsToRepublish.push({\n routingKey,\n record: updatedRecord\n })\n } catch (err: any) {\n this.log.error('error creating updated IPNS record for %s - %e', routingKey, err)\n continue\n }\n }\n\n this.log(`found ${recordsToRepublish.length}/${listed} records to republish`)\n\n // Republish each record\n for (const { routingKey, record } of recordsToRepublish) {\n // Add job to queue to republish the record to all routers\n queue.add(async () => {\n try {\n const marshaledRecord = marshalIPNSRecord(record)\n await Promise.all(\n this.routers.map(r => r.put(routingKey, marshaledRecord, options))\n )\n } catch (err: any) {\n this.log.error('error republishing record - %e', err)\n }\n }, options)\n }\n } catch (err: any) {\n this.log.error('error during republish - %e', err)\n }\n\n await queue.onIdle(options) // Wait for all jobs to complete\n }\n}\n", "const f32 = new Float32Array([-0])\nconst f8b = new Uint8Array(f32.buffer)\n\n/**\n * Writes a 32 bit float to a buffer using little endian byte order\n */\nexport function writeFloatLE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[0]\n buf[pos + 1] = f8b[1]\n buf[pos + 2] = f8b[2]\n buf[pos + 3] = f8b[3]\n}\n\n/**\n * Writes a 32 bit float to a buffer using big endian byte order\n */\nexport function writeFloatBE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[3]\n buf[pos + 1] = f8b[2]\n buf[pos + 2] = f8b[1]\n buf[pos + 3] = f8b[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using little endian byte order\n */\nexport function readFloatLE (buf: Uint8Array, pos: number): number {\n f8b[0] = buf[pos]\n f8b[1] = buf[pos + 1]\n f8b[2] = buf[pos + 2]\n f8b[3] = buf[pos + 3]\n return f32[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using big endian byte order\n */\nexport function readFloatBE (buf: Uint8Array, pos: number): number {\n f8b[3] = buf[pos]\n f8b[2] = buf[pos + 1]\n f8b[1] = buf[pos + 2]\n f8b[0] = buf[pos + 3]\n return f32[0]\n}\n\nconst f64 = new Float64Array([-0])\nconst d8b = new Uint8Array(f64.buffer)\n\n/**\n * Writes a 64 bit double to a buffer using little endian byte order\n */\nexport function writeDoubleLE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[0]\n buf[pos + 1] = d8b[1]\n buf[pos + 2] = d8b[2]\n buf[pos + 3] = d8b[3]\n buf[pos + 4] = d8b[4]\n buf[pos + 5] = d8b[5]\n buf[pos + 6] = d8b[6]\n buf[pos + 7] = d8b[7]\n}\n\n/**\n * Writes a 64 bit double to a buffer using big endian byte order\n */\nexport function writeDoubleBE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[7]\n buf[pos + 1] = d8b[6]\n buf[pos + 2] = d8b[5]\n buf[pos + 3] = d8b[4]\n buf[pos + 4] = d8b[3]\n buf[pos + 5] = d8b[2]\n buf[pos + 6] = d8b[1]\n buf[pos + 7] = d8b[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using little endian byte order\n */\nexport function readDoubleLE (buf: Uint8Array, pos: number): number {\n d8b[0] = buf[pos]\n d8b[1] = buf[pos + 1]\n d8b[2] = buf[pos + 2]\n d8b[3] = buf[pos + 3]\n d8b[4] = buf[pos + 4]\n d8b[5] = buf[pos + 5]\n d8b[6] = buf[pos + 6]\n d8b[7] = buf[pos + 7]\n return f64[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using big endian byte order\n */\nexport function readDoubleBE (buf: Uint8Array, pos: number): number {\n d8b[7] = buf[pos]\n d8b[6] = buf[pos + 1]\n d8b[5] = buf[pos + 2]\n d8b[4] = buf[pos + 3]\n d8b[3] = buf[pos + 4]\n d8b[2] = buf[pos + 5]\n d8b[1] = buf[pos + 6]\n d8b[0] = buf[pos + 7]\n return f64[0]\n}\n", "// the largest BigInt we can safely downcast to a Number\nconst MAX_SAFE_NUMBER_INTEGER = BigInt(Number.MAX_SAFE_INTEGER)\nconst MIN_SAFE_NUMBER_INTEGER = BigInt(Number.MIN_SAFE_INTEGER)\n\n/**\n * Constructs new long bits.\n *\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @function Object() { [native code] }\n * @param {number} lo - Low 32 bits, unsigned\n * @param {number} hi - High 32 bits, unsigned\n */\nexport class LongBits {\n public lo: number\n public hi: number\n\n constructor (lo: number, hi: number) {\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits\n */\n this.lo = lo | 0\n\n /**\n * High bits\n */\n this.hi = hi | 0\n }\n\n /**\n * Converts this long bits to a possibly unsafe JavaScript number\n */\n toNumber (unsigned: boolean = false): number {\n if (!unsigned && (this.hi >>> 31) > 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(lo + hi * 4294967296)\n }\n return this.lo + this.hi * 4294967296\n }\n\n /**\n * Converts this long bits to a bigint\n */\n toBigInt (unsigned: boolean = false): bigint {\n if (unsigned) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n if ((this.hi >>> 31) !== 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(BigInt(lo) + (BigInt(hi) << 32n))\n }\n\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n /**\n * Converts this long bits to a string\n */\n toString (unsigned: boolean = false): string {\n return this.toBigInt(unsigned).toString()\n }\n\n /**\n * Zig-zag encodes this long bits\n */\n zzEncode (): this {\n const mask = this.hi >> 31\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0\n this.lo = (this.lo << 1 ^ mask) >>> 0\n return this\n }\n\n /**\n * Zig-zag decodes this long bits\n */\n zzDecode (): this {\n const mask = -(this.lo & 1)\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0\n this.hi = (this.hi >>> 1 ^ mask) >>> 0\n return this\n }\n\n /**\n * Calculates the length of this longbits when encoded as a varint.\n */\n length (): number {\n const part0 = this.lo\n const part1 = (this.lo >>> 28 | this.hi << 4) >>> 0\n const part2 = this.hi >>> 24\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromBigInt (value: bigint): LongBits {\n if (value === 0n) {\n return zero\n }\n\n if (value < MAX_SAFE_NUMBER_INTEGER && value > MIN_SAFE_NUMBER_INTEGER) {\n return this.fromNumber(Number(value))\n }\n\n const negative = value < 0n\n\n if (negative) {\n value = -value\n }\n\n let hi = value >> 32n\n let lo = value - (hi << 32n)\n\n if (negative) {\n hi = ~hi | 0n\n lo = ~lo | 0n\n\n if (++lo > TWO_32) {\n lo = 0n\n if (++hi > TWO_32) { hi = 0n }\n }\n }\n\n return new LongBits(Number(lo), Number(hi))\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromNumber (value: number): LongBits {\n if (value === 0) { return zero }\n const sign = value < 0\n if (sign) { value = -value }\n let lo = value >>> 0\n let hi = (value - lo) / 4294967296 >>> 0\n if (sign) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n if (++lo > 4294967295) {\n lo = 0\n if (++hi > 4294967295) { hi = 0 }\n }\n }\n return new LongBits(lo, hi)\n }\n\n /**\n * Constructs new long bits from a number, long or string\n */\n static from (value: bigint | number | string | { low: number, high: number }): LongBits {\n if (typeof value === 'number') {\n return LongBits.fromNumber(value)\n }\n if (typeof value === 'bigint') {\n return LongBits.fromBigInt(value)\n }\n if (typeof value === 'string') {\n return LongBits.fromBigInt(BigInt(value))\n }\n return value.low != null || value.high != null ? new LongBits(value.low >>> 0, value.high >>> 0) : zero\n }\n}\n\nconst zero = new LongBits(0, 0)\nzero.toBigInt = function () { return 0n }\nzero.zzEncode = zero.zzDecode = function () { return this }\nzero.length = function () { return 1 }\n\nconst TWO_32 = 4294967296n\n", "/**\n * Calculates the UTF8 byte length of a string\n */\nexport function length (string: string): number {\n let len = 0\n let c = 0\n for (let i = 0; i < string.length; ++i) {\n c = string.charCodeAt(i)\n\n if (c < 128) {\n len += 1\n } else if (c < 2048) {\n len += 2\n } else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\n ++i\n len += 4\n } else {\n len += 3\n }\n }\n\n return len\n}\n\n/**\n * Reads UTF8 bytes as a string\n */\nexport function read (buffer: Uint8Array, start: number, end: number): string {\n const len = end - start\n\n if (len < 1) {\n return ''\n }\n\n let parts: string[] | undefined\n const chunk: number[] = []\n let i = 0 // char offset\n let t: number // temporary\n\n while (start < end) {\n t = buffer[start++]\n\n if (t < 128) {\n chunk[i++] = t\n } else if (t > 191 && t < 224) {\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63\n } else if (t > 239 && t < 365) {\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000\n chunk[i++] = 0xD800 + (t >> 10)\n chunk[i++] = 0xDC00 + (t & 1023)\n } else {\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63\n }\n\n if (i > 8191) {\n (parts ?? (parts = [])).push(String.fromCharCode.apply(String, chunk))\n i = 0\n }\n }\n\n if (parts != null) {\n if (i > 0) {\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)))\n }\n\n return parts.join('')\n }\n\n return String.fromCharCode.apply(String, chunk.slice(0, i))\n}\n\n/**\n * Writes a string as UTF8 bytes\n */\nexport function write (string: string, buffer: Uint8Array, offset: number): number {\n const start = offset\n let c1 // character 1\n let c2 // character 2\n\n for (let i = 0; i < string.length; ++i) {\n c1 = string.charCodeAt(i)\n\n if (c1 < 128) {\n buffer[offset++] = c1\n } else if (c1 < 2048) {\n buffer[offset++] = c1 >> 6 | 192\n buffer[offset++] = c1 & 63 | 128\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF)\n ++i\n buffer[offset++] = c1 >> 18 | 240\n buffer[offset++] = c1 >> 12 & 63 | 128\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n } else {\n buffer[offset++] = c1 >> 12 | 224\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n }\n }\n\n return offset - start\n}\n", "import { decodeUint8Array, encodingLength } from 'uint8-varint'\nimport { readFloatLE, readDoubleLE } from './float.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\n public pos: number\n public len: number\n\n public _slice = Uint8Array.prototype.subarray\n\n constructor (buffer: Uint8Array) {\n /**\n * Read buffer\n */\n this.buf = buffer\n\n /**\n * Read buffer position\n */\n this.pos = 0\n\n /**\n * Read buffer length\n */\n this.len = buffer.length\n }\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32 (): number {\n let value = 4294967295\n\n value = (this.buf[this.pos] & 127) >>> 0; if (this.buf[this.pos++] < 128) { return value }\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) { return value }\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) { return value }\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) { return value }\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) { return value }\n\n if ((this.pos += 5) > this.len) {\n this.pos = this.len\n throw indexOutOfRange(this, 10)\n }\n\n return value\n }\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32 (): number {\n return this.uint32() | 0\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32 (): number {\n const value = this.uint32()\n return value >>> 1 ^ -(value & 1) | 0\n }\n\n /**\n * Reads a varint as a boolean\n */\n bool (): boolean {\n return this.uint32() !== 0\n }\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32 (): number {\n if (this.pos + 4 > this.len) { throw indexOutOfRange(this, 4) }\n\n const res = readFixed32End(this.buf, this.pos += 4)\n\n return res\n }\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32 (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const res = readFixed32End(this.buf, this.pos += 4) | 0\n\n return res\n }\n\n /**\n * Reads a float (32 bit) as a number\n */\n float (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const value = readFloatLE(this.buf, this.pos)\n this.pos += 4\n return value\n }\n\n /**\n * Reads a double (64 bit float) as a number\n */\n double (): number {\n /* istanbul ignore if */\n if (this.pos + 8 > this.len) { throw indexOutOfRange(this, 4) }\n\n const value = readDoubleLE(this.buf, this.pos)\n this.pos += 8\n return value\n }\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes (): Uint8Array {\n const length = this.uint32()\n const start = this.pos\n const end = this.pos + length\n\n /* istanbul ignore if */\n if (end > this.len) {\n throw indexOutOfRange(this, length)\n }\n\n this.pos += length\n\n return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1\n ? new Uint8Array(0)\n : this.buf.subarray(start, end)\n }\n\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string (): string {\n const bytes = this.bytes()\n return utf8.read(bytes, 0, bytes.length)\n }\n\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varint\n */\n skip (length?: number): this {\n if (typeof length === 'number') {\n /* istanbul ignore if */\n if (this.pos + length > this.len) { throw indexOutOfRange(this, length) }\n this.pos += length\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n } while ((this.buf[this.pos++] & 128) !== 0)\n }\n return this\n }\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType (wireType: number): this {\n switch (wireType) {\n case 0:\n this.skip()\n break\n case 1:\n this.skip(8)\n break\n case 2:\n this.skip(this.uint32())\n break\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType)\n }\n break\n case 5:\n this.skip(4)\n break\n\n /* istanbul ignore next */\n default:\n throw Error(`invalid wire type ${wireType} at offset ${this.pos}`)\n }\n return this\n }\n\n private readLongVarint (): LongBits {\n // tends to deopt with local vars for octet etc.\n const bits = new LongBits(0, 0)\n let i = 0\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n i = 0\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len) { throw indexOutOfRange(this) }\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0\n return bits\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n } else {\n for (; i < 5; ++i) {\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n }\n\n throw Error('invalid varint encoding')\n }\n\n private readFixed64 (): LongBits {\n if (this.pos + 8 > this.len) {\n throw indexOutOfRange(this, 8)\n }\n\n const lo = readFixed32End(this.buf, this.pos += 4)\n const hi = readFixed32End(this.buf, this.pos += 4)\n\n return new LongBits(lo, hi)\n }\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64 (): bigint {\n return this.readLongVarint().toBigInt()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n int64Number (): number {\n return this.readLongVarint().toNumber()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a string\n */\n int64String (): string {\n return this.readLongVarint().toString()\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64 (): bigint {\n return this.readLongVarint().toBigInt(true)\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n uint64Number (): number {\n const value = decodeUint8Array(this.buf, this.pos)\n this.pos += encodingLength(value)\n return value\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a string\n */\n uint64String (): string {\n return this.readLongVarint().toString(true)\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64 (): bigint {\n return this.readLongVarint().zzDecode().toBigInt()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * possibly unsafe JavaScript number\n */\n sint64Number (): number {\n return this.readLongVarint().zzDecode().toNumber()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * string\n */\n sint64String (): string {\n return this.readLongVarint().zzDecode().toString()\n }\n\n /**\n * Reads fixed 64 bits\n */\n fixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads fixed 64 bits returned as a possibly unsafe JavaScript number\n */\n fixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads fixed 64 bits returned as a string\n */\n fixed64String (): string {\n return this.readFixed64().toString()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a possibly unsafe\n * JavaScript number\n */\n sfixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a string\n */\n sfixed64String (): string {\n return this.readFixed64().toString()\n }\n}\n\nexport function createReader (buf: Uint8Array | Uint8ArrayList): Reader {\n return new Uint8ArrayReader(buf instanceof Uint8Array ? buf : buf.subarray())\n}\n", "import { createReader } from './utils/reader.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 { allocUnsafe } from 'uint8arrays/alloc'\n\n/**\n * A general purpose buffer pool\n */\nexport default function pool (size?: number): (size: number) => Uint8Array {\n const SIZE = size ?? 8192\n const MAX = SIZE >>> 1\n let slab: Uint8Array\n let offset = SIZE\n return function poolAlloc (size: number) {\n if (size < 1 || size > MAX) {\n return allocUnsafe(size)\n }\n\n if (offset + size > SIZE) {\n slab = allocUnsafe(SIZE)\n offset = 0\n }\n\n const buf = slab.subarray(offset, offset += size)\n\n if ((offset & 7) !== 0) {\n // align to 32 bit\n offset = (offset | 7) + 1\n }\n\n return buf\n }\n}\n", "import { encodeUint8Array, encodingLength } from 'uint8-varint'\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { writeFloatLE, writeDoubleLE } from './float.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 {\n if (globalThis.Buffer != null) {\n return allocUnsafe(size)\n }\n\n return bufferPool(size)\n}\n\n/**\n * When a value is written, the writer calculates its byte length and puts it into a linked\n * list of operations to perform when finish() is called. This both allows us to allocate\n * buffers of the exact required size and reduces the amount of work we have to do compared\n * to first calculating over objects and then encoding over objects. In our case, the encoding\n * part is just a linked list walk calling operations with already prepared values.\n */\nclass Uint8ArrayWriter implements Writer {\n /**\n * Current length\n */\n public len: number\n\n /**\n * Operations head\n */\n public head: Op<any>\n\n /**\n * Operations tail\n */\n public tail: Op<any>\n\n /**\n * Linked forked states\n */\n public states?: any\n\n constructor () {\n this.len = 0\n this.head = new Op(noop, 0, 0)\n this.tail = this.head\n this.states = null\n }\n\n /**\n * Pushes a new operation to the queue\n */\n _push (fn: WriterOperation<any>, len: number, val: any): this {\n this.tail = this.tail.next = new Op(fn, len, val)\n this.len += len\n\n return this\n }\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32 (value: number): this {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0) <\n 128\n ? 1\n : value < 16384\n ? 2\n : value < 2097152\n ? 3\n : value < 268435456\n ? 4\n : 5,\n value)).len\n return this\n }\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32 (value: number): this {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value)\n }\n\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32 (value: number): this {\n return this.uint32((value << 1 ^ value >> 31) >>> 0)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number (value: number): this {\n return this._push(encodeUint8Array, encodingLength(value), value)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String (value: string): this {\n return this.uint64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64 (value: bigint): this {\n return this.uint64(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number (value: number): this {\n return this.uint64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String (value: string): this {\n return this.uint64String(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number (value: number): this {\n const bits = LongBits.fromNumber(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String (value: string): this {\n return this.sint64(BigInt(value))\n }\n\n /**\n * Writes a boolish value as a varint\n */\n bool (value: boolean): this {\n return this._push(writeByte, 1, value ? 1 : 0)\n }\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32 (value: number): this {\n return this._push(writeFixed32, 4, value >>> 0)\n }\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32 (value: number): this {\n return this.fixed32(value)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number (value: number): this {\n const bits = LongBits.fromNumber(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String (value: string): this {\n return this.fixed64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64 (value: bigint): this {\n return this.fixed64(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number (value: number): this {\n return this.fixed64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String (value: string): this {\n return this.fixed64String(value)\n }\n\n /**\n * Writes a float (32 bit)\n */\n float (value: number): this {\n return this._push(writeFloatLE, 4, value)\n }\n\n /**\n * Writes a double (64 bit float).\n *\n * @function\n * @param {number} value - Value to write\n * @returns {Writer} `this`\n */\n double (value: number): this {\n return this._push(writeDoubleLE, 8, value)\n }\n\n /**\n * Writes a sequence of bytes\n */\n bytes (value: Uint8Array): this {\n const len = value.length >>> 0\n\n if (len === 0) {\n return this._push(writeByte, 1, 0)\n }\n\n return this.uint32(len)._push(writeBytes, len, value)\n }\n\n /**\n * Writes a string\n */\n string (value: string): this {\n const len = utf8.length(value)\n return len !== 0\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0)\n }\n\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork (): this {\n this.states = new State(this)\n this.head = this.tail = new Op(noop, 0, 0)\n this.len = 0\n return this\n }\n\n /**\n * Resets this instance to the last state\n */\n reset (): this {\n if (this.states != null) {\n this.head = this.states.head\n this.tail = this.states.tail\n this.len = this.states.len\n this.states = this.states.next\n } else {\n this.head = this.tail = new Op(noop, 0, 0)\n this.len = 0\n }\n return this\n }\n\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim (): this {\n const head = this.head\n const tail = this.tail\n const len = this.len\n this.reset().uint32(len)\n if (len !== 0) {\n this.tail.next = head.next // skip noop\n this.tail = tail\n this.len += len\n }\n return this\n }\n\n /**\n * Finishes the write operation\n */\n finish (): Uint8Array {\n let head = this.head.next // skip noop\n const buf = alloc(this.len)\n let pos = 0\n while (head != null) {\n head.fn(head.val, buf, pos)\n pos += head.len\n head = head.next\n }\n // this.head = this.tail = null;\n return buf\n }\n}\n\nfunction writeByte (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n}\n\nfunction writeVarint32 (val: number, buf: Uint8Array, pos: number): void {\n while (val > 127) {\n buf[pos++] = val & 127 | 128\n val >>>= 7\n }\n buf[pos] = val\n}\n\n/**\n * Constructs a new varint writer operation instance.\n *\n * @classdesc Scheduled varint writer operation\n */\nclass VarintOp extends Op<number> {\n public next?: Op<any>\n\n constructor (len: number, val: number) {\n super(writeVarint32, len, val)\n this.next = undefined\n }\n}\n\nfunction writeVarint64 (val: LongBits, buf: Uint8Array, pos: number): void {\n while (val.hi !== 0) {\n buf[pos++] = val.lo & 127 | 128\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0\n val.hi >>>= 7\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128\n val.lo = val.lo >>> 7\n }\n buf[pos++] = val.lo\n}\n\nfunction writeFixed32 (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n buf[pos + 1] = val >>> 8 & 255\n buf[pos + 2] = val >>> 16 & 255\n buf[pos + 3] = val >>> 24\n}\n\nfunction writeBytes (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos)\n}\n\nif (globalThis.Buffer != null) {\n Uint8ArrayWriter.prototype.bytes = function (value: Uint8Array) {\n const len = value.length >>> 0\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeBytesBuffer, len, value)\n }\n\n return this\n }\n\n Uint8ArrayWriter.prototype.string = function (value: string) {\n const len = globalThis.Buffer.byteLength(value)\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeStringBuffer, len, value)\n }\n\n return this\n }\n}\n\nfunction writeBytesBuffer (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos) // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n}\n\nfunction writeStringBuffer (val: string, buf: Uint8Array, pos: number): void {\n if (val.length < 40) {\n // plain js is faster for short strings (probably due to redundant assertions)\n utf8.write(val, buf, pos)\n // @ts-expect-error buf isn't a Uint8Array?\n } else if (buf.utf8Write != null) {\n // @ts-expect-error buf isn't a Uint8Array?\n buf.utf8Write(val, pos)\n } else {\n buf.set(uint8ArrayFromString(val), pos)\n }\n}\n\n/**\n * Creates a new writer\n */\nexport function createWriter (): Writer {\n return new Uint8ArrayWriter()\n}\n", "import { createWriter } from './utils/writer.ts'\nimport type { Codec } from './codec.ts'\n\nexport function encodeMessage <T> (message: Partial<T>, codec: Pick<Codec<T>, 'encode'>): Uint8Array {\n const w = createWriter()\n\n codec.encode(message, w, {\n lengthDelimited: false\n })\n\n return w.finish()\n}\n", "import { 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 { 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, message, streamMessage } from 'protons-runtime'\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc'\nimport type { Codec, DecodeOptions } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface Record {\n key: Uint8Array\n value: Uint8Array\n timeReceived: string\n}\n\nexport namespace Record {\n let _codec: Codec<Record>\n\n export const codec = (): Codec<Record> => {\n if (_codec == null) {\n _codec = message<Record>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.key != null && obj.key.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.key)\n }\n\n if ((obj.value != null && obj.value.byteLength > 0)) {\n w.uint32(18)\n w.bytes(obj.value)\n }\n\n if ((obj.timeReceived != null && obj.timeReceived !== '')) {\n w.uint32(42)\n w.string(obj.timeReceived)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {\n key: uint8ArrayAlloc(0),\n value: uint8ArrayAlloc(0),\n timeReceived: ''\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.key = reader.bytes()\n break\n }\n case 2: {\n obj.value = reader.bytes()\n break\n }\n case 5: {\n obj.timeReceived = reader.string()\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}.key`,\n value: reader.bytes()\n }\n break\n }\n case 2: {\n yield {\n field: `${prefix}.value`,\n value: reader.bytes()\n }\n break\n }\n case 5: {\n yield {\n field: `${prefix}.timeReceived`,\n value: reader.string()\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 RecordKeyFieldEvent {\n field: '$.key'\n value: Uint8Array\n }\n\n export interface RecordValueFieldEvent {\n field: '$.value'\n value: Uint8Array\n }\n\n export interface RecordTimeReceivedFieldEvent {\n field: '$.timeReceived'\n value: string\n }\n\n export function encode (obj: Partial<Record>): Uint8Array {\n return encodeMessage(obj, Record.codec())\n }\n\n export function decode (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<Record>): Record {\n return decodeMessage(buf, Record.codec(), opts)\n }\n\n export function stream (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<Record>): Generator<RecordKeyFieldEvent | RecordValueFieldEvent | RecordTimeReceivedFieldEvent> {\n return streamMessage(buf, Record.codec(), opts)\n }\n}\n", "/**\n * Convert a JavaScript date into an `RFC3339Nano` formatted\n * string\n */\nexport function toRFC3339 (time: Date): string {\n const year = time.getUTCFullYear()\n const month = String(time.getUTCMonth() + 1).padStart(2, '0')\n const day = String(time.getUTCDate()).padStart(2, '0')\n const hour = String(time.getUTCHours()).padStart(2, '0')\n const minute = String(time.getUTCMinutes()).padStart(2, '0')\n const seconds = String(time.getUTCSeconds()).padStart(2, '0')\n const milliseconds = time.getUTCMilliseconds()\n const nanoseconds = String(milliseconds * 1000 * 1000).padStart(9, '0')\n\n return `${year}-${month}-${day}T${hour}:${minute}:${seconds}.${nanoseconds}Z`\n}\n\n/**\n * Parses a date string formatted as `RFC3339Nano` into a\n * JavaScript Date object\n */\nexport function parseRFC3339 (time: string): Date {\n const rfc3339Matcher = new RegExp(\n // 2006-01-02T\n '(\\\\d{4})-(\\\\d{2})-(\\\\d{2})T' +\n // 15:04:05\n '(\\\\d{2}):(\\\\d{2}):(\\\\d{2})' +\n // .999999999Z\n '\\\\.(\\\\d+)Z'\n )\n const m = String(time).trim().match(rfc3339Matcher)\n\n if (m == null) {\n throw new Error('Invalid format')\n }\n\n const year = parseInt(m[1], 10)\n const month = parseInt(m[2], 10) - 1\n const date = parseInt(m[3], 10)\n const hour = parseInt(m[4], 10)\n const minute = parseInt(m[5], 10)\n const second = parseInt(m[6], 10)\n const millisecond = parseInt(m[7].slice(0, -6), 10)\n\n return new Date(Date.UTC(year, month, date, hour, minute, second, millisecond))\n}\n", "/**\n * @packageDocumentation\n *\n * This is an implementation of the [routing record format](https://github.com/libp2p/specs/blob/b9efe152c29f93f7a87931c14d78ae11e7924d5a/kad-dht/README.md?plain=1#L408-L425) used by libp2p to store data in the datastore passed to the libp2p constructor.\n *\n * @example Deserialization\n *\n * ```TypeScript\n * import { Libp2pRecord } from '@libp2p/record'\n *\n * const buf = Uint8Array.from([0, 1, 2, 3])\n * const record = Libp2pRecord.deserialize(buf)\n * ```\n *\n * @example Serialization\n *\n * ```TypeScript\n * import { Libp2pRecord } from '@libp2p/record'\n *\n * const key = Uint8Array.from([0, 1, 2, 3])\n * const value = Uint8Array.from([0, 1, 2, 3])\n * const timeReceived = new Date()\n *\n * const record = new Libp2pRecord(key, value, timeReceived)\n * const buf = record.serialize()\n * ```\n */\n\nimport {\n Record\n} from './record.ts'\nimport * as utils from './utils.ts'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class Libp2pRecord {\n public key: Uint8Array\n public value: Uint8Array\n public timeReceived: Date\n\n constructor (key: Uint8Array, value: Uint8Array, timeReceived: Date) {\n if (!(key instanceof Uint8Array)) {\n throw new Error('key must be a Uint8Array')\n }\n\n if (!(value instanceof Uint8Array)) {\n throw new Error('value must be a Uint8Array')\n }\n\n this.key = key\n this.value = value\n this.timeReceived = timeReceived\n }\n\n serialize (): Uint8Array {\n return Record.encode(this.prepareSerialize())\n }\n\n /**\n * Return the object format ready to be given to the protobuf library.\n */\n prepareSerialize (): Record {\n return {\n key: this.key,\n value: this.value,\n timeReceived: utils.toRFC3339(this.timeReceived)\n }\n }\n\n /**\n * Decode a protobuf encoded record\n */\n static deserialize (raw: Uint8Array | Uint8ArrayList): Libp2pRecord {\n const rec = Record.decode(raw)\n\n return new Libp2pRecord(rec.key, rec.value, new Date(rec.timeReceived))\n }\n\n /**\n * Create a record from the raw object returned from the protobuf library\n */\n static fromDeserialized (obj: Record): Libp2pRecord {\n const receivedTime = utils.parseRFC3339(obj.timeReceived)\n\n if (obj.key == null) {\n throw new Error('key missing from deserialized object')\n }\n\n if (obj.value == null) {\n throw new Error('value missing from deserialized object')\n }\n\n const rec = new Libp2pRecord(\n obj.key, obj.value, receivedTime\n )\n\n return rec\n }\n}\n", "/**\n * @packageDocumentation\n *\n * This module implements the [libp2p Kademlia spec](https://github.com/libp2p/specs/blob/master/kad-dht/README.md) in TypeScript.\n *\n * The Kademlia DHT allow for several operations such as finding peers, searching for providers of DHT records, etc.\n *\n * @example Using with libp2p\n *\n * ```TypeScript\n * import { kadDHT } from '@libp2p/kad-dht'\n * import { createLibp2p } from 'libp2p'\n * import { peerIdFromString } from '@libp2p/peer-id'\n * import { ping } from '@libp2p/ping'\n * import { identify } from '@libp2p/identify'\n *\n * const node = await createLibp2p({\n * services: {\n * dht: kadDHT({\n * // DHT options\n * }),\n * ping: ping(),\n * identify: identify()\n * }\n * })\n *\n * const peerId = peerIdFromString('QmFoo')\n * const peerInfo = await node.peerRouting.findPeer(peerId)\n *\n * console.info(peerInfo) // peer id, multiaddrs\n * ```\n *\n * @example Connecting to the IPFS Amino DHT\n *\n * The [Amino DHT](https://blog.ipfs.tech/2023-09-amino-refactoring/) is a public-good DHT used by IPFS to fetch content, find peers, etc.\n *\n * If you are trying to access content on the public internet, this is the implementation you want.\n *\n * ```TypeScript\n * import { kadDHT, removePrivateAddressesMapper } from '@libp2p/kad-dht'\n * import { createLibp2p } from 'libp2p'\n * import { peerIdFromString } from '@libp2p/peer-id'\n * import { ping } from '@libp2p/ping'\n * import { identify } from '@libp2p/identify'\n *\n * const node = await createLibp2p({\n * services: {\n * aminoDHT: kadDHT({\n * protocol: '/ipfs/kad/1.0.0',\n * peerInfoMapper: removePrivateAddressesMapper\n * }),\n * ping: ping(),\n * identify: identify()\n * }\n * })\n *\n * const peerId = peerIdFromString('QmFoo')\n * const peerInfo = await node.peerRouting.findPeer(peerId)\n *\n * console.info(peerInfo) // peer id, multiaddrs\n * ```\n *\n * @example Connecting to a LAN-only DHT\n *\n * This DHT only works with privately dialable peers.\n *\n * This is for use when peers are on the local area network.\n *\n * ```TypeScript\n * import { kadDHT, removePublicAddressesMapper } from '@libp2p/kad-dht'\n * import { createLibp2p } from 'libp2p'\n * import { peerIdFromString } from '@libp2p/peer-id'\n * import { ping } from '@libp2p/ping'\n * import { identify } from '@libp2p/identify'\n *\n * const node = await createLibp2p({\n * services: {\n * lanDHT: kadDHT({\n * protocol: '/ipfs/lan/kad/1.0.0',\n * peerInfoMapper: removePublicAddressesMapper,\n * clientMode: false\n * }),\n * ping: ping(),\n * identify: identify()\n * }\n * })\n *\n * const peerId = peerIdFromString('QmFoo')\n * const peerInfo = await node.peerRouting.findPeer(peerId)\n *\n * console.info(peerInfo) // peer id, multiaddrs\n * ```\n *\n * @example Connecting to both a LAN-only DHT and the IPFS Amino DHT\n *\n * When using multiple DHTs, you should specify distinct datastore, metrics and\n * log prefixes to ensure that data is kept separate for each instance.\n *\n * ```TypeScript\n * import { kadDHT, removePublicAddressesMapper, removePrivateAddressesMapper } from '@libp2p/kad-dht'\n * import { createLibp2p } from 'libp2p'\n * import { peerIdFromString } from '@libp2p/peer-id'\n * import { ping } from '@libp2p/ping'\n * import { identify } from '@libp2p/identify'\n *\n * const node = await createLibp2p({\n * services: {\n * lanDHT: kadDHT({\n * protocol: '/ipfs/lan/kad/1.0.0',\n * peerInfoMapper: removePublicAddressesMapper,\n * clientMode: false,\n * logPrefix: 'libp2p:dht-lan',\n * datastorePrefix: '/dht-lan',\n * metricsPrefix: 'libp2p_dht_lan'\n * }),\n * aminoDHT: kadDHT({\n * protocol: '/ipfs/kad/1.0.0',\n * peerInfoMapper: removePrivateAddressesMapper,\n * logPrefix: 'libp2p:dht-amino',\n * datastorePrefix: '/dht-amino',\n * metricsPrefix: 'libp2p_dht_amino'\n * }),\n * ping: ping(),\n * identify: identify()\n * }\n * })\n *\n * const peerId = peerIdFromString('QmFoo')\n * const peerInfo = await node.peerRouting.findPeer(peerId)\n *\n * console.info(peerInfo) // peer id, multiaddrs\n * ```\n */\n\nimport { KadDHT as KadDHTClass } from './kad-dht.ts'\nimport { MessageType } from './message/dht.ts'\nimport { removePrivateAddressesMapper, removePublicAddressesMapper, passthroughMapper } from './utils.ts'\nimport type { Libp2pEvents, ComponentLogger, Metrics, PeerId, PeerInfo, PeerStore, RoutingOptions, PrivateKey, AbortOptions } from '@libp2p/interface'\nimport type { AddressManager, ConnectionManager, Registrar } from '@libp2p/interface-internal'\nimport type { Ping } from '@libp2p/ping'\nimport type { AdaptiveTimeoutInit } from '@libp2p/utils'\nimport type { Datastore } from 'interface-datastore'\nimport type { TypedEventTarget } from 'main-event'\nimport type { CID } from 'multiformats/cid'\nimport type { ProgressEvent } from 'progress-events'\n\nexport { Libp2pRecord as Record } from '@libp2p/record'\nexport { removePrivateAddressesMapper, removePublicAddressesMapper, passthroughMapper }\n\n/**\n * The types of events emitted during DHT queries\n */\nexport enum EventTypes {\n SEND_QUERY = 0,\n PEER_RESPONSE,\n FINAL_PEER,\n QUERY_ERROR,\n PROVIDER,\n VALUE,\n ADD_PEER,\n DIAL_PEER,\n PATH_ENDED\n}\n\n/**\n * The types of messages sent to peers during DHT queries\n */\nexport { MessageType }\n\nexport type MessageName = keyof typeof MessageType\n\nexport interface DHTRecord {\n key: Uint8Array\n value: Uint8Array\n timeReceived?: Date\n}\n\nexport type DHTProgressEvents =\n ProgressEvent<'kad-dht:query:send-query', SendQueryEvent> |\n ProgressEvent<'kad-dht:query:peer-response', PeerResponseEvent> |\n ProgressEvent<'kad-dht:query:final-peer', FinalPeerEvent> |\n ProgressEvent<'kad-dht:query:query-error', QueryErrorEvent> |\n ProgressEvent<'kad-dht:query:provider', ProviderEvent> |\n ProgressEvent<'kad-dht:query:value', ValueEvent> |\n ProgressEvent<'kad-dht:query:add-peer', AddPeerEvent> |\n ProgressEvent<'kad-dht:query:dial-peer', DialPeerEvent>\n\nexport interface DisjointPath {\n index: number\n queued: number\n running: number\n total: number\n}\n\n/**\n * Emitted when sending queries to remote peers\n */\nexport interface SendQueryEvent {\n to: PeerId\n type: EventTypes.SEND_QUERY\n name: 'SEND_QUERY'\n messageName: keyof typeof MessageType\n messageType: MessageType\n path: DisjointPath\n}\n\n/**\n * Emitted when query responses are received form remote peers. Depending on the query\n * these events may be followed by a `FinalPeerEvent`, a `ValueEvent` or a `ProviderEvent`.\n */\nexport interface PeerResponseEvent {\n from: PeerId\n type: EventTypes.PEER_RESPONSE\n name: 'PEER_RESPONSE'\n messageName: keyof typeof MessageType\n messageType: MessageType\n closer: PeerInfo[]\n providers: PeerInfo[]\n record?: DHTRecord\n path: DisjointPath\n}\n\n/**\n * Emitted at the end of a `findPeer` query\n */\nexport interface FinalPeerEvent {\n from: PeerId\n peer: PeerInfo\n type: EventTypes.FINAL_PEER\n name: 'FINAL_PEER'\n path: DisjointPath\n}\n\n/**\n * Something went wrong with the query\n */\nexport interface QueryErrorEvent {\n from: PeerId\n type: EventTypes.QUERY_ERROR\n name: 'QUERY_ERROR'\n error: Error\n path: DisjointPath\n}\n\n/**\n * Emitted when providers are found\n */\nexport interface ProviderEvent {\n from: PeerId\n type: EventTypes.PROVIDER\n name: 'PROVIDER'\n providers: PeerInfo[]\n path: DisjointPath\n}\n\n/**\n * Emitted when values are found\n */\nexport interface ValueEvent {\n from: PeerId\n type: EventTypes.VALUE\n name: 'VALUE'\n value: Uint8Array\n path: DisjointPath\n}\n\n/**\n * Emitted when peers are added to a query\n */\nexport interface AddPeerEvent {\n type: EventTypes.ADD_PEER\n name: 'ADD_PEER'\n peer: PeerId\n path: DisjointPath\n}\n\n/**\n * Emitted when peers are dialled and a new stream is opened as part of a query\n */\nexport interface DialPeerEvent {\n peer: PeerId\n type: EventTypes.DIAL_PEER\n name: 'DIAL_PEER'\n path: DisjointPath\n}\n\n/**\n * Emitted when sending queries to remote peers\n */\nexport interface PathEndedEvent {\n type: EventTypes.PATH_ENDED\n name: 'PATH_ENDED'\n path: DisjointPath\n}\n\nexport type QueryEvent = SendQueryEvent | PeerResponseEvent | FinalPeerEvent | QueryErrorEvent | ProviderEvent | ValueEvent | AddPeerEvent | DialPeerEvent | PathEndedEvent\n\nexport interface RoutingTable {\n size: number\n}\n\nexport interface PeerInfoMapper {\n (peer: PeerInfo): PeerInfo\n}\n\nexport interface SetModeOptions extends AbortOptions {\n force?: boolean\n}\n\nexport interface KadDHT {\n /**\n * This is the maximum size of the k-buckets and how many peers are looked up\n * when searching for peers close to a key.\n */\n readonly k: number\n\n /**\n * Query concurrency factor - this controls how many peers we contact in\n * parallel during a query.\n */\n readonly a: number\n\n /**\n * From section 4.4 of the S/Kademlia paper - this is how many disjoint paths\n * are used during a query.\n */\n readonly d: number\n\n /**\n * Validators validate DHT records that are found\n */\n readonly validators: Record<string, ValidateFn>\n\n /**\n * When multiple records for a DHT key are found, selectors choose one record\n */\n readonly selectors: Record<string, SelectFn>\n\n /**\n * Get a value from the DHT, the final ValueEvent will be the best value\n */\n get(key: Uint8Array, options?: RoutingOptions): AsyncIterable<QueryEvent>\n\n /**\n * Find providers of a given CID\n */\n findProviders(key: CID, options?: RoutingOptions): AsyncIterable<QueryEvent>\n\n /**\n * Find a peer on the DHT\n */\n findPeer(id: PeerId, options?: RoutingOptions): AsyncIterable<QueryEvent>\n\n /**\n * Find the closest peers to the passed key\n */\n getClosestPeers(key: Uint8Array, options?: RoutingOptions): AsyncIterable<QueryEvent>\n\n /**\n * Store provider records for the passed CID on the DHT pointing to us\n */\n provide(key: CID, options?: RoutingOptions): AsyncIterable<QueryEvent>\n\n /**\n * Provider records must be re-published every 24 hours - pass a previously\n * provided CID here to not re-publish a record for it any more\n */\n cancelReprovide(key: CID, options?: AbortOptions): Promise<void>\n\n /**\n * Store the passed value under the passed key on the DHT\n */\n put(key: Uint8Array, value: Uint8Array, options?: RoutingOptions): AsyncIterable<QueryEvent>\n\n /**\n * Returns the mode this node is in\n */\n getMode(): 'client' | 'server'\n\n /**\n * If 'server' this node will respond to DHT queries, if 'client' this node\n * will not.\n */\n setMode(mode: 'client' | 'server', options?: SetModeOptions): Promise<void>\n\n /**\n * Force a routing table refresh\n */\n refreshRoutingTable(options?: AbortOptions): Promise<void>\n}\n\nexport interface SingleKadDHT extends KadDHT {\n routingTable: RoutingTable\n}\n\n/**\n * A selector function takes a DHT key and a list of records and returns the\n * index of the best record in the list\n */\nexport interface SelectFn {\n (key: Uint8Array, records: Uint8Array[]): number | Promise<number>\n}\n\n/**\n * A validator function takes a DHT key and the value of the record for that key\n * and throws if the record is invalid\n */\nexport interface ValidateFn {\n (key: Uint8Array, value: Uint8Array, options?: AbortOptions): void | Promise<void>\n}\n\n/**\n * Selectors are a map of key prefixes to selector functions\n */\nexport type Selectors = Record<string, SelectFn>\n\n/**\n * Validators are a map of key prefixes to validator functions\n */\nexport type Validators = Record<string, ValidateFn>\n\nexport interface ProvidersInit {\n /**\n * @default 256\n */\n cacheSize?: number\n /**\n * How often invalid records are cleaned in seconds\n *\n * @default 5_400\n */\n cleanupInterval?: number\n /**\n * How long is a provider valid for in seconds\n *\n * @default 86_400\n */\n provideValidity?: number\n}\n\nexport interface ReProvideInit {\n /**\n * How many re-provide operations to run simultaneously\n *\n * @default 10\n */\n concurrency?: number\n\n /**\n * How long to let the re-provide queue grow\n *\n * @default 16_384\n */\n maxQueueSize?: number\n\n /**\n * How long before the record expiry to re-provide in ms\n *\n * @default 86_400_000 (24 hours)\n */\n threshold?: number\n\n /**\n * How often to check which records need re-providing in ms\n *\n * @default 3_600_000 (1 hour)\n */\n interval?: number\n\n /**\n * How long provider records are valid for in ms\n *\n * @default 172_800_000 (48 hours)\n */\n validity?: number\n}\n\nexport interface KadDHTInit {\n /**\n * How many peers to store in each kBucket. Once there are more than this\n * number of peers for a given prefix in a kBucket, the node will start to\n * ping existing peers to see if they are still online - if they are offline\n * they will be evicted and the new peer added.\n *\n * @default 20\n */\n kBucketSize?: number\n\n /**\n * The threshold at which a kBucket will be split into two smaller kBuckets.\n *\n * KBuckets will not be split once the maximum trie depth is reached\n * (controlled by the `prefixLength` option) so one can replicate go-libp2p's\n * accelerated DHT client by (for example) setting `kBucketSize` to `Infinity`\n * and `kBucketSplitThreshold` to 20.\n *\n * @default kBucketSize\n */\n kBucketSplitThreshold?: number\n\n /**\n * How many peers are queried in parallel during a query.\n *\n * @default 3\n */\n alpha?: number\n\n /**\n * How many disjoint paths are used during a query\n *\n * @see https://telematics.tm.kit.edu/publications/Files/267/SKademlia_2007.pdf - section 4.4\n *\n * @default alpha\n */\n disjointPaths?: number\n\n /**\n * Concurrency for background routing table updates from query responses.\n *\n * @default min(alpha * 2, 16)\n */\n routingTableUpdateQueueConcurrency?: number\n\n /**\n * Maximum number of pending routing table updates from query responses.\n *\n * @default 16384\n */\n routingTableUpdateMaxQueueSize?: number\n\n /**\n * How many bits of the KAD-ID of peers to use when creating the routing\n * table.\n *\n * The routing table is a binary trie with peers stored in the leaf nodes. The\n * larger this number gets, the taller the trie can grow and the more peers\n * can be stored.\n *\n * Storing more peers means fewer lookups (and network operations) are needed\n * to locate a certain peer, but also that more memory is consumed and more\n * CPU while responding to queries (e.g. with more peers in the table sorting\n * the closest peers becomes more expensive) and CPU/network during table\n * maintenance (e.g. checking peers are still online).\n *\n * The larger this value, the more prefix bits must be the same for a peer to\n * be stored in a KAD bucket, so the fewer nodes that bucket is likely to\n * contain.\n *\n * The total number of peers in the table is a factor of `prefixLength` and\n * `kBucketSize`:\n *\n * ```\n * (2 ^ prefixLength) * kBucketSize\n * ```\n *\n * @default 6\n */\n prefixLength?: number\n\n /**\n * If true, only ever be a DHT client. If false, be a DHT client until told\n * to be a DHT server via `setMode`.\n *\n * In general this should be left as the default because server mode will be\n * selected automatically when libp2p establishes that the current node has\n * a publicly dialable address.\n *\n * The exception to this is LAN-only DHT (e.g. for testing purposes) where it\n * is safe to assume that the current node is dialable.\n *\n * @default false\n */\n clientMode?: boolean\n\n /**\n * Record selectors\n */\n selectors?: Selectors\n\n /**\n * Record validators\n */\n validators?: Validators\n\n /**\n * How often to query our own PeerId in order to ensure we have a\n * good view on the KAD address space local to our PeerId\n */\n querySelfInterval?: number\n\n /**\n * During startup we run the self-query at a shorter interval to ensure\n * the containing node can respond to queries quickly. Set this interval\n * here in ms.\n *\n * @default 1000\n */\n initialQuerySelfInterval?: number\n\n /**\n * After startup by default all queries will be paused until there is at least\n * one peer in the routing table.\n *\n * Pass true here to disable this behavior.\n *\n * @default false\n */\n allowQueryWithZeroPeers?: boolean\n\n /**\n * The network protocol to use\n *\n * @default \"/ipfs/kad/1.0.0\"\n */\n protocol?: string\n\n /**\n * The logging prefix to use\n *\n * @default \"libp2p:kad-dht\"\n */\n logPrefix?: string\n\n /**\n * The datastore prefix to use\n *\n * @default \"/dht\"\n */\n datastorePrefix?: string\n\n /**\n * The metrics prefix to use\n *\n * @default \"libp2p_kad_dht\"\n */\n metricsPrefix?: string\n\n /**\n * Settings for how long to wait in ms when pinging DHT peers to decide if\n * they should be evicted from the routing table or not.\n */\n pingOldContactTimeout?: Omit<AdaptiveTimeoutInit, 'metricsName' | 'metrics'>\n\n /**\n * How many peers to ping in parallel when deciding if they should\n * be evicted from the routing table or not\n *\n * @default 10\n */\n pingOldContactConcurrency?: number\n\n /**\n * How long the queue to ping peers is allowed to grow\n *\n * @default 100\n */\n pingOldContactMaxQueueSize?: number\n\n /**\n * Settings for how long to wait in ms when pinging DHT peers to decide if\n * they should be added to the routing table or not.\n */\n pingNewContactTimeout?: Omit<AdaptiveTimeoutInit, 'metricsName' | 'metrics'>\n\n /**\n * How many peers to ping in parallel when deciding if they should be added to\n * the routing table or not\n *\n * @default 10\n */\n pingNewContactConcurrency?: number\n\n /**\n * How long the queue to ping peers is allowed to grow\n *\n * @default 100\n */\n pingNewContactMaxQueueSize?: number\n\n /**\n * How many parallel incoming streams to allow on the DHT protocol per\n * connection\n *\n * @default 32\n */\n maxInboundStreams?: number\n\n /**\n * How many parallel outgoing streams to allow on the DHT protocol per\n * connection\n *\n * @default 64\n */\n maxOutboundStreams?: number\n\n /**\n * Initialization options for the Providers component\n */\n providers?: ProvidersInit\n\n /**\n * Initialization options for the Reprovider component\n */\n reprovide?: ReProvideInit\n\n /**\n * For every incoming and outgoing PeerInfo, override address configuration\n * with this filter.\n */\n peerInfoMapper?(peer: PeerInfo): PeerInfo\n\n /**\n * Dynamic network timeout settings for sending messages to peers\n */\n networkDialTimeout?: Omit<AdaptiveTimeoutInit, 'metricsName' | 'metrics'>\n\n /**\n * When a peer that supports the KAD-DHT protocol connects we try to add it to\n * the routing table. This setting is how long an active routing table update\n * may run for in ms once it starts processing. Time spent waiting in the\n * routing table update queue does not count towards this timeout.\n *\n * @default 10_000\n */\n onPeerConnectTimeout?: number\n\n /**\n * When acting as a DHT server, all incoming RPC requests must complete within\n * this timeout in ms otherwise the stream will be closed.\n *\n * @default 10_000\n */\n incomingMessageTimeout?: number\n}\n\nexport interface KadDHTComponents {\n peerId: PeerId\n privateKey: PrivateKey\n registrar: Registrar\n addressManager: AddressManager\n peerStore: PeerStore\n metrics?: Metrics\n connectionManager: ConnectionManager\n datastore: Datastore\n events: TypedEventTarget<Libp2pEvents>\n logger: ComponentLogger\n ping: Ping\n}\n\n/**\n * Creates a custom DHT implementation, please ensure you pass a `protocol`\n * string as an option.\n */\nexport function kadDHT (init: KadDHTInit = {}): (components: KadDHTComponents) => KadDHT {\n return (components: KadDHTComponents) => new KadDHTClass(components, init)\n}\n", "import { decodeMessage, encodeMessage, message, streamMessage } from 'protons-runtime'\nimport type { Codec, DecodeOptions } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface IPNSPublishMetadata {\n keyName: string\n lifetime: number\n}\n\nexport namespace IPNSPublishMetadata {\n let _codec: Codec<IPNSPublishMetadata>\n\n export const codec = (): Codec<IPNSPublishMetadata> => {\n if (_codec == null) {\n _codec = message<IPNSPublishMetadata>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.keyName != null && obj.keyName !== '')) {\n w.uint32(10)\n w.string(obj.keyName)\n }\n\n if ((obj.lifetime != null && obj.lifetime !== 0)) {\n w.uint32(16)\n w.uint32(obj.lifetime)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {\n keyName: '',\n lifetime: 0\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.keyName = reader.string()\n break\n }\n case 2: {\n obj.lifetime = reader.uint32()\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}.keyName`,\n value: reader.string()\n }\n break\n }\n case 2: {\n yield {\n field: `${prefix}.lifetime`,\n value: reader.uint32()\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 IPNSPublishMetadataKeyNameFieldEvent {\n field: '$.keyName'\n value: string\n }\n\n export interface IPNSPublishMetadataLifetimeFieldEvent {\n field: '$.lifetime'\n value: number\n }\n\n export function encode (obj: Partial<IPNSPublishMetadata>): Uint8Array<ArrayBuffer> {\n return encodeMessage(obj, IPNSPublishMetadata.codec())\n }\n\n export function decode (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<IPNSPublishMetadata>): IPNSPublishMetadata {\n return decodeMessage(buf, IPNSPublishMetadata.codec(), opts)\n }\n\n export function stream (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<IPNSPublishMetadata>): Generator<IPNSPublishMetadataKeyNameFieldEvent | IPNSPublishMetadataLifetimeFieldEvent> {\n return streamMessage(buf, IPNSPublishMetadata.codec(), opts)\n }\n}\n", "import { Record } from '@libp2p/kad-dht'\nimport { CustomProgressEvent } from 'progress-events'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { IPNSPublishMetadata } from './pb/metadata.ts'\nimport { dhtRoutingKey, DHT_RECORD_PREFIX, ipnsMetadataKey } from './utils.ts'\nimport type { DatastoreProgressEvents, GetOptions, PutOptions } from './routing/index.ts'\nimport type { AbortOptions, Logger } from '@libp2p/interface'\nimport type { Datastore } from 'interface-datastore'\n\nexport interface GetResult {\n record: Uint8Array\n created: Date\n}\n\nexport interface ListResult {\n routingKey: Uint8Array\n record: Uint8Array\n created: Date\n metadata?: IPNSPublishMetadata\n}\n\nexport interface ListOptions extends AbortOptions {\n onProgress?(evt: DatastoreProgressEvents): void\n}\n\nexport interface LocalStore {\n /**\n * Put an IPNS record into the datastore\n *\n * @param routingKey - The routing key for the IPNS record\n * @param marshaledRecord - The marshaled IPNS record\n * @param options - options for the put operation including metadata\n */\n put(routingKey: Uint8Array, marshaledRecord: Uint8Array, options?: PutOptions): Promise<void>\n get(routingKey: Uint8Array, options?: GetOptions): Promise<GetResult>\n has(routingKey: Uint8Array, options?: AbortOptions): Promise<boolean>\n delete(routingKey: Uint8Array, options?: AbortOptions): Promise<void>\n /**\n * List all IPNS records in the datastore\n */\n list(options?: ListOptions): AsyncIterable<ListResult>\n}\n\n/**\n * Read/write IPNS records to the datastore as DHT records.\n *\n * This lets us publish IPNS records offline then serve them to the network\n * later in response to DHT queries.\n */\nexport function localStore (datastore: Datastore, log: Logger): LocalStore {\n return {\n async put (routingKey: Uint8Array, marshalledRecord: Uint8Array, options: PutOptions = {}) {\n try {\n const key = dhtRoutingKey(routingKey)\n\n // don't overwrite existing, identical records as this will affect the\n // TTL\n try {\n const existingBuf = await datastore.get(key)\n const existingRecord = Record.deserialize(existingBuf)\n\n if (uint8ArrayEquals(existingRecord.value, marshalledRecord)) {\n return\n }\n } catch (err: any) {\n if (err.name !== 'NotFoundError') {\n throw err\n }\n }\n\n // Marshal to libp2p record as the DHT does\n const record = new Record(routingKey, marshalledRecord, new Date())\n\n options.onProgress?.(new CustomProgressEvent('ipns:routing:datastore:put'))\n const batch = datastore.batch()\n batch.put(key, record.serialize())\n\n if (options.metadata != null) {\n // derive the datastore key for the IPNS metadata from the same routing key\n batch.put(ipnsMetadataKey(routingKey), IPNSPublishMetadata.encode(options.metadata))\n }\n await batch.commit(options)\n } catch (err: any) {\n options.onProgress?.(new CustomProgressEvent<Error>('ipns:routing:datastore:error', err))\n throw err\n }\n },\n async get (routingKey: Uint8Array, options: GetOptions = {}): Promise<GetResult> {\n try {\n const key = dhtRoutingKey(routingKey)\n\n options.onProgress?.(new CustomProgressEvent('ipns:routing:datastore:get'))\n const buf = await datastore.get(key, options)\n\n // Unmarshal libp2p record as the DHT does\n const record = Record.deserialize(buf)\n\n return {\n record: record.value,\n created: record.timeReceived\n }\n } catch (err: any) {\n options.onProgress?.(new CustomProgressEvent<Error>('ipns:routing:datastore:error', err))\n throw err\n }\n },\n async has (routingKey: Uint8Array, options: AbortOptions = {}): Promise<boolean> {\n const key = dhtRoutingKey(routingKey)\n return datastore.has(key, options)\n },\n async delete (routingKey, options): Promise<void> {\n const key = dhtRoutingKey(routingKey)\n const batch = datastore.batch()\n batch.delete(key)\n batch.delete(ipnsMetadataKey(routingKey))\n await batch.commit(options)\n },\n async * list (options: ListOptions = {}): AsyncIterable<ListResult> {\n try {\n options.onProgress?.(new CustomProgressEvent('ipns:routing:datastore:list'))\n\n // Query all records with the DHT_RECORD_PREFIX\n for await (const { key, value } of datastore.query({\n prefix: DHT_RECORD_PREFIX\n }, options)) {\n try {\n // Deserialize the record\n const libp2pRecord = Record.deserialize(value)\n\n // Extract the routing key from the datastore key\n const keyString = key.toString()\n const routingKeyBase32 = keyString.substring(DHT_RECORD_PREFIX.length)\n const routingKey = uint8ArrayFromString(routingKeyBase32, 'base32')\n\n const metadataKey = ipnsMetadataKey(routingKey)\n let metadata: IPNSPublishMetadata | undefined\n try {\n const metadataBuf = await datastore.get(metadataKey, options)\n metadata = IPNSPublishMetadata.decode(metadataBuf)\n } catch (err: any) {\n log.error('Error deserializing metadata for %s - %e', routingKeyBase32, err)\n }\n\n yield {\n routingKey,\n metadata,\n record: libp2pRecord.value,\n created: libp2pRecord.timeReceived\n }\n } catch (err) {\n // Skip invalid records\n log.error('Error deserializing record - %e', err)\n }\n }\n } catch (err: any) {\n options.onProgress?.(new CustomProgressEvent<Error>('ipns:routing:datastore:error', err))\n throw err\n }\n }\n }\n}\n", "import { CustomProgressEvent } from 'progress-events'\nimport type { GetOptions, PutOptions } from './index.ts'\nimport type { IPNSRouting } from '../index.ts'\nimport type { Routing } from '@helia/interface'\nimport type { ProgressEvent } from 'progress-events'\n\nexport interface HeliaRoutingComponents {\n routing: Routing\n}\n\nexport type HeliaRoutingProgressEvents =\n ProgressEvent<'ipns:routing:helia:error', Error>\n\nexport class HeliaRouting implements IPNSRouting {\n private readonly routing: Routing\n\n constructor (routing: Routing) {\n this.routing = routing\n }\n\n async put (routingKey: Uint8Array, marshaledRecord: Uint8Array, options: PutOptions = {}): Promise<void> {\n try {\n await this.routing.put(routingKey, marshaledRecord, options)\n } catch (err: any) {\n options.onProgress?.(new CustomProgressEvent<Error>('ipns:routing:helia:error', err))\n throw err\n }\n }\n\n async get (routingKey: Uint8Array, options: GetOptions = {}): Promise<Uint8Array> {\n try {\n return await this.routing.get(routingKey, options)\n } catch (err: any) {\n options.onProgress?.(new CustomProgressEvent<Error>('ipns:routing:helia:error', err))\n throw err\n }\n }\n\n toString (): string {\n return 'HeliaRouting()'\n }\n}\n\n/**\n * The helia routing uses any available Routers configured on the passed Helia\n * node. This could be libp2p, HTTP API Delegated Routing, etc.\n */\nexport function helia (routing: Routing): IPNSRouting {\n return new HeliaRouting(routing)\n}\n", "import type { LocalStore } from '../local-store.ts'\nimport type { IPNSRouting, PutOptions, GetOptions } from './index.ts'\n\nclass LocalStoreRouting {\n private localStore: LocalStore\n\n constructor (localStore: LocalStore) {\n this.localStore = localStore\n }\n\n async put (routingKey: Uint8Array, marshaledRecord: Uint8Array, options?: PutOptions): Promise<void> {\n await this.localStore.put(routingKey, marshaledRecord, options)\n }\n\n async get (routingKey: Uint8Array, options?: GetOptions): Promise<Uint8Array> {\n const { record } = await this.localStore.get(routingKey, options)\n\n return record\n }\n\n toString (): string {\n return 'LocalStoreRouting()'\n }\n}\n\n/**\n * Returns an IPNSRouting implementation that reads/writes to the local store\n */\nexport function localStoreRouting (localStore: LocalStore): IPNSRouting {\n return new LocalStoreRouting(localStore)\n}\n", "import { CID } from 'multiformats/cid'\nimport { IPNSPublisher } from './ipns/publisher.ts'\nimport { IPNSRepublisher } from './ipns/republisher.ts'\nimport { IPNSResolver } from './ipns/resolver.ts'\nimport { localStore } from './local-store.ts'\nimport { helia } from './routing/helia.ts'\nimport { localStoreRouting } from './routing/local-store.ts'\nimport { ipnsSelector } from './selector.ts'\nimport { normalizeKey, normalizeValue, unmarshalIPNSRecord } from './utils.ts'\nimport { ipnsValidator } from './validator.ts'\nimport type { IPNSComponents, IPNS as IPNSInterface, IPNSOptions, PublishResult, PublishOptions, ResolveOptions, ResolveResult } from './index.ts'\nimport type { LocalStore } from './local-store.ts'\nimport type { IPNSRouting } from './routing/index.ts'\nimport type { PublicKey } from '@helia/interface'\nimport type { AbortOptions, Libp2p, Startable } from '@libp2p/interface'\nimport type { ValidateFn, SelectFn } from '@libp2p/kad-dht'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nexport class IPNS implements IPNSInterface, Startable {\n public readonly routers: IPNSRouting[]\n private readonly publisher: IPNSPublisher\n private readonly republisher: IPNSRepublisher\n private readonly resolver: IPNSResolver\n private readonly localStore: LocalStore\n private readonly components: IPNSComponents\n private started: boolean\n\n constructor (components: IPNSComponents, init: IPNSOptions = {}) {\n this.localStore = localStore(components.datastore, components.logger.forComponent('helia:ipns:local-store'))\n this.components = components\n this.started = false\n\n this.routers = [\n localStoreRouting(this.localStore),\n helia(components.routing),\n ...(init.routers ?? [])\n ]\n\n this.publisher = new IPNSPublisher(components, {\n ...init,\n routers: this.routers,\n localStore: this.localStore\n })\n this.republisher = new IPNSRepublisher(components, {\n ...init,\n routers: this.routers,\n localStore: this.localStore\n })\n this.resolver = new IPNSResolver(components, {\n ...init,\n routers: this.routers,\n localStore: this.localStore\n })\n\n // start republishing on Helia start\n components.events.addEventListener('start', this.start.bind(this))\n // stop republishing on Helia stop\n components.events.addEventListener('stop', this.stop.bind(this))\n\n if (this.started) {\n this.republisher.start()\n }\n\n for (const component of Object.values(this.components)) {\n if (isLibp2p(component)) {\n for (const service of Object.values(component.services)) {\n if (isKadDHT(service)) {\n // @ ts-expect-error https://github.com/libp2p/js-libp2p/pull/3506\n service.selectors.ipns = async (key: Uint8Array, values: Uint8Array[]): Promise<number> => {\n const records = await Promise.all(values.map(buf => unmarshalIPNSRecord(key, buf, this.components.keychain)))\n\n return ipnsSelector(key, records)\n }\n\n service.validators.ipns = async (key: Uint8Array, value: Uint8Array): Promise<void> => {\n const record = await unmarshalIPNSRecord(key, value, this.components.keychain)\n await ipnsValidator(record)\n }\n }\n }\n }\n }\n }\n\n start (): void {\n if (this.started) {\n return\n }\n\n this.started = true\n this.republisher.start()\n }\n\n stop (): void {\n if (!this.started) {\n return\n }\n\n this.started = false\n this.republisher.stop()\n }\n\n async publish (keyName: string, value: PublicKey | CID | MultihashDigest | string, options: PublishOptions = {}): Promise<PublishResult> {\n return this.publisher.publish(keyName, normalizeValue(value), options)\n }\n\n async * resolve (key: PublicKey | CID<unknown, 0x72> | MultihashDigest | string, options: ResolveOptions = {}): AsyncGenerator<ResolveResult> {\n const { digest } = normalizeKey(key)\n\n yield * this.resolver.resolve(digest, options)\n }\n\n async unpublish (keyName: string, options?: AbortOptions): Promise<void> {\n return this.publisher.unpublish(keyName, options)\n }\n}\n\nfunction isLibp2p (obj?: any): obj is Libp2p {\n return obj?.services != null\n}\n\nfunction isKadDHT (obj?: any): obj is { validators: Record<string, ValidateFn>, selectors: Record<string, SelectFn> } {\n return obj?.validators != null && obj?.selectors != null\n}\n"],
5
- "mappings": ";6pBAAA,IAAAA,GAAAC,GAAA,CAAAC,GAAAC,KAAA,KAAIC,IAAU,UAAU,CAAc,OAAOD,GAApB,MAA6BA,GAAO,QAAQE,GAAG,IAAIC,EAAE,MAAMC,EAAE,KAAKC,EAAE,OAAOD,EAAE,IAAIE,EAAEH,EAAEE,EAAEE,EAAE,IAAID,EAAEE,EAAE,OAAOC,EAAE,WAAWC,EAAE,IAAI,EAAE,YAAYC,EAAE,KAAK,OAAO,SAASC,EAAE,CAAC,IAAIC,EAAED,EAAEA,EAAE,EAAE,OAAUC,GAAH,IAAOD,EAAE,GAAOA,IAAJ,GAAO,EAAEA,GAAG,KAAK,GAAGC,CAAC,EAAED,EAAEV,EAAE,UAAUY,GAAGZ,EAAE,SAAS,SAASU,EAAE,CAAC,OAAO,IAAIV,EAAE,CAACU,CAAC,CAAC,EAAEV,EAAE,YAAYa,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAEb,EAAE,YAAYa,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAEb,EAAE,WAAW,SAASU,EAAE,CAAC,IAAIN,EAAES,EAAE,IAAIb,EAAEU,GAAGA,GAAG,IAAI,QAAQ,gBAAgB,SAASA,EAAE,CAAC,IAAIA,EAAE,CAACA,EAAEC,EAAE,MAAMD,EAAE,MAAM,IAAI,OAAOG,EAAE,KAAKH,EAAEC,EAAEA,CAAC,CAAC,EAAE,QAAQ,+BAA+B,SAASD,EAAEC,EAAEE,EAAE,CAAC,OAAOF,EAAE,IAAIE,GAAG,IAAIT,EAAE,KAAK,GAAG,CAACO,GAAG,CAACE,GAAG,EAAE,CAAC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,GAAkBH,CAAK,EACvBI,GAAMR,EAAW,OAAO,EACxB,GAAIC,EAAQ,SAAW,CAAA,GAGzB,OAAO,IAAIQ,GAAkBT,EAAY,CACvC,QAAAM,EACA,WAAYF,EACb,CACH",
6
- "names": ["require_timestamp_min", "__commonJSMin", "exports", "module", "Timestamp", "d", "l", "s", "T", "e", "f", "c", "g", "h", "m", "n", "t", "o", "r", "p", "y", "M", "u", "C", "D", "a", "i", "v", "w", "index_exports", "__export", "ipns", "ipnsResolver", "base32_exports", "__export", "base32", "base32hex", "base32hexpad", "base32hexpadupper", "base32hexupper", "base32pad", "base32padupper", "base32upper", "base32z", "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", "base32", "rfc4648", "base32upper", "base32pad", "base32padupper", "base32hex", "base32hexupper", "base32hexpad", "base32hexpadupper", "base32z", "base36_exports", "__export", "base36", "base36upper", "base36", "baseX", "base36upper", "base58_exports", "__export", "base58btc", "base58flickr", "base58btc", "baseX", "base58flickr", "encode_1", "encode", "MSB", "REST", "MSBALL", "INT", "num", "out", "offset", "oldOffset", "decode", "read", "MSB$1", "REST$1", "buf", "res", "shift", "counter", "b", "l", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "N8", "N9", "length", "value", "varint", "_brrp_varint", "varint_default", "decode", "data", "offset", "varint_default", "encodeTo", "int", "target", "encodingLength", "create", "code", "digest", "size", "sizeOffset", "encodingLength", "digestOffset", "bytes", "encodeTo", "Digest", "decode", "multihash", "coerce", "equals", "a", "b", "data", "toArrayBufferBackedArray", "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", "DEFAULT_TTL_NS", "DEFAULT_REPUBLISH_CONCURRENCY", "RecordsFailedValidationError", "InvalidValueError", "RecordNotFoundError", "SignatureCreationError", "SignatureVerificationError", "RecordExpiredError", "UnsupportedValidityError", "RecordTooLargeError", "InvalidRecordDataError", "InvalidEmbeddedPublicKeyError", "import_timestamp_nano", "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", "base10", "baseX", "base16_exports", "__export", "base16", "base16upper", "base16", "rfc4648", "base16upper", "base2_exports", "__export", "base2", "base2", "rfc4648", "base256emoji_exports", "__export", "base256emoji", "alphabet", "alphabetBytesToChars", "p", "c", "i", "alphabetCharsToBytes", "codePoint", "encode", "data", "decode", "str", "byts", "char", "byt", "base256emoji", "from", "base64_exports", "__export", "base64", "base64pad", "base64url", "base64urlpad", "base64", "rfc4648", "base64pad", "base64url", "base64urlpad", "base8_exports", "__export", "base8", "base8", "rfc4648", "identity_exports", "__export", "identity", "identity", "from", "buf", "toString", "str", "fromString", "textEncoder", "textDecoder", "identity_exports", "__export", "identity", "code", "name", "encode", "coerce", "digest", "input", "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", "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", "IpnsEntry", "ValidityType", "__ValidityTypeValues", "enumeration", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "prefix", "encode", "encodeMessage", "decode", "buf", "decodeMessage", "stream", "streamMessage", "ipnsSelector", "key", "data", "entries", "record", "index", "a", "b", "aSeq", "bSeq", "IpnsEntry", "recordAValidityDate", "NanoDate", "recordBValidityDate", "isByteArrayWithArrayBuffer", "b", "asUint8Array", "buf", "concat", "arrays", "length", "acc", "curr", "output", "allocUnsafe", "offset", "arr", "asUint8Array", "equals", "a", "b", "i", "isPublicKey", "obj", "AbortError", "message", "isEventObject", "obj", "isOnce", "options", "TypedEventEmitter", "#listeners", "type", "listeners", "listener", "once", "evt", "list", "callback", "detail", "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", "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", "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", "LIBP2P_KEY_CODEC", "MAX_RECORD_SIZE", "IPNS_PREFIX", "fromString", "IPNS_STRING_PREFIX", "isCodec", "digest", "codec", "DHT_RECORD_PREFIX", "IPNS_METADATA_PREFIX", "dhtRoutingKey", "key", "Key", "toString", "ipnsMetadataKey", "shouldRepublish", "ipnsRecord", "created", "now", "dhtExpiry", "recordExpiry", "ipnsRecordDataForV1Sig", "value", "validityType", "validity", "validityTypeBuffer", "fromString", "valueBytes", "concat", "ipnsRecordDataForV2Sig", "data", "entryData", "marshalIPNSRecord", "obj", "publicKey", "IpnsEntry", "valueToString", "CID", "toString", "unmarshalIPNSRecord", "routingKey", "marshalledRecord", "keychain", "options", "MAX_RECORD_SIZE", "RecordTooLargeError", "message", "SignatureVerificationError", "parseCborData", "routingMultihash", "multihashFromIPNSRoutingKey", "isCodec", "InvalidEmbeddedPublicKeyError", "validateCborDataMatchesPbData", "multihashToIPNSRoutingKey", "digest", "IPNS_PREFIX", "key", "decode", "createCborData", "sequence", "ttl", "ValidityType", "UnsupportedValidityError", "encode", "buf", "normalizeValue", "isPublicKey", "base36", "cid", "asCID", "LIBP2P_KEY_CODEC", "hasBytes", "string", "name", "rest", "component", "InvalidValueError", "isMultihashDigest", "normalizeKey", "codec", "base58btc", "entry", "InvalidRecordDataError", "equals", "hasToCID", "import_timestamp_nano", "ipnsValidator", "record", "options", "InvalidEmbeddedPublicKeyError", "isValid", "dataForSignature", "ipnsRecordDataForV2Sig", "SignatureVerificationError", "IpnsEntry", "NanoDate", "RecordExpiredError", "UnsupportedValidityError", "IPNSResolver", "components", "init", "key", "options", "digest", "normalizeKey", "routingKey", "multihashToIPNSRoutingKey", "record", "#findIpnsRecord", "IPNS_STRING_PREFIX", "records", "marshaledIPNSRecord", "created", "ipnsRecord", "unmarshalIPNSRecord", "ipnsValidator", "ttlMs", "DEFAULT_TTL_NS", "err", "RecordNotFoundError", "foundInvalid", "errors", "router", "RecordsFailedValidationError", "ipnsSelector", "CustomProgressEvent", "type", "detail", "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", "r", "setupFormatters", "formatters", "v", "error", "browser_default", "setup", "src_default", "browser_default", "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", "import_timestamp_nano", "log", "logger", "DEFAULT_TTL_NS", "namespace", "namespaceLength", "defaultCreateOptions", "createIPNSRecord", "privateKey", "value", "seq", "lifetime", "options", "expirationDate", "NanoDate", "validityType", "IpnsEntry", "ttlNs", "_create", "_create", "privateKey", "value", "seq", "validityType", "validity", "ttl", "options", "defaultCreateOptions", "isoValidity", "fromString", "data", "createCborData", "sigData", "ipnsRecordDataForV2Sig", "signatureV2", "publicKey", "shouldEmbedPublicKey", "record", "signatureV1", "signLegacyV1", "marshalIPNSRecord", "dataForSignature", "ipnsRecordDataForV1Sig", "error", "log", "SignatureCreationError", "key", "IPNSPublisher", "components", "init", "keyName", "value", "options", "key", "#loadOrCreateKey", "digest", "routingKey", "multihashToIPNSRoutingKey", "sequenceNumber", "record", "unmarshalIPNSRecord", "ttlNs", "DEFAULT_TTL_NS", "lifetime", "createIPNSRecord", "marshaledRecord", "marshalIPNSRecord", "r", "base36", "err", "CustomProgressEvent", "pDefer", "deferred", "resolve", "reject", "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", "TimeoutError", "_TimeoutError", "message", "options", "getAbortedReason", "signal", "pTimeout", "promise", "milliseconds", "fallback", "customTimers", "timer", "abortHandler", "cancelablePromise", "resolve", "reject", "timeoutError", "error", "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", "defaultTranslate", "signal", "raceSignal", "promise", "opts", "translateError", "listener", "resolve", "reject", "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", "repeatingTask", "fn", "interval", "options", "timeout", "shutdownController", "running", "runTask", "opts", "signal", "anySignal", "runTaskDebounced", "debounce", "started", "ms", "IPNSRepublisher", "components", "init", "DEFAULT_REPUBLISH_CONCURRENCY", "repeatingTask", "#republish", "options", "queue", "Queue", "recordsToRepublish", "listed", "routingKey", "record", "metadata", "created", "ipnsRecord", "unmarshalIPNSRecord", "err", "shouldRepublish", "sequenceNumber", "ttlNs", "DEFAULT_TTL_NS", "privKey", "updatedRecord", "createIPNSRecord", "marshaledRecord", "marshalIPNSRecord", "r", "f32", "f8b", "writeFloatLE", "val", "buf", "pos", "readFloatLE", "buf", "pos", "f8b", "f32", "f64", "d8b", "writeDoubleLE", "val", "buf", "pos", "readDoubleLE", "buf", "pos", "d8b", "f64", "MAX_SAFE_NUMBER_INTEGER", "MIN_SAFE_NUMBER_INTEGER", "LongBits", "_LongBits", "lo", "hi", "unsigned", "mask", "part0", "part1", "part2", "value", "zero", "negative", "TWO_32", "sign", "length", "string", "len", "c", "i", "read", "buffer", "start", "end", "parts", "chunk", "t", "write", "offset", "c1", "c2", "indexOutOfRange", "reader", "writeLength", "readFixed32End", "buf", "end", "Uint8ArrayReader", "buffer", "value", "readFloatLE", "readDoubleLE", "length", "start", "bytes", "read", "wireType", "bits", "LongBits", "i", "lo", "hi", "decodeUint8Array", "encodingLength", "createReader", "decodeMessage", "buf", "codec", "opts", "reader", "createReader", "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", "message", "encode", "decode", "stream", "createCodec", "CODEC_TYPES", "Record", "_codec", "message", "obj", "w", "opts", "reader", "length", "alloc", "end", "tag", "prefix", "encode", "encodeMessage", "decode", "buf", "decodeMessage", "stream", "streamMessage", "toRFC3339", "time", "year", "month", "day", "hour", "minute", "seconds", "milliseconds", "nanoseconds", "parseRFC3339", "rfc3339Matcher", "m", "date", "second", "millisecond", "Libp2pRecord", "_Libp2pRecord", "key", "value", "timeReceived", "Record", "toRFC3339", "raw", "rec", "obj", "receivedTime", "parseRFC3339", "EventTypes", "IPNSPublishMetadata", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "prefix", "encode", "encodeMessage", "decode", "buf", "decodeMessage", "stream", "streamMessage", "localStore", "datastore", "log", "routingKey", "marshalledRecord", "options", "key", "dhtRoutingKey", "existingBuf", "existingRecord", "Libp2pRecord", "equals", "err", "record", "CustomProgressEvent", "batch", "ipnsMetadataKey", "IPNSPublishMetadata", "buf", "value", "DHT_RECORD_PREFIX", "libp2pRecord", "routingKeyBase32", "fromString", "metadataKey", "metadata", "metadataBuf", "HeliaRouting", "routing", "routingKey", "marshaledRecord", "options", "err", "CustomProgressEvent", "helia", "LocalStoreRouting", "localStore", "routingKey", "marshaledRecord", "options", "record", "localStoreRouting", "IPNS", "components", "init", "localStore", "localStoreRouting", "helia", "IPNSPublisher", "IPNSRepublisher", "IPNSResolver", "component", "isLibp2p", "service", "isKadDHT", "key", "values", "records", "buf", "unmarshalIPNSRecord", "ipnsSelector", "value", "record", "ipnsValidator", "keyName", "options", "normalizeValue", "digest", "normalizeKey", "obj", "ipns", "components", "options", "IPNS", "ipnsResolver", "store", "localStore", "routers", "localStoreRouting", "helia", "IPNSResolver"]
3
+ "sources": ["../../../node_modules/timestamp-nano/dist/timestamp.min.js", "../src/index.ts", "../../../node_modules/multiformats/src/bases/base32.ts", "../../../node_modules/multiformats/src/bytes.ts", "../../../node_modules/multiformats/src/vendor/base-x.js", "../../../node_modules/multiformats/src/bases/base.ts", "../../../node_modules/multiformats/src/bases/base36.ts", "../../../node_modules/multiformats/src/bases/base58.ts", "../../../node_modules/multiformats/src/vendor/varint.js", "../../../node_modules/multiformats/src/varint.ts", "../../../node_modules/multiformats/src/hashes/digest.ts", "../../../node_modules/multiformats/src/cid.ts", "../src/constants.ts", "../src/errors.ts", "../src/selector.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/bases/base16.ts", "../../../node_modules/multiformats/src/bases/base2.ts", "../../../node_modules/multiformats/src/bases/base256emoji.ts", "../../../node_modules/multiformats/src/bases/base64.ts", "../../../node_modules/multiformats/src/bases/base8.ts", "../../../node_modules/multiformats/src/bases/identity.ts", "../../../node_modules/multiformats/src/codecs/json.ts", "../../../node_modules/multiformats/src/hashes/identity.ts", "../../../node_modules/multiformats/src/hashes/sha2-browser.ts", "../../../node_modules/multiformats/src/hashes/hasher.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", "../src/pb/ipns.ts", "../../../node_modules/uint8arrays/src/util/as-uint8array.ts", "../../../node_modules/uint8arrays/src/concat.ts", "../../../node_modules/uint8arrays/src/equals.ts", "../../../node_modules/@ipshipyard/crypto/src/index.ts", "../../../node_modules/@libp2p/interface/src/errors.ts", "../../../node_modules/main-event/src/index.ts", "../../../node_modules/cborg/lib/is.js", "../../../node_modules/cborg/lib/token.js", "../../../node_modules/cborg/lib/byte-utils.js", "../../../node_modules/cborg/lib/bl.js", "../../../node_modules/cborg/lib/common.js", "../../../node_modules/cborg/lib/0uint.js", "../../../node_modules/cborg/lib/1negint.js", "../../../node_modules/cborg/lib/2bytes.js", "../../../node_modules/cborg/lib/3string.js", "../../../node_modules/cborg/lib/4array.js", "../../../node_modules/cborg/lib/5map.js", "../../../node_modules/cborg/lib/6tag.js", "../../../node_modules/cborg/lib/7float.js", "../../../node_modules/cborg/lib/jump.js", "../../../node_modules/cborg/lib/encode.js", "../../../node_modules/cborg/lib/decode.js", "../../../node_modules/cborg/lib/tagged.js", "../../../node_modules/uint8arrays/src/to-string.ts", "../../../node_modules/interface-datastore/src/key.ts", "../src/utils.ts", "../src/validator.ts", "../src/ipns/resolver.ts", "../../../node_modules/progress-events/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/@libp2p/logger/src/index.ts", "../src/records.ts", "../src/ipns/publisher.ts", "../../../node_modules/p-defer/index.js", "../../../node_modules/it-pushable/src/fifo.ts", "../../../node_modules/it-pushable/src/index.ts", "../../../node_modules/p-timeout/index.js", "../../../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/race-signal/src/index.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/@libp2p/utils/src/repeating-task.ts", "../src/ipns/republisher.ts", "../../../node_modules/@libp2p/record/src/record.ts", "../../../node_modules/@libp2p/record/src/utils.ts", "../../../node_modules/@libp2p/record/src/index.ts", "../../../node_modules/@libp2p/kad-dht/src/index.ts", "../src/pb/metadata.ts", "../src/local-store.ts", "../src/routing/helia.ts", "../src/routing/local-store.ts", "../src/ipns.ts"],
4
+ "sourcesContent": ["var Timestamp=function(){\"undefined\"!=typeof module&&(module.exports=d);var l=86400,s=3200,T=146097*s/400,e=l*T,f=1e3*e,c=864e13,g=4294967296,h=1e6,u=\"000000000\",m=Math.trunc||function(n){var t=n-n%1;return 0==t&&(n<0||0===n&&1/n!=1/0)?-0:t},n=d.prototype,o=(d.fromDate=function(n){return new d(+n)},d.fromInt64BE=r(0,1,2,3,0,4),d.fromInt64LE=r(3,2,1,0,4,0),d.fromString=function(n){var e,r=new d,n=(n+=\"\").replace(/^\\s*[+\\-]?\\d+/,function(n){var n=+n,t=1970+(n-1970)%400;return r.year=n-t,t}).replace(/(?:Z|([+\\-]\\d{2}):?(\\d{2}))$/,function(n,t,r){return t<0&&(r*=-1),e=6e4*(60*+t+ +r),\"\"}).replace(/\\.\\d+$/,function(n){return r.nano=+(n+u).substr(1,9),\"\"}).split(/\\D+/);1<n.length?n[1]--:n[1]=0;if(r.time=e=Date.UTC.apply(Date,n)-(e||0),isNaN(e))throw new TypeError(\"Invalid Date\");return p(r)},d.fromTimeT=function(n){return y(n,0)},n.year=0,n.time=0,n.nano=0,n.addNano=function(n){return this.nano+=+n||0,this},n.getNano=function(){var n=p(this);return(n.time%1e3*h+ +n.nano+1e9)%1e9},n.getTimeT=function(){var n=p(this),t=Math.floor(n.time/1e3),n=n.year;n&&(t+=n*T*l/s);return t},n.getYear=function(){return this.toDate().getUTCFullYear()+this.year},n.toDate=function(){return M(p(this).time)},n.toJSON=function(){return this.toString().replace(/0{1,6}Z$/,\"Z\")},n.toString=function(n){var t=this,r=t.toDate(),u={H:function(){return C(r.getUTCHours())},L:function(){return D(r.getUTCMilliseconds(),3)},M:function(){return C(r.getUTCMinutes())},N:function(){return D(t.getNano(),9)},S:function(){return C(r.getUTCSeconds())},Y:function(){var n=t.getYear();return 999999<n?\"+\"+n:9999<n?\"+\"+D(n,6):0<=n?D(n,4):-999999<=n?\"-\"+D(-n,6):n},a:function(){return a[r.getUTCDay()]},b:function(){return i[r.getUTCMonth()]},d:function(){return C(r.getUTCDate())},e:function(){return function(n){return(9<n?\"\":\" \")+(0|n)}(r.getUTCDate())},m:function(){return C(r.getUTCMonth()+1)}};return function e(n){return n.replace(/%./g,function(n){var t=n[1],r=v[t],t=u[t];return r?e(r):t?t():n})}(n||o)},n.writeInt64BE=t(0,1,2,3,0,4),n.writeInt64LE=t(3,2,1,0,4,0),\"%Y-%m-%dT%H:%M:%S.%NZ\"),i=[\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"],a=[\"Sun\",\"Mon\",\"Tue\",\"Wed\",\"Thu\",\"Fri\",\"Sat\"],v={\"%\":\"%\",F:\"%Y-%m-%d\",n:\"\\n\",R:\"%H:%M\",T:\"%H:%M:%S\",t:\"\\t\",X:\"%T\",Z:\"GMT\",z:\"+0000\"};return d;function d(n,t,r){var e=this;if(!(e instanceof d))return new d(n,t,r);e.time=+n||0,e.nano=+t||0,e.year=+r||0,p(e)}function p(n){var t,r,e,u=n.year,o=n.time,i=n.nano,a=((i<0||h<=i)&&(i-=(r=Math.floor(i/h))*h,o+=r,r=1),u%s);return(o<-c||c<o||a)&&((t=m(o/f))&&(u+=t*s,o-=t*f),(e=M(o)).setUTCFullYear(a+e.getUTCFullYear()),e=(o=+e)+(t=m((u-=a)/s))*f,t&&-c<=e&&e<=c&&(u-=t*s,o=e),r=1),r&&(n.year=u,n.time=o,n.nano=i),n}function M(n){var t=new Date(0);return t.setTime(n),t}function y(n,t){n=+n||0;var r=m((t=(t|0)*g)/e)+m(n/e),t=t%e+n%e,n=m(t/e);return n&&(r+=n,t-=n*e),new d(1e3*t,0,r*s)}function t(e,u,o,i,a,f){return function(n,t){var r=p(this);n=n||new Array(8);w(n,t|=0);var e=Math.floor(r.time/1e3),r=r.year*(T*l/s),u=m(r/g)+m(e/g),r=r%g+e%g,e=Math.floor(r/g);e&&(u+=e,r-=e*g);return c(n,t+a,u),c(n,t+f,r),n};function c(n,t,r){n[t+e]=r>>24&255,n[t+u]=r>>16&255,n[t+o]=r>>8&255,n[t+i]=255&r}}function r(r,e,u,o,i,a){return function(n,t){w(n,t|=0);var r=f(n,t+i);return y(f(n,t+a),r)};function f(n,t){return 16777216*n[t+r]+(n[t+e]<<16|n[t+u]<<8|n[t+o])}}function w(n,t){n=n&&n.length;if(null==n)throw new TypeError(\"Invalid Buffer\");if(n<t+8)throw new RangeError(\"Out of range\")}function C(n){return(9<n?\"\":\"0\")+(0|n)}function D(n,t){return(u+(0|n)).substr(-t)}}();", "/**\n * @packageDocumentation\n *\n * [IPNS](https://docs.ipfs.tech/concepts/ipns/) operations using a Helia node\n *\n * @example Getting started\n *\n * With {@link IPNSRouting} routers:\n *\n * ```TypeScript\n * import { createHelia } from 'helia'\n * import { ipns } from '@helia/ipns'\n * import { unixfs } from '@helia/unixfs'\n *\n * const helia = await createHelia()\n * const name = ipns(helia)\n *\n * // store some data to publish\n * const fs = unixfs(helia)\n * const cid = await fs.addBytes(Uint8Array.from([0, 1, 2, 3, 4]))\n *\n * // publish the name\n * const { publicKey } = await name.publish('key-1', cid)\n *\n * // resolve the name\n * for await (const result of name.resolve(publicKey)) {\n * console.info(result.record.value) // /ipfs/QmFoo\n * }\n * ```\n *\n * @example Publishing a recursive record\n *\n * A recursive record is a one that points to another record rather than to a\n * value.\n *\n * ```TypeScript\n * import { createHelia } from 'helia'\n * import { ipns } from '@helia/ipns'\n * import { unixfs } from '@helia/unixfs'\n * import { generateKeyPair } from '@libp2p/crypto/keys'\n *\n * const helia = await createHelia()\n * const name = ipns(helia)\n *\n * // store some data to publish\n * const fs = unixfs(helia)\n * const cid = await fs.addBytes(Uint8Array.from([0, 1, 2, 3, 4]))\n *\n * // publish the name\n * const { publicKey } = await name.publish('key-1', cid)\n *\n * // publish the recursive name\n * const { publicKey: recursivePublicKey } = await name.publish('key-2', publicKey)\n *\n * // resolve the name recursively - it resolves until a CID is found\n * for await (const result of name.resolve(recursivePublicKey)) {\n * console.info(result.record.value) // /ipfs/QmFoo../foo.txt\n * }\n * ```\n *\n * @example Publishing a record with a path\n *\n * It is possible to publish CIDs with an associated path.\n *\n * ```TypeScript\n * import { createHelia } from 'helia'\n * import { ipns } from '@helia/ipns'\n * import { unixfs } from '@helia/unixfs'\n * import { generateKeyPair } from '@libp2p/crypto/keys'\n *\n * const helia = await createHelia()\n * const name = ipns(helia)\n *\n * // store some data to publish\n * const fs = unixfs(helia)\n * const fileCid = await fs.addBytes(Uint8Array.from([0, 1, 2, 3, 4]))\n *\n * // store the file in a directory\n * const dirCid = await fs.addDirectory()\n * const finalDirCid = await fs.cp(fileCid, dirCid, '/foo.txt')\n *\n * // publish the name\n * const { publicKey } = await name.publish('key-1', `/ipfs/${finalDirCid}/foo.txt`)\n *\n * // resolve the name\n * for await (const result of name.resolve(publicKey)) {\n * console.info(result.record.value) // /ipfs/QmFoo../foo.txt\n * }\n * ```\n *\n * @example Using custom PubSub router\n *\n * Additional IPNS routers can be configured - these enable alternative means to\n * publish and resolve IPNS names.\n *\n * One example is the PubSub router - this requires an instance of Helia with\n * libp2p PubSub configured.\n *\n * It works by subscribing to a pubsub topic for each IPNS name that we try to\n * resolve. Updated IPNS records are shared on these topics so an update must\n * occur before the name is resolvable.\n *\n * This router is only suitable for networks where IPNS updates are frequent\n * and multiple peers are listening on the topic(s), otherwise update messages\n * may fail to be published with \"Insufficient peers\" errors.\n *\n * ```TypeScript\n * import { ipns } from '@helia/ipns'\n * import { pubsub } from '@helia/ipns/routing'\n * import { withLibp2p, libp2pDefaults } from '@helia/libp2p'\n * import { unixfs } from '@helia/unixfs'\n * import { generateKeyPair } from '@libp2p/crypto/keys'\n * import { floodsub } from '@libp2p/floodsub'\n * import { createHelia } from 'helia'\n * import type { Helia } from '@helia/interface'\n * import type { PubSub } from '@helia/ipns/routing'\n * import type { DefaultLibp2pServices } from '@helia/libp2p'\n * import type { FloodSub } from '@libp2p/floodsub'\n * import type { Libp2p } from '@libp2p/interface'\n *\n * const libp2pOptions = libp2pDefaults() as any\n * libp2pOptions.services.pubsub = floodsub()\n *\n * const helia = await withLibp2p<Helia, { pubsub: FloodSub }>(createHelia(), libp2pOptions).start()\n *\n * const name = ipns(helia, {\n * routers: [\n * pubsub(helia)\n * ]\n * })\n *\n * // store some data to publish\n * const fs = unixfs(helia)\n * const cid = await fs.addBytes(Uint8Array.from([0, 1, 2, 3, 4]))\n *\n * // publish the name\n * const { publicKey } = await name.publish('key-1', cid)\n *\n * // resolve the name\n * for await (const result of name.resolve(publicKey)) {\n * console.info(result.record.value)\n * }\n * ```\n */\n\nimport { CID } from 'multiformats/cid'\nimport { IPNSResolver as IPNSResolverClass } from './ipns/resolver.ts'\nimport { IPNS as IPNSClass } from './ipns.ts'\nimport { localStore } from './local-store.ts'\nimport { helia } from './routing/index.ts'\nimport { localStoreRouting } from './routing/local-store.ts'\nimport type { IPNSResolverComponents } from './ipns/resolver.ts'\nimport type { IPNSRecord } from './records.ts'\nimport type { IPNSRouting, IPNSRoutingProgressEvents } from './routing/index.ts'\nimport type { Routing, HeliaEvents, Keychain, PublicKey } from '@helia/interface'\nimport type { ComponentLogger, TypedEventEmitter } from '@libp2p/interface'\nimport type { AbortOptions } from 'abort-error'\nimport type { Datastore } from 'interface-datastore'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\nimport type { ProgressEvent, ProgressOptions } from 'progress-events'\n\nexport type PublishProgressEvents =\n ProgressEvent<'ipns:publish:start'> |\n ProgressEvent<'ipns:publish:success', IPNSRecord> |\n ProgressEvent<'ipns:publish:error', Error>\n\nexport type ResolveProgressEvents =\n ProgressEvent<'ipns:resolve:start', unknown> |\n ProgressEvent<'ipns:resolve:success', IPNSRecord> |\n ProgressEvent<'ipns:resolve:error', Error>\n\nexport type DatastoreProgressEvents =\n ProgressEvent<'ipns:routing:datastore:put'> |\n ProgressEvent<'ipns:routing:datastore:get'> |\n ProgressEvent<'ipns:routing:datastore:list'> |\n ProgressEvent<'ipns:routing:datastore:error', Error>\n\nexport interface PublishOptions extends AbortOptions, ProgressOptions<PublishProgressEvents | IPNSRoutingProgressEvents> {\n /**\n * Time duration of the signature validity in ms\n *\n * @default 172_800_000\n */\n lifetime?: number\n\n /**\n * Only publish to a local datastore\n *\n * @default false\n */\n offline?: boolean\n\n /**\n * By default a IPNS V1 and a V2 signature is added to every record. Pass\n * false here to only add a V2 signature.\n *\n * @default true\n */\n v1Compatible?: boolean\n\n /**\n * The TTL of the record in ms\n *\n * @default 300_000\n */\n ttl?: number\n}\n\nexport interface IPNSRecordMetadata {\n keyName: string\n lifetime: number\n}\n\nexport interface ResolveOptions extends AbortOptions, ProgressOptions<ResolveProgressEvents | IPNSRoutingProgressEvents> {\n /**\n * Do not query the network for the IPNS record\n *\n * @default false\n */\n offline?: boolean\n\n /**\n * Do not use cached IPNS Record entries\n *\n * @default false\n */\n nocache?: boolean\n}\n\nexport interface ResolveResult {\n /**\n * The resolved record\n */\n record: IPNSRecord\n}\n\nexport interface PublishResult {\n /**\n * The published record\n */\n record: IPNSRecord\n\n /**\n * The IPNS name that can be used to resolve this record\n */\n name: string\n\n /**\n * The public key that was used to sign and publish the record\n */\n publicKey: PublicKey\n}\n\nexport interface IPNSResolver {\n /**\n * Accepts a libp2p public key, a CID with the libp2p-key codec and either the\n * identity hash (for Ed25519 and secp256k1 public keys) or a SHA256 hash (for\n * RSA public keys), or the multihash of a libp2p-key encoded CID, or a\n * Ed25519, secp256k1 or RSA PeerId and recursively resolves the IPNS record\n * corresponding to that key until a value is found.\n */\n resolve(key: CID<unknown, 0x72> | MultihashDigest, options?: ResolveOptions): AsyncGenerator<ResolveResult>\n}\n\nexport interface IPNS {\n /**\n * Configured routing subsystems used to publish/resolve IPNS names\n */\n routers: IPNSRouting[]\n\n /**\n * Creates and publishes an IPNS record that will resolve the passed value\n * signed by a key stored in the libp2p keychain under the passed key name.\n *\n * If the key does not exist, a new Ed25519 key will be created. To use a\n * different key types, ensure the key is created and stored in the keychain\n * before invoking this method.\n *\n * It is possible to create a recursive IPNS record by passing:\n *\n * - A CID with the libp2p-key codec\n * - A Multihash\n * - A string IPNS key (e.g. `/ipns/Qmfoo`)\n *\n * @example\n *\n * ```TypeScript\n * import { createHelia } from 'helia'\n * import { ipns } from '@helia/ipns'\n *\n * const helia = await createHelia()\n * const name = ipns(helia)\n *\n * const result = await name.publish('my-key-name', cid, {\n * signal: AbortSignal.timeout(5_000)\n * })\n *\n * console.info(result) // { answer: ... }\n * ```\n */\n publish(keyName: string, value: CID | PublicKey | MultihashDigest | string, options?: PublishOptions): Promise<PublishResult>\n\n /**\n * Accepts a multihash of a public key, a libp2p-key CID containing the\n * multihash of a public key, or an IPNS name in it's string representation\n * and recursively resolves IPNS records until a non-recursive record is found\n * (e.g. the value can be parsed as a string that does not start with\n * `/ipns/`).\n */\n resolve(name: CID<unknown, 0x72> | PublicKey | MultihashDigest | string, options?: ResolveOptions): AsyncGenerator<ResolveResult>\n\n /**\n * Stop republishing of an IPNS record\n *\n * This will delete the last signed IPNS record from the datastore.\n *\n * Note that the record may still be resolved by other peers until it expires\n * or is otherwise no longer valid.\n */\n unpublish(keyName: string, options?: AbortOptions): Promise<void>\n}\n\nexport type { IPNSRouting } from './routing/index.ts'\nexport type { IPNSRecord } from './records.ts'\n\nexport interface IPNSComponents {\n datastore: Datastore\n routing: Routing\n logger: ComponentLogger\n keychain: Keychain\n events: TypedEventEmitter<HeliaEvents> // Helia event bus\n}\n\nexport interface IPNSOptions {\n /**\n * Different routing systems for IPNS publishing/resolving\n */\n routers?: IPNSRouting[]\n\n /**\n * How often to check if published records have expired and need republishing\n * in ms\n *\n * @default 3_600_000\n */\n republishInterval?: number\n\n /**\n * How many IPNS records to republish at once\n *\n * @default 5\n */\n republishConcurrency?: number\n}\n\nexport interface IPNSResolverOptions {\n /**\n * Different routing systems for IPNS publishing/resolving\n */\n routers?: IPNSRouting[]\n}\n\nexport function ipns (components: IPNSComponents, options: IPNSOptions = {}): IPNS {\n return new IPNSClass(components, options)\n}\n\nexport function ipnsResolver (components: IPNSResolverComponents, options: IPNSResolverOptions = {}): IPNSResolver {\n const store = localStore(components.datastore, components.logger.forComponent('helia:ipns:local-store'))\n const routers = [\n localStoreRouting(store),\n helia(components.routing),\n ...(options.routers ?? [])\n ]\n\n return new IPNSResolverClass(components, {\n routers,\n localStore: store\n })\n}\n\nexport type { IPNSRoutingProgressEvents }\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", "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 { 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", "/* 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 { 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", "const MINUTE = 60 * 1000\nconst HOUR = 60 * MINUTE\n\nexport const DEFAULT_LIFETIME_MS = 48 * HOUR\n\n/**\n * The default DHT record expiry\n */\nexport const DHT_EXPIRY_MS = 48 * HOUR\n\n/**\n * How often to run the republish loop\n */\nexport const DEFAULT_REPUBLISH_INTERVAL_MS = HOUR\n\n/**\n * Republish IPNS records when the expiry of our provider records is within this\n * threshold\n */\nexport const REPUBLISH_THRESHOLD = 24 * HOUR\n\nexport const DEFAULT_TTL_NS = BigInt(MINUTE) * 5_000_000n // 5 minutes\n\nexport const DEFAULT_REPUBLISH_CONCURRENCY = 5\n", "export class RecordsFailedValidationError extends Error {\n static name = 'RecordsFailedValidationError'\n name = 'RecordsFailedValidationError'\n}\n\nexport class UnsupportedMultibasePrefixError extends Error {\n static name = 'UnsupportedMultibasePrefixError'\n name = 'UnsupportedMultibasePrefixError'\n}\n\nexport class UnsupportedMultihashCodecError extends Error {\n static name = 'UnsupportedMultihashCodecError'\n name = 'UnsupportedMultihashCodecError'\n}\n\nexport class InvalidValueError extends Error {\n static name = 'InvalidValueError'\n name = 'InvalidValueError'\n}\n\nexport class InvalidTopicError extends Error {\n static name = 'InvalidTopicError'\n name = 'InvalidTopicError'\n}\n\nexport class RecordNotFoundError extends Error {\n static name = 'RecordNotFoundError'\n name = 'RecordNotFoundError'\n}\n\nexport class SignatureCreationError extends Error {\n static name = 'SignatureCreationError'\n name = 'SignatureCreationError'\n}\n\nexport class SignatureVerificationError extends Error {\n static name = 'SignatureVerificationError'\n name = 'SignatureVerificationError'\n}\n\nexport class RecordExpiredError extends Error {\n static name = 'RecordExpiredError'\n name = 'RecordExpiredError'\n}\n\nexport class UnsupportedValidityError extends Error {\n static name = 'UnsupportedValidityError'\n name = 'UnsupportedValidityError'\n}\n\nexport class RecordTooLargeError extends Error {\n static name = 'RecordTooLargeError'\n name = 'RecordTooLargeError'\n}\n\nexport class InvalidRecordDataError extends Error {\n static name = 'InvalidRecordDataError'\n name = 'InvalidRecordDataError'\n}\n\nexport class InvalidEmbeddedPublicKeyError extends Error {\n static name = 'InvalidEmbeddedPublicKeyError'\n name = 'InvalidEmbeddedPublicKeyError'\n}\n", "import NanoDate from 'timestamp-nano'\nimport { IpnsEntry } from './pb/ipns.ts'\nimport type { IPNSRecord } from './records.ts'\n\n/**\n * Selects the latest valid IPNS record from an array of marshalled IPNS records.\n *\n * Records are sorted by:\n * 1. Sequence number (higher takes precedence)\n * 2. Validity time for EOL records with same sequence number (longer lived record takes precedence)\n *\n * @param key - The routing key for the IPNS record\n * @param data - Array of marshalled IPNS records to select from\n * @returns The index of the most valid record from the input array\n */\nexport function ipnsSelector (key: Uint8Array, data: IPNSRecord[]): number {\n const entries = data.map((record, index) => ({\n record,\n index\n }))\n\n entries.sort((a, b) => {\n // Before we'd sort based on the signature version. Unmarshal now fails if\n // a record does not have SignatureV2, so that is no longer needed. V1-only\n // records haven't been issues in a long time.\n\n const aSeq = a.record.sequence\n const bSeq = b.record.sequence\n\n // choose later sequence number\n if (aSeq > bSeq) {\n return -1\n } else if (aSeq < bSeq) {\n return 1\n }\n\n if (a.record.validityType === IpnsEntry.ValidityType.EOL && b.record.validityType === IpnsEntry.ValidityType.EOL) {\n // choose longer lived record if sequence numbers the same\n const recordAValidityDate = NanoDate.fromString(a.record.validity).toDate()\n const recordBValidityDate = NanoDate.fromString(b.record.validity).toDate()\n\n if (recordAValidityDate.getTime() > recordBValidityDate.getTime()) {\n return -1\n }\n\n if (recordAValidityDate.getTime() < recordBValidityDate.getTime()) {\n return 1\n }\n }\n\n return 0\n })\n\n return entries[0].index\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", "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 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 * 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", "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 * 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 interface IpnsEntry {\n value?: Uint8Array\n signatureV1?: Uint8Array\n validityType?: IpnsEntry.ValidityType\n validity?: Uint8Array\n sequence?: bigint\n ttl?: bigint\n publicKey?: Uint8Array\n signatureV2?: Uint8Array\n data?: Uint8Array\n}\n\nexport namespace IpnsEntry {\n export enum ValidityType {\n EOL = 'EOL'\n }\n\n enum __ValidityTypeValues {\n EOL = 0\n }\n\n export namespace ValidityType {\n export const codec = (): Codec<ValidityType> => {\n return enumeration<ValidityType>(__ValidityTypeValues)\n }\n }\n\n let _codec: Codec<IpnsEntry>\n\n export const codec = (): Codec<IpnsEntry> => {\n if (_codec == null) {\n _codec = message<IpnsEntry>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.value != null) {\n w.uint32(10)\n w.bytes(obj.value)\n }\n\n if (obj.signatureV1 != null) {\n w.uint32(18)\n w.bytes(obj.signatureV1)\n }\n\n if (obj.validityType != null) {\n w.uint32(24)\n IpnsEntry.ValidityType.codec().encode(obj.validityType, w)\n }\n\n if (obj.validity != null) {\n w.uint32(34)\n w.bytes(obj.validity)\n }\n\n if (obj.sequence != null) {\n w.uint32(40)\n w.uint64(obj.sequence)\n }\n\n if (obj.ttl != null) {\n w.uint32(48)\n w.uint64(obj.ttl)\n }\n\n if (obj.publicKey != null) {\n w.uint32(58)\n w.bytes(obj.publicKey)\n }\n\n if (obj.signatureV2 != null) {\n w.uint32(66)\n w.bytes(obj.signatureV2)\n }\n\n if (obj.data != null) {\n w.uint32(74)\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.value = reader.bytes()\n break\n }\n case 2: {\n obj.signatureV1 = reader.bytes()\n break\n }\n case 3: {\n obj.validityType = IpnsEntry.ValidityType.codec().decode(reader)\n break\n }\n case 4: {\n obj.validity = reader.bytes()\n break\n }\n case 5: {\n obj.sequence = reader.uint64()\n break\n }\n case 6: {\n obj.ttl = reader.uint64()\n break\n }\n case 7: {\n obj.publicKey = reader.bytes()\n break\n }\n case 8: {\n obj.signatureV2 = reader.bytes()\n break\n }\n case 9: {\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}.value`,\n value: reader.bytes()\n }\n break\n }\n case 2: {\n yield {\n field: `${prefix}.signatureV1`,\n value: reader.bytes()\n }\n break\n }\n case 3: {\n yield {\n field: `${prefix}.validityType`,\n value: IpnsEntry.ValidityType.codec().decode(reader)\n }\n break\n }\n case 4: {\n yield {\n field: `${prefix}.validity`,\n value: reader.bytes()\n }\n break\n }\n case 5: {\n yield {\n field: `${prefix}.sequence`,\n value: reader.uint64()\n }\n break\n }\n case 6: {\n yield {\n field: `${prefix}.ttl`,\n value: reader.uint64()\n }\n break\n }\n case 7: {\n yield {\n field: `${prefix}.publicKey`,\n value: reader.bytes()\n }\n break\n }\n case 8: {\n yield {\n field: `${prefix}.signatureV2`,\n value: reader.bytes()\n }\n break\n }\n case 9: {\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 IpnsEntryValueFieldEvent {\n field: '$.value'\n value: Uint8Array\n }\n\n export interface IpnsEntrySignatureV1FieldEvent {\n field: '$.signatureV1'\n value: Uint8Array\n }\n\n export interface IpnsEntryValidityTypeFieldEvent {\n field: '$.validityType'\n value: IpnsEntry.ValidityType\n }\n\n export interface IpnsEntryValidityFieldEvent {\n field: '$.validity'\n value: Uint8Array\n }\n\n export interface IpnsEntrySequenceFieldEvent {\n field: '$.sequence'\n value: bigint\n }\n\n export interface IpnsEntryTtlFieldEvent {\n field: '$.ttl'\n value: bigint\n }\n\n export interface IpnsEntryPublicKeyFieldEvent {\n field: '$.publicKey'\n value: Uint8Array\n }\n\n export interface IpnsEntrySignatureV2FieldEvent {\n field: '$.signatureV2'\n value: Uint8Array\n }\n\n export interface IpnsEntryDataFieldEvent {\n field: '$.data'\n value: Uint8Array\n }\n\n export function encode (obj: Partial<IpnsEntry>): Uint8Array<ArrayBuffer> {\n return encodeMessage(obj, IpnsEntry.codec())\n }\n\n export function decode (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<IpnsEntry>): IpnsEntry {\n return decodeMessage(buf, IpnsEntry.codec(), opts)\n }\n\n export function stream (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<IpnsEntry>): Generator<IpnsEntryValueFieldEvent | IpnsEntrySignatureV1FieldEvent | IpnsEntryValidityTypeFieldEvent | IpnsEntryValidityFieldEvent | IpnsEntrySequenceFieldEvent | IpnsEntryTtlFieldEvent | IpnsEntryPublicKeyFieldEvent | IpnsEntrySignatureV2FieldEvent | IpnsEntryDataFieldEvent> {\n return streamMessage(buf, IpnsEntry.codec(), opts)\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", "/**\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 * WebCrypto-based implementations of ECDSA, Ed25519, and RSA cryptography.\n */\nimport type { AbortOptions } from 'abort-error'\nimport type { CID, MultihashDigest } from 'multiformats/cid'\n\nexport { ecdsaCrypto } from './ecdsa.ts'\nexport { ed25519Crypto } from './ed25519.ts'\nexport { rsaCrypto } from './rsa.ts'\n\nexport interface PublicKey {\n /**\n * The type of the crypto implementation, e.g. `Ed15519`\n */\n readonly type: string\n\n /**\n * The code that is used as the `Type` field in the protobuf representation of\n * the public/private keys\n */\n readonly code: number\n\n /**\n * Return a MultihashDigest that represents this key\n */\n toMultihash (): MultihashDigest\n\n /**\n * Return the libp2p-key CID that represents this key\n */\n toCID (): CID<unknown, 0x72, number, 1>\n\n /**\n * Return this key encoded as a protobuf PublicKey message\n */\n toProtobuf (): Uint8Array<ArrayBuffer>\n\n /**\n * Return this key as a RFC 7517 Json Web Key\n */\n toJWK (): JsonWebKey\n\n /**\n * Verify the passed message against it's signature\n */\n verify(message: Uint8Array, signature: Uint8Array, options?: AbortOptions): boolean | Promise<boolean>\n}\n\nexport function isPublicKey (obj?: any): obj is PublicKey {\n if (obj == null) {\n return false\n }\n\n return typeof obj.type === 'string' && typeof obj.code === 'number' && typeof obj.verify === 'function'\n}\n\nexport interface PrivateKey {\n /**\n * The type of the crypto implementation, e.g. `Ed15519`\n */\n readonly type: string\n\n /**\n * The code that is used as the `Type` field in the protobuf representation of\n * the public/private keys\n */\n readonly code: number\n\n /**\n * The public key that corresponds to this private key\n */\n readonly publicKey: PublicKey\n\n /**\n * Return this key encoded as a protobuf PrivateKey message\n */\n toProtobuf (): Uint8Array<ArrayBuffer>\n\n /**\n * Return this key as a RFC 7517 Json Web Key\n */\n toJWK (): JsonWebKey\n\n /**\n * Sign the passed message and return a signature\n */\n sign(message: Uint8Array, options?: AbortOptions): Uint8Array<ArrayBuffer> | Promise<Uint8Array<ArrayBuffer>>\n}\n\nexport function isPrivateKey (obj?: any): obj is PrivateKey {\n if (obj == null) {\n return false\n }\n\n return typeof obj.type === 'string' && typeof obj.code === 'number' && typeof obj.sign === 'function' && isPublicKey(obj.publicKey)\n}\n\nexport interface Crypto {\n /**\n * The type of the crypto implementation, e.g. `Ed15519`\n */\n type: string\n\n /**\n * The code that is used as the `Type` field in the protobuf representation of\n * the public/private keys\n */\n code: number\n\n /**\n * Create a new private key\n */\n generatePrivateKey(options?: AbortOptions & Record<string, any>): Promise<PrivateKey>\n\n /**\n * Convert the passed bytes into a public key. The bytes come from the `.Data`\n * field of a `PublicKey` protobuf message.\n */\n publicKeyFromProtobuf(buf: Uint8Array, options?: AbortOptions): PublicKey | Promise<PublicKey>\n\n /**\n * Convert the passed bytes into a public key. The bytes come from the `.Data`\n * field of a `PublicKey` protobuf message.\n */\n privateKeyFromProtobuf(buf: Uint8Array, options?: AbortOptions): PrivateKey | Promise<PrivateKey>\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 * @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", "// 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", "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 { isPublicKey } from '@helia/interface'\nimport { InvalidParametersError } from '@libp2p/interface'\nimport * as cborg from 'cborg'\nimport { Key } from 'interface-datastore'\nimport { base36 } from 'multiformats/bases/base36'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { DHT_EXPIRY_MS, REPUBLISH_THRESHOLD } from './constants.ts'\nimport { InvalidEmbeddedPublicKeyError, InvalidRecordDataError, InvalidValueError, RecordTooLargeError, SignatureVerificationError, UnsupportedValidityError } from './errors.ts'\nimport { IpnsEntry } from './pb/ipns.ts'\nimport type { IPNSRecord, IPNSRecordV2, IPNSRecordData } from './records.ts'\nimport type { PublicKey, Keychain } from '@helia/interface'\nimport type { AbortOptions } from '@libp2p/interface'\nimport type { MultibaseDecoder } from 'multiformats/cid'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nexport const LIBP2P_KEY_CODEC = 0x72\nexport const IDENTITY_CODEC = 0x0\nexport const SHA2_256_CODEC = 0x12\n\n/**\n * Limit valid IPNS record sizes to 10kb\n */\nconst MAX_RECORD_SIZE = 1024 * 10\n\nconst IPNS_PREFIX = uint8ArrayFromString('/ipns/')\nexport const IPNS_STRING_PREFIX = '/ipns/'\n\nexport function isCodec <T extends number> (digest: MultihashDigest, codec: T): digest is MultihashDigest<T> {\n return digest.code === codec\n}\n\nexport const DHT_RECORD_PREFIX = '/dht/record/'\nexport const IPNS_METADATA_PREFIX = '/ipns/metadata/'\n\nexport function dhtRoutingKey (key: Uint8Array): Key {\n return new Key(DHT_RECORD_PREFIX + uint8ArrayToString(key, 'base32'), false)\n}\n\n/**\n * Calculate the datastore key for IPNS record metadata\n *\n * @param key - The DHT routing key for the IPNS record as defined in\n * https://specs.ipfs.tech/ipns/ipns-record/#routing-record\n *\n * @example\n *\n * ```ts\n * const key = multihashToIPNSRoutingKey(privKey.publicKey.toMultihash())\n * const metadataKey = ipnsMetadataKey(key)\n * ```\n * @returns The local storage key for IPNS record metadata\n */\nexport function ipnsMetadataKey (key: Uint8Array): Key {\n return new Key(IPNS_METADATA_PREFIX + uint8ArrayToString(key, 'base32'), false)\n}\n\nexport function shouldRepublish (ipnsRecord: IPNSRecord, created: Date): boolean {\n const now = Date.now()\n const dhtExpiry = created.getTime() + DHT_EXPIRY_MS\n const recordExpiry = new Date(ipnsRecord.validity).getTime()\n\n // If the DHT expiry is within the threshold, republish it\n if (dhtExpiry - now < REPUBLISH_THRESHOLD) {\n return true\n }\n\n // If the record expiry (based on validity/lifetime) is within the threshold, republish it\n if (recordExpiry - now < REPUBLISH_THRESHOLD) {\n return true\n }\n\n return false\n}\n\nfunction isCID (obj?: any): obj is CID {\n return obj?.asCID === obj\n}\n\nexport function isLibp2pCID (obj?: any): obj is CID<unknown, 0x72, 0x00 | 0x12, 1> {\n if (!isCID(obj)) {\n return false\n }\n\n if (obj.code !== LIBP2P_KEY_CODEC) {\n throw new InvalidParametersError(`CID codec ${obj.code} was not libp2p-key`)\n }\n\n if (obj.multihash.code !== IDENTITY_CODEC && obj.multihash.code !== SHA2_256_CODEC) {\n throw new InvalidParametersError(`Multihash algorithm codec ${obj.multihash.code} was not Identity or SHA256 hash`)\n }\n\n return true\n}\n\n/**\n * Utility for creating the record data for being signed\n */\nexport function ipnsRecordDataForV1Sig (value: string, validityType: IpnsEntry.ValidityType, validity: Uint8Array): Uint8Array {\n const validityTypeBuffer = uint8ArrayFromString(validityType)\n const valueBytes = uint8ArrayFromString(value)\n\n return uint8ArrayConcat([\n valueBytes,\n validity,\n validityTypeBuffer\n ], valueBytes.byteLength + validity.byteLength + validityTypeBuffer.byteLength)\n}\n\n/**\n * Utility for creating the record data for being signed\n */\nexport function ipnsRecordDataForV2Sig (data: Uint8Array): Uint8Array {\n const entryData = uint8ArrayFromString('ipns-signature:')\n\n return uint8ArrayConcat([entryData, data])\n}\n\nexport function marshalIPNSRecord (obj: IPNSRecord | IPNSRecordV2): Uint8Array {\n let publicKey: Uint8Array | undefined = obj.publicKey?.toProtobuf()\n\n // do not embed public keys whose multihash is an identity hash as these can\n // be derived from the routing key\n if (obj.publicKey?.toMultihash().code === 0x00) {\n publicKey = undefined\n }\n\n if ('signatureV1' in obj) {\n return IpnsEntry.encode({\n value: uint8ArrayFromString(obj.value),\n signatureV1: obj.signatureV1,\n validityType: obj.validityType,\n validity: uint8ArrayFromString(obj.validity),\n sequence: obj.sequence,\n ttl: obj.ttl,\n publicKey,\n signatureV2: obj.signatureV2,\n data: obj.data\n })\n } else {\n return IpnsEntry.encode({\n publicKey,\n signatureV2: obj.signatureV2,\n data: obj.data\n })\n }\n}\n\nfunction valueToString (value: Uint8Array): string {\n // handle legacy case where record value is raw CID bytes\n try {\n const cid = CID.decode(value)\n return `/ipfs/${cid}`\n } catch {\n // ignore error\n }\n\n return uint8ArrayToString(value)\n}\n\nexport async function unmarshalIPNSRecord (routingKey: Uint8Array, marshalledRecord: Uint8Array, keychain: Keychain, options?: AbortOptions): Promise<IPNSRecord> {\n if (marshalledRecord.byteLength > MAX_RECORD_SIZE) {\n throw new RecordTooLargeError('The record is too large')\n }\n\n const message = IpnsEntry.decode(marshalledRecord)\n\n // Check if we have the data field. If we don't, we fail. We've been producing\n // V1+V2 records for quite a while and we don't support V1-only records during\n // validation any more\n if (message.signatureV2 == null || message.data == null) {\n throw new SignatureVerificationError('Missing data or signatureV2')\n }\n\n const data = parseCborData(message.data)\n const validity = uint8ArrayToString(data.Validity)\n\n let publicKey: PublicKey | undefined\n\n // try to extract public key from routing key\n const routingMultihash = multihashFromIPNSRoutingKey(routingKey)\n\n // identity hash\n if (isCodec(routingMultihash, 0x0)) {\n publicKey = await keychain.loadPublicKeyFromProtobuf(routingMultihash.digest, options)\n }\n\n // otherwise try to load key from message\n if (publicKey == null && message.publicKey != null) {\n publicKey = await keychain.loadPublicKeyFromProtobuf(message.publicKey, options)\n }\n\n if (publicKey == null) {\n throw new InvalidEmbeddedPublicKeyError('Could not extract public key from IPNS record or routing key')\n }\n\n if (message.value != null && message.signatureV1 != null) {\n // V1+V2\n validateCborDataMatchesPbData(message)\n\n return {\n value: valueToString(data.Value),\n validityType: IpnsEntry.ValidityType.EOL,\n validity,\n sequence: data.Sequence,\n ttl: data.TTL,\n publicKey,\n signatureV1: message.signatureV1,\n signatureV2: message.signatureV2,\n data: message.data,\n bytes: marshalledRecord\n }\n } else if (message.signatureV2 != null) {\n // V2-only\n return {\n value: valueToString(data.Value),\n validityType: IpnsEntry.ValidityType.EOL,\n validity,\n sequence: data.Sequence,\n ttl: data.TTL,\n publicKey,\n signatureV2: message.signatureV2,\n data: message.data,\n bytes: marshalledRecord\n }\n } else {\n throw new Error('invalid record: does not include signatureV1 or signatureV2')\n }\n}\n\nexport function multihashToIPNSRoutingKey (digest: MultihashDigest): Uint8Array {\n return uint8ArrayConcat([\n IPNS_PREFIX,\n digest.bytes\n ])\n}\n\nexport function multihashFromIPNSRoutingKey (key: Uint8Array): MultihashDigest {\n return Digest.decode(key.slice(IPNS_PREFIX.length))\n}\n\nexport function createCborData (value: string, validityType: IpnsEntry.ValidityType, validity: Uint8Array, sequence: bigint, ttl: bigint): Uint8Array {\n let ValidityType\n\n if (validityType === IpnsEntry.ValidityType.EOL) {\n ValidityType = 0\n } else {\n throw new UnsupportedValidityError('The validity type is unsupported')\n }\n\n const data = {\n Value: uint8ArrayFromString(value),\n Validity: validity,\n ValidityType,\n Sequence: sequence,\n TTL: ttl\n }\n\n return cborg.encode(data)\n}\n\nexport function parseCborData (buf: Uint8Array): IPNSRecordData {\n const data = cborg.decode(buf)\n\n if (data.ValidityType === 0) {\n data.ValidityType = IpnsEntry.ValidityType.EOL\n } else {\n throw new UnsupportedValidityError('The validity type is unsupported')\n }\n\n if (Number.isInteger(data.Sequence)) {\n // sequence must be a BigInt, but DAG-CBOR doesn't preserve this for Numbers within the safe-integer range\n data.Sequence = BigInt(data.Sequence)\n }\n\n if (Number.isInteger(data.TTL)) {\n // ttl must be a BigInt, but DAG-CBOR doesn't preserve this for Numbers within the safe-integer range\n data.TTL = BigInt(data.TTL)\n }\n\n return data\n}\n\n/**\n * Normalizes the given record value. It ensures it is a PeerID, a CID or a\n * string starting with '/'. PeerIDs become `/ipns/${cidV1Libp2pKey}`,\n * CIDs become `/ipfs/${cidAsV1}`.\n */\nexport function normalizeValue (value?: PublicKey | CID | MultihashDigest | string): string {\n if (value != null) {\n if (isPublicKey(value)) {\n return `/ipns/${value.toCID().toV1().toString(base36)}`\n }\n\n const cid = asCID(value)\n\n // if we have a CID, turn it into an ipfs path\n if (cid != null) {\n // PeerID encoded as a CID\n if (cid.code === LIBP2P_KEY_CODEC) {\n return `/ipns/${cid.toV1().toString(base36)}`\n }\n\n return `/ipfs/${cid.toV1()}`\n }\n\n if (hasBytes(value)) {\n return `/ipns/${base36.encode(value.bytes)}`\n }\n\n // if we have a path, check it is a valid path\n const string = value.toString().trim()\n\n if (string.startsWith('/ipfs/')) {\n const [, name, ...rest] = string.split('/')\n .filter(component => component.trim() !== '')\n\n return `/ipfs/${CID.parse(name).toV1()}${rest.length > 0 ? `/${rest.join('/')}` : ''}`\n }\n\n if (string.startsWith('/') && string.length > 1) {\n return string\n }\n }\n\n throw new InvalidValueError('Value must be a valid content path starting with /')\n}\n\nfunction isMultihashDigest (obj: any): obj is MultihashDigest {\n return typeof obj.code === 'number' && obj.digest instanceof Uint8Array && typeof obj.size === 'number' && obj.bytes instanceof Uint8Array\n}\n\nexport function normalizeKey (key?: PublicKey | CID<unknown, 0x72> | MultihashDigest | string): { digest: MultihashDigest, path: string } {\n if (key != null) {\n if (isPublicKey(key)) {\n return {\n digest: key.toMultihash(),\n path: '/'\n }\n }\n\n const cid = asCID(key)\n\n // if we have a CID, turn it into an ipfs path\n if (cid != null) {\n // PeerID encoded as a CID\n if (cid.code !== LIBP2P_KEY_CODEC) {\n throw new InvalidValueError('CIDs must have the `libp2p-key` codec')\n }\n\n return {\n digest: cid.multihash,\n path: '/'\n }\n }\n\n if (isMultihashDigest(key)) {\n return {\n digest: key,\n path: '/'\n }\n }\n\n key = key.toString()\n\n if (key.startsWith('/ipns/')) {\n let [,, name, ...rest] = key.split('/')\n let codec: MultibaseDecoder<any> = base36\n\n // base58btc encoded public key hash or protobuf in identity hash\n if (name.startsWith('1') || name.startsWith('Q')) {\n name = `z${name}`\n codec = base58btc\n }\n\n const buf = codec.decode(name)\n let digest: MultihashDigest\n\n try {\n digest = CID.decode(buf).multihash\n } catch {\n digest = Digest.decode(buf)\n }\n\n return {\n digest,\n path: `/${rest.join('/')}`\n }\n }\n }\n\n throw new InvalidValueError('Value must be a valid IPNS path starting with /')\n}\n\nfunction validateCborDataMatchesPbData (entry: IpnsEntry): void {\n if (entry.data == null) {\n throw new InvalidRecordDataError('Record data is missing')\n }\n\n const data = parseCborData(entry.data)\n\n if (!uint8ArrayEquals(data.Value, entry.value ?? new Uint8Array(0))) {\n throw new SignatureVerificationError('Field \"value\" did not match between protobuf and CBOR')\n }\n\n if (!uint8ArrayEquals(data.Validity, entry.validity ?? new Uint8Array(0))) {\n throw new SignatureVerificationError('Field \"validity\" did not match between protobuf and CBOR')\n }\n\n if (data.ValidityType !== entry.validityType) {\n throw new SignatureVerificationError('Field \"validityType\" did not match between protobuf and CBOR')\n }\n\n if (data.Sequence !== entry.sequence) {\n throw new SignatureVerificationError('Field \"sequence\" did not match between protobuf and CBOR')\n }\n\n if (data.TTL !== entry.ttl) {\n throw new SignatureVerificationError('Field \"ttl\" did not match between protobuf and CBOR')\n }\n}\n\nfunction hasBytes (obj?: any): obj is { bytes: Uint8Array } {\n return obj.bytes instanceof Uint8Array\n}\n\nfunction hasToCID (obj?: any): obj is { toCID(): CID } {\n return typeof obj?.toCID === 'function'\n}\n\nfunction asCID (obj?: any): CID | null {\n if (hasToCID(obj)) {\n return obj.toCID()\n }\n\n // try parsing as a CID string\n try {\n return CID.parse(obj)\n } catch {\n // fall through\n }\n\n return CID.asCID(obj)\n}\n", "import NanoDate from 'timestamp-nano'\nimport { InvalidEmbeddedPublicKeyError, RecordExpiredError, SignatureVerificationError, UnsupportedValidityError } from './errors.ts'\nimport { IpnsEntry } from './pb/ipns.ts'\nimport { ipnsRecordDataForV2Sig } from './utils.ts'\nimport type { IPNSRecord } from './index.ts'\nimport type { AbortOptions } from '@libp2p/interface'\n\n/**\n * Validate the given IPNS record against the given routing key.\n *\n * @see https://specs.ipfs.tech/ipns/ipns-record/#routing-record for the binary\n * format of the routing key\n */\nexport async function ipnsValidator (record: IPNSRecord, options?: AbortOptions): Promise<void> {\n if (record.publicKey == null) {\n throw new InvalidEmbeddedPublicKeyError('The record had no public key associated with it')\n }\n\n // Validate Signature V2\n let isValid\n\n try {\n const dataForSignature = ipnsRecordDataForV2Sig(record.data)\n isValid = await record.publicKey.verify(dataForSignature, record.signatureV2, options)\n } catch {\n isValid = false\n }\n\n if (!isValid) {\n throw new SignatureVerificationError('Record signature verification failed')\n }\n\n // Validate according to the validity type\n if (record.validityType === IpnsEntry.ValidityType.EOL) {\n if (NanoDate.fromString(record.validity).toDate().getTime() < Date.now()) {\n throw new RecordExpiredError('record has expired')\n }\n } else if (record.validityType != null) {\n throw new UnsupportedValidityError('The validity type is unsupported')\n }\n}\n\n/**\n * Returns the number of milliseconds until the record expires.\n * If the record is already expired, returns 0.\n *\n * @param record - The IPNS record to validate.\n * @returns The number of milliseconds until the record expires, or 0 if the record is already expired.\n */\nexport function validFor (record: IPNSRecord): number {\n if (record.validityType !== IpnsEntry.ValidityType.EOL) {\n throw new UnsupportedValidityError()\n }\n\n if (record.validity == null) {\n throw new UnsupportedValidityError()\n }\n\n const validUntil = NanoDate.fromString(record.validity).toDate().getTime()\n const now = Date.now()\n\n if (validUntil < now) {\n return 0\n }\n\n return validUntil - now\n}\n", "import { DEFAULT_TTL_NS } from '../constants.ts'\nimport { RecordNotFoundError, RecordsFailedValidationError } from '../errors.ts'\nimport { ipnsSelector } from '../selector.ts'\nimport { multihashToIPNSRoutingKey, unmarshalIPNSRecord, normalizeKey, IPNS_STRING_PREFIX } from '../utils.ts'\nimport { ipnsValidator } from '../validator.ts'\nimport type { IPNSRecord, ResolveOptions, ResolveResult } from '../index.ts'\nimport type { LocalStore } from '../local-store.ts'\nimport type { IPNSRouting } from '../routing/index.ts'\nimport type { Routing, Keychain } from '@helia/interface'\nimport type { ComponentLogger, Logger } from '@libp2p/interface'\nimport type { Datastore } from 'interface-datastore'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nexport interface IPNSResolverComponents {\n datastore: Datastore\n routing: Routing\n logger: ComponentLogger\n keychain: Keychain\n}\n\nexport interface IPNResolverInit {\n localStore: LocalStore\n routers: IPNSRouting[]\n}\n\nexport class IPNSResolver {\n public readonly routers: IPNSRouting[]\n private readonly localStore: LocalStore\n private readonly log: Logger\n private keychain: Keychain\n\n constructor (components: IPNSResolverComponents, init: IPNResolverInit) {\n this.log = components.logger.forComponent('helia:ipns')\n this.localStore = init.localStore\n this.routers = init.routers\n this.keychain = components.keychain\n }\n\n async * resolve (key: MultihashDigest, options: ResolveOptions = {}): AsyncGenerator<ResolveResult> {\n let { digest } = normalizeKey(key)\n\n while (true) {\n const routingKey = multihashToIPNSRoutingKey(digest)\n const record = await this.#findIpnsRecord(routingKey, options)\n\n yield {\n record\n }\n\n if (!record.value.startsWith(IPNS_STRING_PREFIX)) {\n // not a recursive record\n break\n }\n\n ({ digest } = normalizeKey(record.value))\n }\n }\n\n async #findIpnsRecord (routingKey: Uint8Array, options: ResolveOptions = {}): Promise<IPNSRecord> {\n const records: IPNSRecord[] = []\n const cached = await this.localStore.has(routingKey, options)\n\n if (cached) {\n this.log('record is present in the cache')\n\n if (options.nocache !== true) {\n try {\n // check the local cache first\n const { record: marshaledIPNSRecord, created } = await this.localStore.get(routingKey, options)\n\n this.log('record retrieved from cache')\n\n // unmarshal the record\n const ipnsRecord = await unmarshalIPNSRecord(routingKey, marshaledIPNSRecord, this.keychain, options)\n\n // validate the record\n await ipnsValidator(ipnsRecord, options)\n\n this.log('record was valid')\n\n // check the TTL\n\n // IPNS TTL is in nanoseconds, convert to milliseconds, default to one\n // hour\n const ttlMs = Number((ipnsRecord.ttl ?? DEFAULT_TTL_NS) / 1_000_000n)\n const ttlExpires = created.getTime() + ttlMs\n\n if (ttlExpires > Date.now()) {\n // the TTL has not yet expired, return the cached record\n this.log('record TTL was valid')\n return ipnsRecord\n }\n\n if (options.offline === true) {\n // the TTL has expired but we are skipping the routing search\n this.log('record TTL has been reached but we are resolving offline-only, returning record')\n return ipnsRecord\n }\n\n this.log('record TTL has been reached, searching routing for updates')\n\n // add the local record to our list of resolved record, and also\n // search the routing for updates - the most up to date record will be\n // returned\n records.push(ipnsRecord)\n } catch (err) {\n this.log('cached record was invalid - %e', err)\n await this.localStore.delete(routingKey, options)\n }\n } else {\n this.log('ignoring local cache due to nocache=true option')\n }\n }\n\n if (options.offline === true) {\n throw new RecordNotFoundError('Record was not present in the cache or has expired')\n }\n\n this.log('did not have record locally')\n\n let foundInvalid = 0\n const errors: Error[] = []\n\n await Promise.all(\n this.routers.map(async (router) => {\n let marshaledIPNSRecord: Uint8Array\n\n try {\n marshaledIPNSRecord = await router.get(routingKey, {\n ...options,\n validate: false\n })\n } catch (err: any) {\n this.log.error('error finding IPNS record using router %s - %e', router.toString(), err)\n errors.push(err)\n\n return\n }\n\n try {\n // unmarshal ensures that (1) SignatureV2 and Data are present, (2) that ValidityType\n // and Validity are of valid types and have a value, (3) that CBOR data matches protobuf\n // if it's a V1+V2 record\n const record = await unmarshalIPNSRecord(routingKey, marshaledIPNSRecord, this.keychain, options)\n\n await ipnsValidator(record, options)\n\n records.push(record)\n } catch (err) {\n // we found a record, but the validator rejected it\n foundInvalid++\n this.log.error('error validating IPNS record from router %s - %e', router.toString(), err)\n }\n })\n )\n\n if (records.length === 0) {\n if (foundInvalid > 0) {\n throw new RecordsFailedValidationError(`${foundInvalid > 1 ? `${foundInvalid} records` : 'Record'} found for routing key ${foundInvalid > 1 ? 'were' : 'was'} invalid`)\n }\n\n throw new RecordNotFoundError('Could not find record for routing key')\n }\n\n const record = records[ipnsSelector(routingKey, records)]\n\n await this.localStore.put(routingKey, record.bytes, options)\n\n return record\n }\n}\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", "//#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 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", "import { logger } from '@libp2p/logger'\nimport NanoDate from 'timestamp-nano'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { SignatureCreationError } from './errors.ts'\nimport { IpnsEntry } from './pb/ipns.ts'\nimport { createCborData, ipnsRecordDataForV1Sig, ipnsRecordDataForV2Sig, marshalIPNSRecord } from './utils.ts'\nimport type { PrivateKey, PublicKey } from '@helia/interface'\nimport type { AbortOptions } from 'abort-error'\nimport type { Key } from 'interface-datastore/key'\n\nconst log = logger('ipns')\nconst DEFAULT_TTL_NS = 5 * 60 * 1e+9 // 5 Minutes or 300 Seconds, as suggested by https://specs.ipfs.tech/ipns/ipns-record/#ttl-uint64\n\nexport const namespace = '/ipns/'\nexport const namespaceLength = namespace.length\n\nexport interface IPNSRecordV1V2 {\n /**\n * value of the record\n */\n value: string\n\n /**\n * signature of the record\n */\n signatureV1: Uint8Array\n\n /**\n * Type of validation being used\n */\n validityType: IpnsEntry.ValidityType\n\n /**\n * expiration datetime for the record in RFC3339 format\n */\n validity: string\n\n /**\n * number representing the version of the record\n */\n sequence: bigint\n\n /**\n * ttl in nanoseconds\n */\n ttl?: bigint\n\n /**\n * the public portion of the key that signed this record\n */\n publicKey: PublicKey\n\n /**\n * the v2 signature of the record\n */\n signatureV2: Uint8Array\n\n /**\n * extensible data\n */\n data: Uint8Array\n\n /**\n * The marshalled record\n */\n bytes: Uint8Array\n}\n\nexport interface IPNSRecordV2 {\n /**\n * value of the record\n */\n value: string\n\n /**\n * the v2 signature of the record\n */\n signatureV2: Uint8Array\n\n /**\n * Type of validation being used\n */\n validityType: IpnsEntry.ValidityType\n\n /**\n * If the validity type is EOL, this is the expiration datetime for the record\n * in RFC3339 format\n */\n validity: string\n\n /**\n * number representing the version of the record\n */\n sequence: bigint\n\n /**\n * ttl in nanoseconds\n */\n ttl?: bigint\n\n /**\n * the public portion of the key that signed this record\n */\n publicKey: PublicKey\n\n /**\n * extensible data\n */\n data: Uint8Array\n\n /**\n * The marshalled record\n */\n bytes: Uint8Array\n}\n\nexport type IPNSRecord = IPNSRecordV1V2 | IPNSRecordV2\n\nexport interface IPNSRecordData {\n Value: Uint8Array\n Validity: Uint8Array\n ValidityType: IpnsEntry.ValidityType\n Sequence: bigint\n TTL: bigint\n}\n\nexport interface IDKeys {\n routingPubKey: Key\n pkKey: Key\n routingKey: Key\n ipnsKey: Key\n}\n\nexport interface CreateOptions extends AbortOptions {\n ttlNs?: number | bigint\n v1Compatible?: boolean\n}\n\nexport interface CreateV2OrV1Options extends AbortOptions {\n v1Compatible: true\n}\n\nexport interface CreateV2Options extends AbortOptions {\n v1Compatible: false\n}\n\nconst defaultCreateOptions: CreateOptions = {\n v1Compatible: true,\n ttlNs: DEFAULT_TTL_NS\n}\n\n/**\n * Creates a new IPNS record and signs it with the given private key.\n * The IPNS Record validity should follow the [RFC3339]{@link https://www.ietf.org/rfc/rfc3339.txt} with nanoseconds precision.\n * Note: This function does not embed the public key. If you want to do that, use `EmbedPublicKey`.\n *\n * The passed value can be a CID, a PublicKey or an arbitrary string path e.g. `/ipfs/...` or `/ipns/...`.\n *\n * CIDs will be converted to v1 and stored in the record as a string similar to: `/ipfs/${cid}`\n * PublicKeys will create recursive records, eg. the record value will be `/ipns/${cidV1Libp2pKey}`\n * String paths will be stored in the record as-is, but they must start with `\"/\"`\n *\n * @param {PrivateKey} privateKey - the private key for signing the record.\n * @param {CID | PublicKey | string} value - content to be stored in the record.\n * @param {number | bigint} seq - number representing the current version of the record.\n * @param {number} lifetime - lifetime of the record (in milliseconds).\n * @param {CreateOptions} options - additional create options.\n */\nexport async function createIPNSRecord (privateKey: PrivateKey, value: string, seq: number | bigint, lifetime: number, options?: CreateV2OrV1Options): Promise<IPNSRecordV1V2>\nexport async function createIPNSRecord (privateKey: PrivateKey, value: string, seq: number | bigint, lifetime: number, options: CreateV2Options): Promise<IPNSRecordV2>\nexport async function createIPNSRecord (privateKey: PrivateKey, value: string, seq: number | bigint, lifetime: number, options: CreateOptions): Promise<IPNSRecordV1V2>\nexport async function createIPNSRecord (privateKey: PrivateKey, value: string, seq: number | bigint, lifetime: number, options: CreateOptions = defaultCreateOptions): Promise<IPNSRecord> {\n // Validity in ISOString with nanoseconds precision and validity type EOL\n const expirationDate = new NanoDate(Date.now() + Number(lifetime))\n const validityType = IpnsEntry.ValidityType.EOL\n const ttlNs = BigInt(options.ttlNs ?? DEFAULT_TTL_NS)\n\n return _create(privateKey, value, seq, validityType, expirationDate.toString(), ttlNs, options)\n}\n\n/**\n * Same as create(), but instead of generating a new Date, it receives the intended expiration time\n * WARNING: nano precision is not standard, make sure the value in seconds is 9 orders of magnitude lesser than the one provided.\n *\n * The passed value can be a CID, a PublicKey or an arbitrary string path e.g. `/ipfs/...` or `/ipns/...`.\n *\n * CIDs will be converted to v1 and stored in the record as a string similar to: `/ipfs/${cid}`\n * PublicKeys will create recursive records, eg. the record value will be `/ipns/${cidV1Libp2pKey}`\n * String paths will be stored in the record as-is, but they must start with `\"/\"`\n *\n * @param {PrivateKey} privateKey - the private key for signing the record.\n * @param {CID | PublicKey | string} value - content to be stored in the record.\n * @param {number | bigint} seq - number representing the current version of the record.\n * @param {string} expiration - expiration datetime for record in the [RFC3339]{@link https://www.ietf.org/rfc/rfc3339.txt} with nanoseconds precision.\n * @param {CreateOptions} options - additional creation options.\n */\nexport async function createIPNSRecordWithExpiration (privateKey: PrivateKey, value: string, seq: number | bigint, expiration: string, options?: CreateV2OrV1Options): Promise<IPNSRecordV1V2>\nexport async function createIPNSRecordWithExpiration (privateKey: PrivateKey, value: string, seq: number | bigint, expiration: string, options: CreateV2Options): Promise<IPNSRecordV2>\nexport async function createIPNSRecordWithExpiration (privateKey: PrivateKey, value: string, seq: number | bigint, expiration: string, options: CreateOptions): Promise<IPNSRecordV1V2>\nexport async function createIPNSRecordWithExpiration (privateKey: PrivateKey, value: string, seq: number | bigint, expiration: string, options: CreateOptions = defaultCreateOptions): Promise<IPNSRecord> {\n const expirationDate = NanoDate.fromString(expiration)\n const validityType = IpnsEntry.ValidityType.EOL\n const ttlNs = BigInt(options.ttlNs ?? DEFAULT_TTL_NS)\n\n return _create(privateKey, value, seq, validityType, expirationDate.toString(), ttlNs, options)\n}\n\nconst _create = async (privateKey: PrivateKey, value: string, seq: number | bigint, validityType: IpnsEntry.ValidityType, validity: string, ttl: bigint, options: CreateOptions = defaultCreateOptions): Promise<IPNSRecord> => {\n seq = BigInt(seq)\n const isoValidity = uint8ArrayFromString(validity)\n const data = createCborData(value, validityType, isoValidity, seq, ttl)\n const sigData = ipnsRecordDataForV2Sig(data)\n const signatureV2 = await privateKey.sign(sigData, options)\n const publicKey = shouldEmbedPublicKey(privateKey.publicKey) ? privateKey.publicKey : undefined\n let record: any\n\n if (options.v1Compatible === true) {\n const signatureV1 = await signLegacyV1(privateKey, value, validityType, isoValidity)\n\n record = {\n value,\n signatureV1,\n validity,\n validityType,\n sequence: seq,\n ttl,\n signatureV2,\n data,\n publicKey\n }\n } else {\n record = {\n value,\n validity,\n validityType,\n sequence: seq,\n ttl,\n signatureV2,\n data,\n publicKey\n }\n }\n\n record.bytes = marshalIPNSRecord(record)\n\n return record\n}\n\nexport { unmarshalIPNSRecord } from './utils.ts'\nexport { marshalIPNSRecord } from './utils.ts'\nexport { multihashToIPNSRoutingKey } from './utils.ts'\nexport { multihashFromIPNSRoutingKey } from './utils.ts'\n\n/**\n * Sign ipns record data using the legacy V1 signature scheme\n */\nconst signLegacyV1 = async (privateKey: PrivateKey, value: string, validityType: IpnsEntry.ValidityType, validity: Uint8Array, options?: AbortOptions): Promise<Uint8Array> => {\n try {\n const dataForSignature = ipnsRecordDataForV1Sig(value, validityType, validity)\n\n return await privateKey.sign(dataForSignature, options)\n } catch (error: any) {\n log.error('record signature creation failed', error)\n throw new SignatureCreationError('Record signature creation failed')\n }\n}\n\n/**\n * Returns true if the public key multihash is not an identity hash\n */\nfunction shouldEmbedPublicKey (key: PublicKey): boolean {\n return key.toMultihash().code !== 0\n}\n", "import { base36 } from 'multiformats/bases/base36'\nimport { CustomProgressEvent } from 'progress-events'\nimport { DEFAULT_LIFETIME_MS, DEFAULT_TTL_NS } from '../constants.ts'\nimport { createIPNSRecord } from '../records.ts'\nimport { marshalIPNSRecord, multihashToIPNSRoutingKey, unmarshalIPNSRecord } from '../utils.ts'\nimport type { PublishResult, PublishOptions } from '../index.ts'\nimport type { LocalStore } from '../local-store.ts'\nimport type { IPNSRouting } from '../routing/index.ts'\nimport type { Keychain, PrivateKey } from '@helia/interface'\nimport type { AbortOptions, ComponentLogger } from '@libp2p/interface'\nimport type { Datastore } from 'interface-datastore'\n\nexport interface IPNSPublisherComponents {\n datastore: Datastore\n logger: ComponentLogger\n keychain: Keychain\n}\n\nexport interface IPNSPublisherInit {\n localStore: LocalStore\n routers: IPNSRouting[]\n}\n\nexport class IPNSPublisher {\n public readonly routers: IPNSRouting[]\n private readonly localStore: LocalStore\n private readonly keychain: Keychain\n\n constructor (components: IPNSPublisherComponents, init: IPNSPublisherInit) {\n this.keychain = components.keychain\n this.localStore = init.localStore\n this.routers = init.routers\n }\n\n async publish (keyName: string, value: string, options: PublishOptions = {}): Promise<PublishResult> {\n try {\n const key = await this.#loadOrCreateKey(keyName, options)\n const digest = key.publicKey.toMultihash()\n const routingKey = multihashToIPNSRoutingKey(digest)\n let sequenceNumber = 1n\n\n if (await this.localStore.has(routingKey, options)) {\n // if we have published under this key before, increment the sequence number\n const { record } = await this.localStore.get(routingKey, options)\n const existingRecord = await unmarshalIPNSRecord(routingKey, record, this.keychain, options)\n sequenceNumber = existingRecord.sequence + 1n\n }\n\n // convert ttl from milliseconds to nanoseconds as createIPNSRecord expects\n const ttlNs = options.ttl != null ? BigInt(options.ttl) * 1_000_000n : DEFAULT_TTL_NS\n const lifetime = options.lifetime ?? DEFAULT_LIFETIME_MS\n const record = await createIPNSRecord(key, value, sequenceNumber, lifetime, { ...options, ttlNs })\n const marshaledRecord = marshalIPNSRecord(record)\n\n if (options.offline === true) {\n // only store record locally\n await this.localStore.put(routingKey, marshaledRecord, { ...options, metadata: { keyName, lifetime } })\n } else {\n // publish record to routing (including the local store)\n await Promise.all(this.routers.map(async r => {\n await r.put(routingKey, marshaledRecord, { ...options, metadata: { keyName, lifetime } })\n }))\n }\n\n return {\n record: {\n ...record,\n publicKey: key.publicKey\n },\n name: `/ipns/${key.publicKey.toCID().toString(base36)}`,\n publicKey: key.publicKey\n }\n } catch (err: any) {\n options.onProgress?.(new CustomProgressEvent<Error>('ipns:publish:error', err))\n throw err\n }\n }\n\n /**\n * Create the private key if it is not in the keychain already, defaulting to\n * Ed25519 keys\n */\n async #loadOrCreateKey (keyName: string, options?: AbortOptions): Promise<PrivateKey> {\n try {\n return await this.keychain.exportKey(keyName, options)\n } catch (err: any) {\n if (err.name === 'NotFoundError') {\n // create a new key\n return this.keychain.generateKey(keyName, options)\n } else {\n throw err\n }\n }\n }\n\n async unpublish (keyName: string, options?: AbortOptions): Promise<void> {\n const key = await this.keychain.exportKey(keyName, options)\n const digest = key.publicKey.toMultihash()\n const routingKey = multihashToIPNSRoutingKey(digest)\n await this.localStore.delete(routingKey, options)\n }\n}\n", "export default function pDefer() {\n\tconst deferred = {};\n\n\tdeferred.promise = new Promise((resolve, reject) => {\n\t\tdeferred.resolve = resolve;\n\t\tdeferred.reject = reject;\n\t});\n\n\treturn deferred;\n}\n", "// 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", "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", "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", "/**\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", "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", "import { anySignal } from 'any-signal'\nimport { setMaxListeners } from 'main-event'\nimport { debounce } from './debounce.ts'\nimport type { AbortOptions } from '@libp2p/interface'\n\nexport interface RepeatingTask {\n /**\n * Update the interval after which the next iteration of the task will run.\n *\n * This is useful if, for example, you want to retry a task with a short rest\n * duration until it succeeds, then periodically after that.\n *\n * This only affects the next iteration of the task, if it is currently\n * running, that run will not be interrupted.\n *\n * Setting the interval to the current value has no effect.\n */\n setInterval(ms: number): void\n\n /**\n * Update the amount of time a task will run before the passed abort signal\n * will fire.\n *\n * This only affects the next iteration of the task, if it is currently\n * running, that run will not be interrupted.\n */\n setTimeout(ms: number): void\n\n /**\n * Schedule the task to be run immediately - if the task is not running it\n * will run after a short delay in order to debounce multiple `.run()`\n * invocations.\n */\n run(): void\n\n /**\n * Start the task running\n */\n start(): void\n\n /**\n * Stop the task running\n */\n stop(): void\n}\n\nexport interface RepeatingTaskOptions {\n /**\n * How long the task is allowed to run before the passed AbortSignal fires an\n * abort event\n */\n timeout?: number\n\n /**\n * Whether to schedule the task to run immediately\n *\n * @default false\n */\n runImmediately?: boolean\n\n /**\n * When `.run()` is called to run the task outside of the current interval,\n * debounce repeated calls to `.run()` by this amount.\n *\n * @default 100\n */\n debounce?: number\n}\n\nexport function repeatingTask (fn: (options?: AbortOptions) => void | Promise<void>, interval: number, options?: RepeatingTaskOptions): RepeatingTask {\n let timeout: ReturnType<typeof setTimeout>\n let shutdownController: AbortController\n let running = false\n\n function runTask (): void {\n const opts: AbortOptions = {\n signal: shutdownController.signal\n }\n\n let signal: ReturnType<typeof anySignal> | undefined\n\n if (options?.timeout != null) {\n signal = anySignal([shutdownController.signal, AbortSignal.timeout(options.timeout)])\n setMaxListeners(Infinity, signal)\n\n opts.signal = signal\n }\n\n running = true\n\n Promise.resolve().then(async () => {\n await fn(opts)\n })\n .catch(() => {})\n .finally(() => {\n if (signal != null) {\n if (signal.aborted) {\n signal.clear()\n } else {\n // Clear listeners once this per-run signal eventually aborts\n signal.addEventListener('abort', () => {\n signal.clear()\n }, { once: true })\n }\n }\n\n running = false\n\n if (shutdownController.signal.aborted) {\n // task has been cancelled, bail\n return\n }\n\n // reschedule\n timeout = setTimeout(runTask, interval)\n })\n }\n\n const runTaskDebounced = debounce(runTask, options?.debounce ?? 100)\n\n let started = false\n\n return {\n setInterval: (ms): void => {\n if (interval === ms) {\n // already running at this interval, nothing to do\n return\n }\n\n interval = ms\n\n // maybe reschedule\n if (timeout != null) {\n clearTimeout(timeout)\n timeout = setTimeout(runTask, interval)\n }\n },\n setTimeout: (ms): void => {\n options ??= {}\n options.timeout = ms\n },\n run: (): void => {\n if (running) {\n return\n }\n\n clearTimeout(timeout)\n runTaskDebounced()\n },\n start: (): void => {\n if (started) {\n return\n }\n\n started = true\n shutdownController = new AbortController()\n setMaxListeners(Infinity, shutdownController.signal)\n\n // run now\n if (options?.runImmediately === true) {\n queueMicrotask(() => {\n runTask()\n })\n } else {\n // run later\n timeout = setTimeout(runTask, interval)\n }\n },\n stop: (): void => {\n clearTimeout(timeout)\n shutdownController?.abort()\n started = false\n }\n }\n}\n", "import { Queue, repeatingTask } from '@libp2p/utils'\nimport { DEFAULT_REPUBLISH_CONCURRENCY, DEFAULT_REPUBLISH_INTERVAL_MS, DEFAULT_TTL_NS } from '../constants.ts'\nimport { createIPNSRecord } from '../records.ts'\nimport { marshalIPNSRecord, unmarshalIPNSRecord } from '../utils.ts'\nimport { shouldRepublish } from '../utils.ts'\nimport type { IPNSRecord } from '../index.ts'\nimport type { LocalStore } from '../local-store.ts'\nimport type { IPNSRouting } from '../routing/index.ts'\nimport type { Keychain, PrivateKey } from '@helia/interface'\nimport type { AbortOptions, ComponentLogger, Logger } from '@libp2p/interface'\nimport type { RepeatingTask } from '@libp2p/utils'\n\nexport interface IPNSRepublisherComponents {\n logger: ComponentLogger\n keychain: Keychain\n}\n\nexport interface IPNSRepublisherInit {\n republishConcurrency?: number\n republishInterval?: number\n routers: IPNSRouting[]\n localStore: LocalStore\n}\n\nexport class IPNSRepublisher {\n public readonly routers: IPNSRouting[]\n private readonly localStore: LocalStore\n private readonly republishTask: RepeatingTask\n private readonly log: Logger\n private readonly keychain: Keychain\n private started: boolean = false\n private readonly republishConcurrency: number\n\n constructor (components: IPNSRepublisherComponents, init: IPNSRepublisherInit) {\n this.log = components.logger.forComponent('helia:ipns')\n this.localStore = init.localStore\n this.keychain = components.keychain\n this.republishConcurrency = init.republishConcurrency || DEFAULT_REPUBLISH_CONCURRENCY\n this.started = false\n this.routers = init.routers ?? []\n\n this.republishTask = repeatingTask(this.#republish.bind(this), init.republishInterval ?? DEFAULT_REPUBLISH_INTERVAL_MS, {\n runImmediately: true\n })\n\n if (this.started) {\n this.republishTask.start()\n }\n }\n\n start (): void {\n if (this.started) {\n return\n }\n\n this.started = true\n this.republishTask.start()\n }\n\n stop (): void {\n if (!this.started) {\n return\n }\n\n this.started = false\n this.republishTask.stop()\n }\n\n async #republish (options: AbortOptions = {}): Promise<void> {\n if (!this.started) {\n return\n }\n\n this.log('starting ipns republish records loop')\n\n const queue = new Queue({\n concurrency: this.republishConcurrency\n })\n\n try {\n const recordsToRepublish: Array<{ routingKey: Uint8Array, record: IPNSRecord }> = []\n let listed = 0\n\n // Find all records using the localStore.list method\n for await (const { routingKey, record, metadata, created } of this.localStore.list(options)) {\n listed++\n\n if (metadata == null) {\n // Skip if no metadata is found from before we started\n // storing metadata or for records republished without a key\n this.log('no metadata found for record %b, skipping', routingKey)\n continue\n }\n let ipnsRecord: IPNSRecord\n try {\n ipnsRecord = await unmarshalIPNSRecord(routingKey, record, this.keychain, options)\n } catch (err: any) {\n this.log.error('error unmarshaling record - %e', err)\n continue\n }\n\n // Only republish records that are within the DHT or record expiry threshold\n if (!shouldRepublish(ipnsRecord, created)) {\n this.log.trace('skipping record %b within republish threshold', routingKey)\n continue\n }\n const sequenceNumber = ipnsRecord.sequence + 1n\n const ttlNs = ipnsRecord.ttl ?? DEFAULT_TTL_NS\n let privKey: PrivateKey\n\n try {\n privKey = await this.keychain.exportKey(metadata.keyName)\n } catch (err: any) {\n this.log.error('missing key %s, skipping republishing record - %e', metadata.keyName, err)\n continue\n }\n\n try {\n const updatedRecord = await createIPNSRecord(privKey, ipnsRecord.value, sequenceNumber, metadata.lifetime, {\n ...options,\n ttlNs\n })\n recordsToRepublish.push({\n routingKey,\n record: updatedRecord\n })\n } catch (err: any) {\n this.log.error('error creating updated IPNS record for %s - %e', routingKey, err)\n continue\n }\n }\n\n this.log(`found ${recordsToRepublish.length}/${listed} records to republish`)\n\n // Republish each record\n for (const { routingKey, record } of recordsToRepublish) {\n // Add job to queue to republish the record to all routers\n queue.add(async () => {\n try {\n const marshaledRecord = marshalIPNSRecord(record)\n await Promise.all(\n this.routers.map(r => r.put(routingKey, marshaledRecord, options))\n )\n } catch (err: any) {\n this.log.error('error republishing record - %e', err)\n }\n }, options)\n }\n } catch (err: any) {\n this.log.error('error during republish - %e', err)\n }\n\n await queue.onIdle(options) // Wait for all jobs to complete\n }\n}\n", "import { decodeMessage, encodeMessage, message, streamMessage } from 'protons-runtime'\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc'\nimport type { Codec, DecodeOptions } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface Record {\n key: Uint8Array\n value: Uint8Array\n timeReceived: string\n}\n\nexport namespace Record {\n let _codec: Codec<Record>\n\n export const codec = (): Codec<Record> => {\n if (_codec == null) {\n _codec = message<Record>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.key != null && obj.key.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.key)\n }\n\n if ((obj.value != null && obj.value.byteLength > 0)) {\n w.uint32(18)\n w.bytes(obj.value)\n }\n\n if ((obj.timeReceived != null && obj.timeReceived !== '')) {\n w.uint32(42)\n w.string(obj.timeReceived)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {\n key: uint8ArrayAlloc(0),\n value: uint8ArrayAlloc(0),\n timeReceived: ''\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.key = reader.bytes()\n break\n }\n case 2: {\n obj.value = reader.bytes()\n break\n }\n case 5: {\n obj.timeReceived = reader.string()\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}.key`,\n value: reader.bytes()\n }\n break\n }\n case 2: {\n yield {\n field: `${prefix}.value`,\n value: reader.bytes()\n }\n break\n }\n case 5: {\n yield {\n field: `${prefix}.timeReceived`,\n value: reader.string()\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 RecordKeyFieldEvent {\n field: '$.key'\n value: Uint8Array\n }\n\n export interface RecordValueFieldEvent {\n field: '$.value'\n value: Uint8Array\n }\n\n export interface RecordTimeReceivedFieldEvent {\n field: '$.timeReceived'\n value: string\n }\n\n export function encode (obj: Partial<Record>): Uint8Array {\n return encodeMessage(obj, Record.codec())\n }\n\n export function decode (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<Record>): Record {\n return decodeMessage(buf, Record.codec(), opts)\n }\n\n export function stream (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<Record>): Generator<RecordKeyFieldEvent | RecordValueFieldEvent | RecordTimeReceivedFieldEvent> {\n return streamMessage(buf, Record.codec(), opts)\n }\n}\n", "/**\n * Convert a JavaScript date into an `RFC3339Nano` formatted\n * string\n */\nexport function toRFC3339 (time: Date): string {\n const year = time.getUTCFullYear()\n const month = String(time.getUTCMonth() + 1).padStart(2, '0')\n const day = String(time.getUTCDate()).padStart(2, '0')\n const hour = String(time.getUTCHours()).padStart(2, '0')\n const minute = String(time.getUTCMinutes()).padStart(2, '0')\n const seconds = String(time.getUTCSeconds()).padStart(2, '0')\n const milliseconds = time.getUTCMilliseconds()\n const nanoseconds = String(milliseconds * 1000 * 1000).padStart(9, '0')\n\n return `${year}-${month}-${day}T${hour}:${minute}:${seconds}.${nanoseconds}Z`\n}\n\n/**\n * Parses a date string formatted as `RFC3339Nano` into a\n * JavaScript Date object\n */\nexport function parseRFC3339 (time: string): Date {\n const rfc3339Matcher = new RegExp(\n // 2006-01-02T\n '(\\\\d{4})-(\\\\d{2})-(\\\\d{2})T' +\n // 15:04:05\n '(\\\\d{2}):(\\\\d{2}):(\\\\d{2})' +\n // .999999999Z\n '\\\\.(\\\\d+)Z'\n )\n const m = String(time).trim().match(rfc3339Matcher)\n\n if (m == null) {\n throw new Error('Invalid format')\n }\n\n const year = parseInt(m[1], 10)\n const month = parseInt(m[2], 10) - 1\n const date = parseInt(m[3], 10)\n const hour = parseInt(m[4], 10)\n const minute = parseInt(m[5], 10)\n const second = parseInt(m[6], 10)\n const millisecond = parseInt(m[7].slice(0, -6), 10)\n\n return new Date(Date.UTC(year, month, date, hour, minute, second, millisecond))\n}\n", "/**\n * @packageDocumentation\n *\n * This is an implementation of the [routing record format](https://github.com/libp2p/specs/blob/b9efe152c29f93f7a87931c14d78ae11e7924d5a/kad-dht/README.md?plain=1#L408-L425) used by libp2p to store data in the datastore passed to the libp2p constructor.\n *\n * @example Deserialization\n *\n * ```TypeScript\n * import { Libp2pRecord } from '@libp2p/record'\n *\n * const buf = Uint8Array.from([0, 1, 2, 3])\n * const record = Libp2pRecord.deserialize(buf)\n * ```\n *\n * @example Serialization\n *\n * ```TypeScript\n * import { Libp2pRecord } from '@libp2p/record'\n *\n * const key = Uint8Array.from([0, 1, 2, 3])\n * const value = Uint8Array.from([0, 1, 2, 3])\n * const timeReceived = new Date()\n *\n * const record = new Libp2pRecord(key, value, timeReceived)\n * const buf = record.serialize()\n * ```\n */\n\nimport {\n Record\n} from './record.ts'\nimport * as utils from './utils.ts'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class Libp2pRecord {\n public key: Uint8Array\n public value: Uint8Array\n public timeReceived: Date\n\n constructor (key: Uint8Array, value: Uint8Array, timeReceived: Date) {\n if (!(key instanceof Uint8Array)) {\n throw new Error('key must be a Uint8Array')\n }\n\n if (!(value instanceof Uint8Array)) {\n throw new Error('value must be a Uint8Array')\n }\n\n this.key = key\n this.value = value\n this.timeReceived = timeReceived\n }\n\n serialize (): Uint8Array {\n return Record.encode(this.prepareSerialize())\n }\n\n /**\n * Return the object format ready to be given to the protobuf library.\n */\n prepareSerialize (): Record {\n return {\n key: this.key,\n value: this.value,\n timeReceived: utils.toRFC3339(this.timeReceived)\n }\n }\n\n /**\n * Decode a protobuf encoded record\n */\n static deserialize (raw: Uint8Array | Uint8ArrayList): Libp2pRecord {\n const rec = Record.decode(raw)\n\n return new Libp2pRecord(rec.key, rec.value, new Date(rec.timeReceived))\n }\n\n /**\n * Create a record from the raw object returned from the protobuf library\n */\n static fromDeserialized (obj: Record): Libp2pRecord {\n const receivedTime = utils.parseRFC3339(obj.timeReceived)\n\n if (obj.key == null) {\n throw new Error('key missing from deserialized object')\n }\n\n if (obj.value == null) {\n throw new Error('value missing from deserialized object')\n }\n\n const rec = new Libp2pRecord(\n obj.key, obj.value, receivedTime\n )\n\n return rec\n }\n}\n", "/**\n * @packageDocumentation\n *\n * This module implements the [libp2p Kademlia spec](https://github.com/libp2p/specs/blob/master/kad-dht/README.md) in TypeScript.\n *\n * The Kademlia DHT allow for several operations such as finding peers, searching for providers of DHT records, etc.\n *\n * @example Using with libp2p\n *\n * ```TypeScript\n * import { kadDHT } from '@libp2p/kad-dht'\n * import { createLibp2p } from 'libp2p'\n * import { peerIdFromString } from '@libp2p/peer-id'\n * import { ping } from '@libp2p/ping'\n * import { identify } from '@libp2p/identify'\n *\n * const node = await createLibp2p({\n * services: {\n * dht: kadDHT({\n * // DHT options\n * }),\n * ping: ping(),\n * identify: identify()\n * }\n * })\n *\n * const peerId = peerIdFromString('QmFoo')\n * const peerInfo = await node.peerRouting.findPeer(peerId)\n *\n * console.info(peerInfo) // peer id, multiaddrs\n * ```\n *\n * @example Connecting to the IPFS Amino DHT\n *\n * The [Amino DHT](https://blog.ipfs.tech/2023-09-amino-refactoring/) is a public-good DHT used by IPFS to fetch content, find peers, etc.\n *\n * If you are trying to access content on the public internet, this is the implementation you want.\n *\n * ```TypeScript\n * import { kadDHT, removePrivateAddressesMapper } from '@libp2p/kad-dht'\n * import { createLibp2p } from 'libp2p'\n * import { peerIdFromString } from '@libp2p/peer-id'\n * import { ping } from '@libp2p/ping'\n * import { identify } from '@libp2p/identify'\n *\n * const node = await createLibp2p({\n * services: {\n * aminoDHT: kadDHT({\n * protocol: '/ipfs/kad/1.0.0',\n * peerInfoMapper: removePrivateAddressesMapper\n * }),\n * ping: ping(),\n * identify: identify()\n * }\n * })\n *\n * const peerId = peerIdFromString('QmFoo')\n * const peerInfo = await node.peerRouting.findPeer(peerId)\n *\n * console.info(peerInfo) // peer id, multiaddrs\n * ```\n *\n * @example Connecting to a LAN-only DHT\n *\n * This DHT only works with privately dialable peers.\n *\n * This is for use when peers are on the local area network.\n *\n * ```TypeScript\n * import { kadDHT, removePublicAddressesMapper } from '@libp2p/kad-dht'\n * import { createLibp2p } from 'libp2p'\n * import { peerIdFromString } from '@libp2p/peer-id'\n * import { ping } from '@libp2p/ping'\n * import { identify } from '@libp2p/identify'\n *\n * const node = await createLibp2p({\n * services: {\n * lanDHT: kadDHT({\n * protocol: '/ipfs/lan/kad/1.0.0',\n * peerInfoMapper: removePublicAddressesMapper,\n * clientMode: false\n * }),\n * ping: ping(),\n * identify: identify()\n * }\n * })\n *\n * const peerId = peerIdFromString('QmFoo')\n * const peerInfo = await node.peerRouting.findPeer(peerId)\n *\n * console.info(peerInfo) // peer id, multiaddrs\n * ```\n *\n * @example Connecting to both a LAN-only DHT and the IPFS Amino DHT\n *\n * When using multiple DHTs, you should specify distinct datastore, metrics and\n * log prefixes to ensure that data is kept separate for each instance.\n *\n * ```TypeScript\n * import { kadDHT, removePublicAddressesMapper, removePrivateAddressesMapper } from '@libp2p/kad-dht'\n * import { createLibp2p } from 'libp2p'\n * import { peerIdFromString } from '@libp2p/peer-id'\n * import { ping } from '@libp2p/ping'\n * import { identify } from '@libp2p/identify'\n *\n * const node = await createLibp2p({\n * services: {\n * lanDHT: kadDHT({\n * protocol: '/ipfs/lan/kad/1.0.0',\n * peerInfoMapper: removePublicAddressesMapper,\n * clientMode: false,\n * logPrefix: 'libp2p:dht-lan',\n * datastorePrefix: '/dht-lan',\n * metricsPrefix: 'libp2p_dht_lan'\n * }),\n * aminoDHT: kadDHT({\n * protocol: '/ipfs/kad/1.0.0',\n * peerInfoMapper: removePrivateAddressesMapper,\n * logPrefix: 'libp2p:dht-amino',\n * datastorePrefix: '/dht-amino',\n * metricsPrefix: 'libp2p_dht_amino'\n * }),\n * ping: ping(),\n * identify: identify()\n * }\n * })\n *\n * const peerId = peerIdFromString('QmFoo')\n * const peerInfo = await node.peerRouting.findPeer(peerId)\n *\n * console.info(peerInfo) // peer id, multiaddrs\n * ```\n */\n\nimport { KadDHT as KadDHTClass } from './kad-dht.ts'\nimport { MessageType } from './message/dht.ts'\nimport { removePrivateAddressesMapper, removePublicAddressesMapper, passthroughMapper } from './utils.ts'\nimport type { Libp2pEvents, ComponentLogger, Metrics, PeerId, PeerInfo, PeerStore, RoutingOptions, PrivateKey, AbortOptions } from '@libp2p/interface'\nimport type { AddressManager, ConnectionManager, Registrar } from '@libp2p/interface-internal'\nimport type { Ping } from '@libp2p/ping'\nimport type { AdaptiveTimeoutInit } from '@libp2p/utils'\nimport type { Datastore } from 'interface-datastore'\nimport type { TypedEventTarget } from 'main-event'\nimport type { CID } from 'multiformats/cid'\nimport type { ProgressEvent } from 'progress-events'\n\nexport { Libp2pRecord as Record } from '@libp2p/record'\nexport { removePrivateAddressesMapper, removePublicAddressesMapper, passthroughMapper }\n\n/**\n * The types of events emitted during DHT queries\n */\nexport enum EventTypes {\n SEND_QUERY = 0,\n PEER_RESPONSE,\n FINAL_PEER,\n QUERY_ERROR,\n PROVIDER,\n VALUE,\n ADD_PEER,\n DIAL_PEER,\n PATH_ENDED\n}\n\n/**\n * The types of messages sent to peers during DHT queries\n */\nexport { MessageType }\n\nexport type MessageName = keyof typeof MessageType\n\nexport interface DHTRecord {\n key: Uint8Array\n value: Uint8Array\n timeReceived?: Date\n}\n\nexport type DHTProgressEvents =\n ProgressEvent<'kad-dht:query:send-query', SendQueryEvent> |\n ProgressEvent<'kad-dht:query:peer-response', PeerResponseEvent> |\n ProgressEvent<'kad-dht:query:final-peer', FinalPeerEvent> |\n ProgressEvent<'kad-dht:query:query-error', QueryErrorEvent> |\n ProgressEvent<'kad-dht:query:provider', ProviderEvent> |\n ProgressEvent<'kad-dht:query:value', ValueEvent> |\n ProgressEvent<'kad-dht:query:add-peer', AddPeerEvent> |\n ProgressEvent<'kad-dht:query:dial-peer', DialPeerEvent>\n\nexport interface DisjointPath {\n index: number\n queued: number\n running: number\n total: number\n}\n\n/**\n * Emitted when sending queries to remote peers\n */\nexport interface SendQueryEvent {\n to: PeerId\n type: EventTypes.SEND_QUERY\n name: 'SEND_QUERY'\n messageName: keyof typeof MessageType\n messageType: MessageType\n path: DisjointPath\n}\n\n/**\n * Emitted when query responses are received form remote peers. Depending on the query\n * these events may be followed by a `FinalPeerEvent`, a `ValueEvent` or a `ProviderEvent`.\n */\nexport interface PeerResponseEvent {\n from: PeerId\n type: EventTypes.PEER_RESPONSE\n name: 'PEER_RESPONSE'\n messageName: keyof typeof MessageType\n messageType: MessageType\n closer: PeerInfo[]\n providers: PeerInfo[]\n record?: DHTRecord\n path: DisjointPath\n}\n\n/**\n * Emitted at the end of a `findPeer` query\n */\nexport interface FinalPeerEvent {\n from: PeerId\n peer: PeerInfo\n type: EventTypes.FINAL_PEER\n name: 'FINAL_PEER'\n path: DisjointPath\n}\n\n/**\n * Something went wrong with the query\n */\nexport interface QueryErrorEvent {\n from: PeerId\n type: EventTypes.QUERY_ERROR\n name: 'QUERY_ERROR'\n error: Error\n path: DisjointPath\n}\n\n/**\n * Emitted when providers are found\n */\nexport interface ProviderEvent {\n from: PeerId\n type: EventTypes.PROVIDER\n name: 'PROVIDER'\n providers: PeerInfo[]\n path: DisjointPath\n}\n\n/**\n * Emitted when values are found\n */\nexport interface ValueEvent {\n from: PeerId\n type: EventTypes.VALUE\n name: 'VALUE'\n value: Uint8Array\n path: DisjointPath\n}\n\n/**\n * Emitted when peers are added to a query\n */\nexport interface AddPeerEvent {\n type: EventTypes.ADD_PEER\n name: 'ADD_PEER'\n peer: PeerId\n path: DisjointPath\n}\n\n/**\n * Emitted when peers are dialled and a new stream is opened as part of a query\n */\nexport interface DialPeerEvent {\n peer: PeerId\n type: EventTypes.DIAL_PEER\n name: 'DIAL_PEER'\n path: DisjointPath\n}\n\n/**\n * Emitted when sending queries to remote peers\n */\nexport interface PathEndedEvent {\n type: EventTypes.PATH_ENDED\n name: 'PATH_ENDED'\n path: DisjointPath\n}\n\nexport type QueryEvent = SendQueryEvent | PeerResponseEvent | FinalPeerEvent | QueryErrorEvent | ProviderEvent | ValueEvent | AddPeerEvent | DialPeerEvent | PathEndedEvent\n\nexport interface RoutingTable {\n size: number\n}\n\nexport interface PeerInfoMapper {\n (peer: PeerInfo): PeerInfo\n}\n\nexport interface SetModeOptions extends AbortOptions {\n force?: boolean\n}\n\nexport interface KadDHT {\n /**\n * This is the maximum size of the k-buckets and how many peers are looked up\n * when searching for peers close to a key.\n */\n readonly k: number\n\n /**\n * Query concurrency factor - this controls how many peers we contact in\n * parallel during a query.\n */\n readonly a: number\n\n /**\n * From section 4.4 of the S/Kademlia paper - this is how many disjoint paths\n * are used during a query.\n */\n readonly d: number\n\n /**\n * Validators validate DHT records that are found\n */\n readonly validators: Record<string, ValidateFn>\n\n /**\n * When multiple records for a DHT key are found, selectors choose one record\n */\n readonly selectors: Record<string, SelectFn>\n\n /**\n * Get a value from the DHT, the final ValueEvent will be the best value\n */\n get(key: Uint8Array, options?: RoutingOptions): AsyncIterable<QueryEvent>\n\n /**\n * Find providers of a given CID\n */\n findProviders(key: CID, options?: RoutingOptions): AsyncIterable<QueryEvent>\n\n /**\n * Find a peer on the DHT\n */\n findPeer(id: PeerId, options?: RoutingOptions): AsyncIterable<QueryEvent>\n\n /**\n * Find the closest peers to the passed key\n */\n getClosestPeers(key: Uint8Array, options?: RoutingOptions): AsyncIterable<QueryEvent>\n\n /**\n * Store provider records for the passed CID on the DHT pointing to us\n */\n provide(key: CID, options?: RoutingOptions): AsyncIterable<QueryEvent>\n\n /**\n * Provider records must be re-published every 24 hours - pass a previously\n * provided CID here to not re-publish a record for it any more\n */\n cancelReprovide(key: CID, options?: AbortOptions): Promise<void>\n\n /**\n * Store the passed value under the passed key on the DHT\n */\n put(key: Uint8Array, value: Uint8Array, options?: RoutingOptions): AsyncIterable<QueryEvent>\n\n /**\n * Returns the mode this node is in\n */\n getMode(): 'client' | 'server'\n\n /**\n * If 'server' this node will respond to DHT queries, if 'client' this node\n * will not.\n */\n setMode(mode: 'client' | 'server', options?: SetModeOptions): Promise<void>\n\n /**\n * Force a routing table refresh\n */\n refreshRoutingTable(options?: AbortOptions): Promise<void>\n}\n\nexport interface SingleKadDHT extends KadDHT {\n routingTable: RoutingTable\n}\n\n/**\n * A selector function takes a DHT key and a list of records and returns the\n * index of the best record in the list\n */\nexport interface SelectFn {\n (key: Uint8Array, records: Uint8Array[]): number | Promise<number>\n}\n\n/**\n * A validator function takes a DHT key and the value of the record for that key\n * and throws if the record is invalid\n */\nexport interface ValidateFn {\n (key: Uint8Array, value: Uint8Array, options?: AbortOptions): void | Promise<void>\n}\n\n/**\n * Selectors are a map of key prefixes to selector functions\n */\nexport type Selectors = Record<string, SelectFn>\n\n/**\n * Validators are a map of key prefixes to validator functions\n */\nexport type Validators = Record<string, ValidateFn>\n\nexport interface ProvidersInit {\n /**\n * @default 256\n */\n cacheSize?: number\n /**\n * How often invalid records are cleaned in seconds\n *\n * @default 5_400\n */\n cleanupInterval?: number\n /**\n * How long is a provider valid for in seconds\n *\n * @default 86_400\n */\n provideValidity?: number\n}\n\nexport interface ReProvideInit {\n /**\n * How many re-provide operations to run simultaneously\n *\n * @default 10\n */\n concurrency?: number\n\n /**\n * How long to let the re-provide queue grow\n *\n * @default 16_384\n */\n maxQueueSize?: number\n\n /**\n * How long before the record expiry to re-provide in ms\n *\n * @default 86_400_000 (24 hours)\n */\n threshold?: number\n\n /**\n * How often to check which records need re-providing in ms\n *\n * @default 3_600_000 (1 hour)\n */\n interval?: number\n\n /**\n * How long provider records are valid for in ms\n *\n * @default 172_800_000 (48 hours)\n */\n validity?: number\n}\n\nexport interface KadDHTInit {\n /**\n * How many peers to store in each kBucket. Once there are more than this\n * number of peers for a given prefix in a kBucket, the node will start to\n * ping existing peers to see if they are still online - if they are offline\n * they will be evicted and the new peer added.\n *\n * @default 20\n */\n kBucketSize?: number\n\n /**\n * The threshold at which a kBucket will be split into two smaller kBuckets.\n *\n * KBuckets will not be split once the maximum trie depth is reached\n * (controlled by the `prefixLength` option) so one can replicate go-libp2p's\n * accelerated DHT client by (for example) setting `kBucketSize` to `Infinity`\n * and `kBucketSplitThreshold` to 20.\n *\n * @default kBucketSize\n */\n kBucketSplitThreshold?: number\n\n /**\n * How many peers are queried in parallel during a query.\n *\n * @default 10\n */\n alpha?: number\n\n /**\n * How many disjoint paths are used during a query\n *\n * @see https://telematics.tm.kit.edu/publications/Files/267/SKademlia_2007.pdf - section 4.4\n *\n * @default alpha\n */\n disjointPaths?: number\n\n /**\n * Concurrency for background routing table updates from query responses.\n *\n * @default min(alpha * 2, 16)\n */\n routingTableUpdateQueueConcurrency?: number\n\n /**\n * Maximum number of pending routing table updates from query responses.\n *\n * @default 16384\n */\n routingTableUpdateMaxQueueSize?: number\n\n /**\n * How many bits of the KAD-ID of peers to use when creating the routing\n * table.\n *\n * The routing table is a binary trie with peers stored in the leaf nodes. The\n * larger this number gets, the taller the trie can grow and the more peers\n * can be stored.\n *\n * Storing more peers means fewer lookups (and network operations) are needed\n * to locate a certain peer, but also that more memory is consumed and more\n * CPU while responding to queries (e.g. with more peers in the table sorting\n * the closest peers becomes more expensive) and CPU/network during table\n * maintenance (e.g. checking peers are still online).\n *\n * The larger this value, the more prefix bits must be the same for a peer to\n * be stored in a KAD bucket, so the fewer nodes that bucket is likely to\n * contain.\n *\n * The total number of peers in the table is a factor of `prefixLength` and\n * `kBucketSize`:\n *\n * ```\n * (2 ^ prefixLength) * kBucketSize\n * ```\n *\n * @default 6\n */\n prefixLength?: number\n\n /**\n * If true, only ever be a DHT client. If false, be a DHT client until told\n * to be a DHT server via `setMode`.\n *\n * In general this should be left as the default because server mode will be\n * selected automatically when libp2p establishes that the current node has\n * a publicly dialable address.\n *\n * The exception to this is LAN-only DHT (e.g. for testing purposes) where it\n * is safe to assume that the current node is dialable.\n *\n * @default false\n */\n clientMode?: boolean\n\n /**\n * Record selectors\n */\n selectors?: Selectors\n\n /**\n * Record validators\n */\n validators?: Validators\n\n /**\n * How often to query our own PeerId in order to ensure we have a\n * good view on the KAD address space local to our PeerId\n */\n querySelfInterval?: number\n\n /**\n * During startup we run the self-query at a shorter interval to ensure\n * the containing node can respond to queries quickly. Set this interval\n * here in ms.\n *\n * @default 1000\n */\n initialQuerySelfInterval?: number\n\n /**\n * After startup by default all queries will be paused until there is at least\n * one peer in the routing table.\n *\n * Pass true here to disable this behavior.\n *\n * @default false\n */\n allowQueryWithZeroPeers?: boolean\n\n /**\n * The network protocol to use\n *\n * @default \"/ipfs/kad/1.0.0\"\n */\n protocol?: string\n\n /**\n * The logging prefix to use\n *\n * @default \"libp2p:kad-dht\"\n */\n logPrefix?: string\n\n /**\n * The datastore prefix to use\n *\n * @default \"/dht\"\n */\n datastorePrefix?: string\n\n /**\n * The metrics prefix to use\n *\n * @default \"libp2p_kad_dht\"\n */\n metricsPrefix?: string\n\n /**\n * Settings for how long to wait in ms when pinging DHT peers to decide if\n * they should be evicted from the routing table or not.\n */\n pingOldContactTimeout?: Omit<AdaptiveTimeoutInit, 'metricsName' | 'metrics'>\n\n /**\n * How many peers to ping in parallel when deciding if they should\n * be evicted from the routing table or not\n *\n * @default 10\n */\n pingOldContactConcurrency?: number\n\n /**\n * How long the queue to ping peers is allowed to grow\n *\n * @default 100\n */\n pingOldContactMaxQueueSize?: number\n\n /**\n * Settings for how long to wait in ms when pinging DHT peers to decide if\n * they should be added to the routing table or not.\n */\n pingNewContactTimeout?: Omit<AdaptiveTimeoutInit, 'metricsName' | 'metrics'>\n\n /**\n * How many peers to ping in parallel when deciding if they should be added to\n * the routing table or not\n *\n * @default 10\n */\n pingNewContactConcurrency?: number\n\n /**\n * How long the queue to ping peers is allowed to grow\n *\n * @default 100\n */\n pingNewContactMaxQueueSize?: number\n\n /**\n * How many parallel incoming streams to allow on the DHT protocol per\n * connection\n *\n * @default 32\n */\n maxInboundStreams?: number\n\n /**\n * How many parallel outgoing streams to allow on the DHT protocol per\n * connection\n *\n * @default 64\n */\n maxOutboundStreams?: number\n\n /**\n * Initialization options for the Providers component\n */\n providers?: ProvidersInit\n\n /**\n * Initialization options for the Reprovider component\n */\n reprovide?: ReProvideInit\n\n /**\n * For every incoming and outgoing PeerInfo, override address configuration\n * with this filter.\n */\n peerInfoMapper?(peer: PeerInfo): PeerInfo\n\n /**\n * Dynamic network timeout settings for sending messages to peers\n */\n networkDialTimeout?: Omit<AdaptiveTimeoutInit, 'metricsName' | 'metrics'>\n\n /**\n * When a peer that supports the KAD-DHT protocol connects we try to add it to\n * the routing table. This setting is how long an active routing table update\n * may run for in ms once it starts processing. Time spent waiting in the\n * routing table update queue does not count towards this timeout.\n *\n * @default 10_000\n */\n onPeerConnectTimeout?: number\n\n /**\n * When acting as a DHT server, all incoming RPC requests must complete within\n * this timeout in ms otherwise the stream will be closed.\n *\n * @default 10_000\n */\n incomingMessageTimeout?: number\n}\n\nexport interface KadDHTComponents {\n peerId: PeerId\n privateKey: PrivateKey\n registrar: Registrar\n addressManager: AddressManager\n peerStore: PeerStore\n metrics?: Metrics\n connectionManager: ConnectionManager\n datastore: Datastore\n events: TypedEventTarget<Libp2pEvents>\n logger: ComponentLogger\n ping: Ping\n}\n\n/**\n * Creates a custom DHT implementation, please ensure you pass a `protocol`\n * string as an option.\n */\nexport function kadDHT (init: KadDHTInit = {}): (components: KadDHTComponents) => KadDHT {\n return (components: KadDHTComponents) => new KadDHTClass(components, init)\n}\n", "import { decodeMessage, encodeMessage, message, streamMessage } from 'protons-runtime'\nimport type { Codec, DecodeOptions } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface IPNSPublishMetadata {\n keyName: string\n lifetime: number\n}\n\nexport namespace IPNSPublishMetadata {\n let _codec: Codec<IPNSPublishMetadata>\n\n export const codec = (): Codec<IPNSPublishMetadata> => {\n if (_codec == null) {\n _codec = message<IPNSPublishMetadata>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.keyName != null && obj.keyName !== '')) {\n w.uint32(10)\n w.string(obj.keyName)\n }\n\n if ((obj.lifetime != null && obj.lifetime !== 0)) {\n w.uint32(16)\n w.uint32(obj.lifetime)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {\n keyName: '',\n lifetime: 0\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.keyName = reader.string()\n break\n }\n case 2: {\n obj.lifetime = reader.uint32()\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}.keyName`,\n value: reader.string()\n }\n break\n }\n case 2: {\n yield {\n field: `${prefix}.lifetime`,\n value: reader.uint32()\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 IPNSPublishMetadataKeyNameFieldEvent {\n field: '$.keyName'\n value: string\n }\n\n export interface IPNSPublishMetadataLifetimeFieldEvent {\n field: '$.lifetime'\n value: number\n }\n\n export function encode (obj: Partial<IPNSPublishMetadata>): Uint8Array<ArrayBuffer> {\n return encodeMessage(obj, IPNSPublishMetadata.codec())\n }\n\n export function decode (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<IPNSPublishMetadata>): IPNSPublishMetadata {\n return decodeMessage(buf, IPNSPublishMetadata.codec(), opts)\n }\n\n export function stream (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<IPNSPublishMetadata>): Generator<IPNSPublishMetadataKeyNameFieldEvent | IPNSPublishMetadataLifetimeFieldEvent> {\n return streamMessage(buf, IPNSPublishMetadata.codec(), opts)\n }\n}\n", "import { Record } from '@libp2p/kad-dht'\nimport { CustomProgressEvent } from 'progress-events'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { IPNSPublishMetadata } from './pb/metadata.ts'\nimport { dhtRoutingKey, DHT_RECORD_PREFIX, ipnsMetadataKey } from './utils.ts'\nimport type { DatastoreProgressEvents, GetOptions, PutOptions } from './routing/index.ts'\nimport type { AbortOptions, Logger } from '@libp2p/interface'\nimport type { Datastore } from 'interface-datastore'\n\nexport interface GetResult {\n record: Uint8Array\n created: Date\n}\n\nexport interface ListResult {\n routingKey: Uint8Array\n record: Uint8Array\n created: Date\n metadata?: IPNSPublishMetadata\n}\n\nexport interface ListOptions extends AbortOptions {\n onProgress?(evt: DatastoreProgressEvents): void\n}\n\nexport interface LocalStore {\n /**\n * Put an IPNS record into the datastore\n *\n * @param routingKey - The routing key for the IPNS record\n * @param marshaledRecord - The marshaled IPNS record\n * @param options - options for the put operation including metadata\n */\n put(routingKey: Uint8Array, marshaledRecord: Uint8Array, options?: PutOptions): Promise<void>\n get(routingKey: Uint8Array, options?: GetOptions): Promise<GetResult>\n has(routingKey: Uint8Array, options?: AbortOptions): Promise<boolean>\n delete(routingKey: Uint8Array, options?: AbortOptions): Promise<void>\n /**\n * List all IPNS records in the datastore\n */\n list(options?: ListOptions): AsyncIterable<ListResult>\n}\n\n/**\n * Read/write IPNS records to the datastore as DHT records.\n *\n * This lets us publish IPNS records offline then serve them to the network\n * later in response to DHT queries.\n */\nexport function localStore (datastore: Datastore, log: Logger): LocalStore {\n return {\n async put (routingKey: Uint8Array, marshalledRecord: Uint8Array, options: PutOptions = {}) {\n try {\n const key = dhtRoutingKey(routingKey)\n\n // don't overwrite existing, identical records as this will affect the\n // TTL\n try {\n const existingBuf = await datastore.get(key)\n const existingRecord = Record.deserialize(existingBuf)\n\n if (uint8ArrayEquals(existingRecord.value, marshalledRecord)) {\n return\n }\n } catch (err: any) {\n if (err.name !== 'NotFoundError') {\n throw err\n }\n }\n\n // Marshal to libp2p record as the DHT does\n const record = new Record(routingKey, marshalledRecord, new Date())\n\n options.onProgress?.(new CustomProgressEvent('ipns:routing:datastore:put'))\n const batch = datastore.batch()\n batch.put(key, record.serialize())\n\n if (options.metadata != null) {\n // derive the datastore key for the IPNS metadata from the same routing key\n batch.put(ipnsMetadataKey(routingKey), IPNSPublishMetadata.encode(options.metadata))\n }\n await batch.commit(options)\n } catch (err: any) {\n options.onProgress?.(new CustomProgressEvent<Error>('ipns:routing:datastore:error', err))\n throw err\n }\n },\n async get (routingKey: Uint8Array, options: GetOptions = {}): Promise<GetResult> {\n try {\n const key = dhtRoutingKey(routingKey)\n\n options.onProgress?.(new CustomProgressEvent('ipns:routing:datastore:get'))\n const buf = await datastore.get(key, options)\n\n // Unmarshal libp2p record as the DHT does\n const record = Record.deserialize(buf)\n\n return {\n record: record.value,\n created: record.timeReceived\n }\n } catch (err: any) {\n options.onProgress?.(new CustomProgressEvent<Error>('ipns:routing:datastore:error', err))\n throw err\n }\n },\n async has (routingKey: Uint8Array, options: AbortOptions = {}): Promise<boolean> {\n const key = dhtRoutingKey(routingKey)\n return datastore.has(key, options)\n },\n async delete (routingKey, options): Promise<void> {\n const key = dhtRoutingKey(routingKey)\n const batch = datastore.batch()\n batch.delete(key)\n batch.delete(ipnsMetadataKey(routingKey))\n await batch.commit(options)\n },\n async * list (options: ListOptions = {}): AsyncIterable<ListResult> {\n try {\n options.onProgress?.(new CustomProgressEvent('ipns:routing:datastore:list'))\n\n // Query all records with the DHT_RECORD_PREFIX\n for await (const { key, value } of datastore.query({\n prefix: DHT_RECORD_PREFIX\n }, options)) {\n try {\n // Deserialize the record\n const libp2pRecord = Record.deserialize(value)\n\n // Extract the routing key from the datastore key\n const keyString = key.toString()\n const routingKeyBase32 = keyString.substring(DHT_RECORD_PREFIX.length)\n const routingKey = uint8ArrayFromString(routingKeyBase32, 'base32')\n\n const metadataKey = ipnsMetadataKey(routingKey)\n let metadata: IPNSPublishMetadata | undefined\n try {\n const metadataBuf = await datastore.get(metadataKey, options)\n metadata = IPNSPublishMetadata.decode(metadataBuf)\n } catch (err: any) {\n log.error('Error deserializing metadata for %s - %e', routingKeyBase32, err)\n }\n\n yield {\n routingKey,\n metadata,\n record: libp2pRecord.value,\n created: libp2pRecord.timeReceived\n }\n } catch (err) {\n // Skip invalid records\n log.error('Error deserializing record - %e', err)\n }\n }\n } catch (err: any) {\n options.onProgress?.(new CustomProgressEvent<Error>('ipns:routing:datastore:error', err))\n throw err\n }\n }\n }\n}\n", "import { CustomProgressEvent } from 'progress-events'\nimport type { GetOptions, PutOptions } from './index.ts'\nimport type { IPNSRouting } from '../index.ts'\nimport type { Routing } from '@helia/interface'\nimport type { ProgressEvent } from 'progress-events'\n\nexport interface HeliaRoutingComponents {\n routing: Routing\n}\n\nexport type HeliaRoutingProgressEvents =\n ProgressEvent<'ipns:routing:helia:error', Error>\n\nexport class HeliaRouting implements IPNSRouting {\n private readonly routing: Routing\n\n constructor (routing: Routing) {\n this.routing = routing\n }\n\n async put (routingKey: Uint8Array, marshaledRecord: Uint8Array, options: PutOptions = {}): Promise<void> {\n try {\n await this.routing.put(routingKey, marshaledRecord, options)\n } catch (err: any) {\n options.onProgress?.(new CustomProgressEvent<Error>('ipns:routing:helia:error', err))\n throw err\n }\n }\n\n async get (routingKey: Uint8Array, options: GetOptions = {}): Promise<Uint8Array> {\n try {\n return await this.routing.get(routingKey, options)\n } catch (err: any) {\n options.onProgress?.(new CustomProgressEvent<Error>('ipns:routing:helia:error', err))\n throw err\n }\n }\n\n toString (): string {\n return 'HeliaRouting()'\n }\n}\n\n/**\n * The helia routing uses any available Routers configured on the passed Helia\n * node. This could be libp2p, HTTP API Delegated Routing, etc.\n */\nexport function helia (routing: Routing): IPNSRouting {\n return new HeliaRouting(routing)\n}\n", "import type { LocalStore } from '../local-store.ts'\nimport type { IPNSRouting, PutOptions, GetOptions } from './index.ts'\n\nclass LocalStoreRouting {\n private localStore: LocalStore\n\n constructor (localStore: LocalStore) {\n this.localStore = localStore\n }\n\n async put (routingKey: Uint8Array, marshaledRecord: Uint8Array, options?: PutOptions): Promise<void> {\n await this.localStore.put(routingKey, marshaledRecord, options)\n }\n\n async get (routingKey: Uint8Array, options?: GetOptions): Promise<Uint8Array> {\n const { record } = await this.localStore.get(routingKey, options)\n\n return record\n }\n\n toString (): string {\n return 'LocalStoreRouting()'\n }\n}\n\n/**\n * Returns an IPNSRouting implementation that reads/writes to the local store\n */\nexport function localStoreRouting (localStore: LocalStore): IPNSRouting {\n return new LocalStoreRouting(localStore)\n}\n", "import { CID } from 'multiformats/cid'\nimport { IPNSPublisher } from './ipns/publisher.ts'\nimport { IPNSRepublisher } from './ipns/republisher.ts'\nimport { IPNSResolver } from './ipns/resolver.ts'\nimport { localStore } from './local-store.ts'\nimport { helia } from './routing/helia.ts'\nimport { localStoreRouting } from './routing/local-store.ts'\nimport { ipnsSelector } from './selector.ts'\nimport { normalizeKey, normalizeValue, unmarshalIPNSRecord } from './utils.ts'\nimport { ipnsValidator } from './validator.ts'\nimport type { IPNSComponents, IPNS as IPNSInterface, IPNSOptions, PublishResult, PublishOptions, ResolveOptions, ResolveResult } from './index.ts'\nimport type { LocalStore } from './local-store.ts'\nimport type { IPNSRouting } from './routing/index.ts'\nimport type { PublicKey } from '@helia/interface'\nimport type { AbortOptions, Libp2p, Startable } from '@libp2p/interface'\nimport type { ValidateFn, SelectFn } from '@libp2p/kad-dht'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nexport class IPNS implements IPNSInterface, Startable {\n public readonly routers: IPNSRouting[]\n private readonly publisher: IPNSPublisher\n private readonly republisher: IPNSRepublisher\n private readonly resolver: IPNSResolver\n private readonly localStore: LocalStore\n private readonly components: IPNSComponents\n private started: boolean\n\n constructor (components: IPNSComponents, init: IPNSOptions = {}) {\n this.localStore = localStore(components.datastore, components.logger.forComponent('helia:ipns:local-store'))\n this.components = components\n this.started = false\n\n this.routers = [\n localStoreRouting(this.localStore),\n helia(components.routing),\n ...(init.routers ?? [])\n ]\n\n this.publisher = new IPNSPublisher(components, {\n ...init,\n routers: this.routers,\n localStore: this.localStore\n })\n this.republisher = new IPNSRepublisher(components, {\n ...init,\n routers: this.routers,\n localStore: this.localStore\n })\n this.resolver = new IPNSResolver(components, {\n ...init,\n routers: this.routers,\n localStore: this.localStore\n })\n\n // start republishing on Helia start\n components.events.addEventListener('start', this.start.bind(this))\n // stop republishing on Helia stop\n components.events.addEventListener('stop', this.stop.bind(this))\n\n if (this.started) {\n this.republisher.start()\n }\n\n for (const component of Object.values(this.components)) {\n if (isLibp2p(component)) {\n for (const service of Object.values(component.services)) {\n if (isKadDHT(service)) {\n // @ ts-expect-error https://github.com/libp2p/js-libp2p/pull/3506\n service.selectors.ipns = async (key: Uint8Array, values: Uint8Array[]): Promise<number> => {\n const records = await Promise.all(values.map(buf => unmarshalIPNSRecord(key, buf, this.components.keychain)))\n\n return ipnsSelector(key, records)\n }\n\n service.validators.ipns = async (key: Uint8Array, value: Uint8Array): Promise<void> => {\n const record = await unmarshalIPNSRecord(key, value, this.components.keychain)\n await ipnsValidator(record)\n }\n }\n }\n }\n }\n }\n\n start (): void {\n if (this.started) {\n return\n }\n\n this.started = true\n this.republisher.start()\n }\n\n stop (): void {\n if (!this.started) {\n return\n }\n\n this.started = false\n this.republisher.stop()\n }\n\n async publish (keyName: string, value: PublicKey | CID | MultihashDigest | string, options: PublishOptions = {}): Promise<PublishResult> {\n return this.publisher.publish(keyName, normalizeValue(value), options)\n }\n\n async * resolve (key: PublicKey | CID<unknown, 0x72> | MultihashDigest | string, options: ResolveOptions = {}): AsyncGenerator<ResolveResult> {\n const { digest } = normalizeKey(key)\n\n yield * this.resolver.resolve(digest, options)\n }\n\n async unpublish (keyName: string, options?: AbortOptions): Promise<void> {\n return this.publisher.unpublish(keyName, options)\n }\n}\n\nfunction isLibp2p (obj?: any): obj is Libp2p {\n return obj?.services != null\n}\n\nfunction isKadDHT (obj?: any): obj is { validators: Record<string, ValidateFn>, selectors: Record<string, SelectFn> } {\n return obj?.validators != null && obj?.selectors != null\n}\n"],
5
+ "mappings": ";8rBAAA,IAAAA,GAAAC,GAAA,CAAAC,GAAAC,KAAA,KAAIC,IAAU,UAAU,CAAc,OAAOD,GAApB,MAA6BA,GAAO,QAAQE,GAAG,IAAIC,EAAE,MAAMC,EAAE,KAAKC,EAAE,OAAOD,EAAE,IAAIE,EAAEH,EAAEE,EAAEE,EAAE,IAAID,EAAEE,EAAE,OAAOC,EAAE,WAAWC,EAAE,IAAI,EAAE,YAAYC,EAAE,KAAK,OAAO,SAASC,EAAE,CAAC,IAAIC,EAAED,EAAEA,EAAE,EAAE,OAAUC,GAAH,IAAOD,EAAE,GAAOA,IAAJ,GAAO,EAAEA,GAAG,KAAK,GAAGC,CAAC,EAAED,EAAEV,EAAE,UAAUY,GAAGZ,EAAE,SAAS,SAASU,EAAE,CAAC,OAAO,IAAIV,EAAE,CAACU,CAAC,CAAC,EAAEV,EAAE,YAAYa,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAEb,EAAE,YAAYa,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAEb,EAAE,WAAW,SAASU,EAAE,CAAC,IAAIN,EAAES,EAAE,IAAIb,EAAEU,GAAGA,GAAG,IAAI,QAAQ,gBAAgB,SAASA,EAAE,CAAC,IAAIA,EAAE,CAACA,EAAEC,EAAE,MAAMD,EAAE,MAAM,IAAI,OAAOG,EAAE,KAAKH,EAAEC,EAAEA,CAAC,CAAC,EAAE,QAAQ,+BAA+B,SAASD,EAAEC,EAAEE,EAAE,CAAC,OAAOF,EAAE,IAAIE,GAAG,IAAIT,EAAE,KAAK,GAAG,CAACO,GAAG,CAACE,GAAG,EAAE,CAAC,EAAE,QAAQ,SAAS,SAASH,EAAE,CAAC,OAAOG,EAAE,KAAK,EAAEH,EAAE,GAAG,OAAO,EAAE,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AAiBH,EAAmDI,EAA0B,CAAA,EAAE,CAC7G,OAAO,KAAK,UAAU,QAAQD,EAASE,GAAeL,CAAK,EAAGI,CAAO,CACvE,CAEA,MAAQ,QAASV,EAAgEU,EAA0B,CAAA,EAAE,CAC3G,GAAM,CAAE,OAAAE,CAAM,EAAKC,GAAab,CAAG,EAEnC,MAAQ,KAAK,SAAS,QAAQY,EAAQF,CAAO,CAC/C,CAEA,MAAM,UAAWD,EAAiBC,EAAsB,CACtD,OAAO,KAAK,UAAU,UAAUD,EAASC,CAAO,CAClD,GAGF,SAASb,GAAUiB,EAAS,CAC1B,OAAOA,GAAK,UAAY,IAC1B,CAEA,SAASf,GAAUe,EAAS,CAC1B,OAAOA,GAAK,YAAc,MAAQA,GAAK,WAAa,IACtD,CtG+OM,SAAUC,GAAMC,EAA4BC,EAAuB,CAAA,EAAE,CACzE,OAAO,IAAIC,GAAUF,EAAYC,CAAO,CAC1C,CAEM,SAAUE,GAAcH,EAAoCC,EAA+B,CAAA,EAAE,CACjG,IAAMG,EAAQC,GAAWL,EAAW,UAAWA,EAAW,OAAO,aAAa,wBAAwB,CAAC,EACjGM,EAAU,CACdC,GAAkBH,CAAK,EACvBI,GAAMR,EAAW,OAAO,EACxB,GAAIC,EAAQ,SAAW,CAAA,GAGzB,OAAO,IAAIQ,GAAkBT,EAAY,CACvC,QAAAM,EACA,WAAYF,EACb,CACH",
6
+ "names": ["require_timestamp_min", "__commonJSMin", "exports", "module", "Timestamp", "d", "l", "s", "T", "e", "f", "c", "g", "h", "m", "n", "t", "o", "r", "p", "y", "M", "u", "C", "D", "a", "i", "v", "w", "index_exports", "__export", "ipns", "ipnsResolver", "base32_exports", "__export", "base32", "base32hex", "base32hexpad", "base32hexpadupper", "base32hexupper", "base32pad", "base32padupper", "base32upper", "base32z", "empty", "equals", "aa", "bb", "ii", "coerce", "o", "toArrayBufferBackedArray", "fromString", "str", "toString", "b", "isByteArrayWithArrayBuffer", "toArrayBufferBackedArray", "base", "ALPHABET", "name", "BASE_MAP", "j", "i", "x", "xc", "BASE", "LEADER", "FACTOR", "iFACTOR", "encode", "source", "zeroes", "length", "pbegin", "pend", "size", "b58", "carry", "it1", "it2", "str", "decodeUnsafe", "psz", "b256", "it3", "it4", "vch", "decode", "string", "buffer", "src", "_brrp__multiformats_scope_baseX", "base_x_default", "Encoder", "name", "prefix", "baseEncode", "bytes", "Decoder", "baseDecode", "prefixCodePoint", "text", "decoder", "or", "ComposedDecoder", "decoders", "input", "left", "right", "Codec", "from", "encode", "decode", "baseX", "alphabet", "base_x_default", "coerce", "string", "alphabetIdx", "bitsPerChar", "end", "out", "bits", "buffer", "written", "i", "value", "data", "pad", "mask", "createAlphabetIdx", "rfc4648", "base32", "rfc4648", "base32upper", "base32pad", "base32padupper", "base32hex", "base32hexupper", "base32hexpad", "base32hexpadupper", "base32z", "base36_exports", "__export", "base36", "base36upper", "base36", "baseX", "base36upper", "base58_exports", "__export", "base58btc", "base58flickr", "base58btc", "baseX", "base58flickr", "encode_1", "encode", "MSB", "REST", "MSBALL", "INT", "num", "out", "offset", "oldOffset", "decode", "read", "MSB$1", "REST$1", "buf", "res", "shift", "counter", "b", "l", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "N8", "N9", "length", "value", "varint", "_brrp_varint", "varint_default", "decode", "data", "offset", "varint_default", "encodeTo", "int", "target", "encodingLength", "create", "code", "digest", "size", "sizeOffset", "encodingLength", "digestOffset", "bytes", "encodeTo", "Digest", "decode", "multihash", "coerce", "equals", "a", "b", "data", "toArrayBufferBackedArray", "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", "DEFAULT_TTL_NS", "DEFAULT_REPUBLISH_CONCURRENCY", "RecordsFailedValidationError", "InvalidValueError", "RecordNotFoundError", "SignatureCreationError", "SignatureVerificationError", "RecordExpiredError", "UnsupportedValidityError", "RecordTooLargeError", "InvalidRecordDataError", "InvalidEmbeddedPublicKeyError", "import_timestamp_nano", "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", "base10", "baseX", "base16_exports", "__export", "base16", "base16upper", "base16", "rfc4648", "base16upper", "base2_exports", "__export", "base2", "base2", "rfc4648", "base256emoji_exports", "__export", "base256emoji", "alphabet", "alphabetBytesToChars", "p", "c", "i", "alphabetCharsToBytes", "codePoint", "encode", "data", "decode", "str", "byts", "char", "byt", "base256emoji", "from", "base64_exports", "__export", "base64", "base64pad", "base64url", "base64urlpad", "base64", "rfc4648", "base64pad", "base64url", "base64urlpad", "base8_exports", "__export", "base8", "base8", "rfc4648", "identity_exports", "__export", "identity", "identity", "from", "buf", "toString", "str", "fromString", "textEncoder", "textDecoder", "identity_exports", "__export", "identity", "code", "name", "encode", "coerce", "digest", "input", "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", "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", "IpnsEntry", "ValidityType", "__ValidityTypeValues", "enumeration", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "prefix", "encode", "encodeMessage", "decode", "buf", "decodeMessage", "stream", "streamMessage", "ipnsSelector", "key", "data", "entries", "record", "index", "a", "b", "aSeq", "bSeq", "IpnsEntry", "recordAValidityDate", "NanoDate", "recordBValidityDate", "isByteArrayWithArrayBuffer", "b", "asUint8Array", "buf", "concat", "arrays", "length", "acc", "curr", "output", "allocUnsafe", "offset", "arr", "asUint8Array", "equals", "a", "b", "i", "isPublicKey", "obj", "AbortError", "message", "isEventObject", "obj", "isOnce", "options", "TypedEventEmitter", "#listeners", "type", "listeners", "listener", "once", "evt", "list", "callback", "detail", "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", "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", "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", "e", "objectToTokens", "typ", "isMap", "keys", "maxLength", "skipUndefined", "i", "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", "i", "value", "tokensToObject", "tokenToMap", "useMaps", "rejectDuplicateMapKeys", "obj", "m", "key", "tokenToMapEntries", "createTagDecodeControl", "called", "decode", "Type", "entries", "entry", "decodeControl", "result", "decodeFirst", "u8aData", "asU8A", "decoded", "remainder", "Tagged", "_Tagged", "tag", "value", "decode", "tagNumbers", "tags", "toString", "array", "encoding", "base", "bases_default", "pathSepS", "pathSepB", "pathSep", "Key", "_Key", "s", "clean", "fromString", "encoding", "toString", "list", "other", "bytes", "key", "list1", "list2", "i", "c1", "c2", "ns", "namespaceType", "namespaceValue", "p", "keys", "flatten", "parts", "arr", "LIBP2P_KEY_CODEC", "MAX_RECORD_SIZE", "IPNS_PREFIX", "fromString", "IPNS_STRING_PREFIX", "isCodec", "digest", "codec", "DHT_RECORD_PREFIX", "IPNS_METADATA_PREFIX", "dhtRoutingKey", "key", "Key", "toString", "ipnsMetadataKey", "shouldRepublish", "ipnsRecord", "created", "now", "dhtExpiry", "recordExpiry", "ipnsRecordDataForV1Sig", "value", "validityType", "validity", "validityTypeBuffer", "fromString", "valueBytes", "concat", "ipnsRecordDataForV2Sig", "data", "entryData", "marshalIPNSRecord", "obj", "publicKey", "IpnsEntry", "valueToString", "CID", "toString", "unmarshalIPNSRecord", "routingKey", "marshalledRecord", "keychain", "options", "MAX_RECORD_SIZE", "RecordTooLargeError", "message", "SignatureVerificationError", "parseCborData", "routingMultihash", "multihashFromIPNSRoutingKey", "isCodec", "InvalidEmbeddedPublicKeyError", "validateCborDataMatchesPbData", "multihashToIPNSRoutingKey", "digest", "IPNS_PREFIX", "key", "decode", "createCborData", "sequence", "ttl", "ValidityType", "UnsupportedValidityError", "encode", "buf", "normalizeValue", "isPublicKey", "base36", "cid", "asCID", "LIBP2P_KEY_CODEC", "hasBytes", "string", "name", "rest", "component", "InvalidValueError", "isMultihashDigest", "normalizeKey", "codec", "base58btc", "entry", "InvalidRecordDataError", "equals", "hasToCID", "import_timestamp_nano", "ipnsValidator", "record", "options", "InvalidEmbeddedPublicKeyError", "isValid", "dataForSignature", "ipnsRecordDataForV2Sig", "SignatureVerificationError", "IpnsEntry", "NanoDate", "RecordExpiredError", "UnsupportedValidityError", "IPNSResolver", "components", "init", "key", "options", "digest", "normalizeKey", "routingKey", "multihashToIPNSRoutingKey", "record", "#findIpnsRecord", "IPNS_STRING_PREFIX", "records", "marshaledIPNSRecord", "created", "ipnsRecord", "unmarshalIPNSRecord", "ipnsValidator", "ttlMs", "DEFAULT_TTL_NS", "err", "RecordNotFoundError", "foundInvalid", "errors", "router", "RecordsFailedValidationError", "ipnsSelector", "CustomProgressEvent", "type", "detail", "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", "r", "setupFormatters", "formatters", "v", "error", "browser_default", "setup", "src_default", "browser_default", "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", "import_timestamp_nano", "log", "logger", "DEFAULT_TTL_NS", "namespace", "namespaceLength", "defaultCreateOptions", "createIPNSRecord", "privateKey", "value", "seq", "lifetime", "options", "expirationDate", "NanoDate", "validityType", "IpnsEntry", "ttlNs", "_create", "_create", "privateKey", "value", "seq", "validityType", "validity", "ttl", "options", "defaultCreateOptions", "isoValidity", "fromString", "data", "createCborData", "sigData", "ipnsRecordDataForV2Sig", "signatureV2", "publicKey", "shouldEmbedPublicKey", "record", "signatureV1", "signLegacyV1", "marshalIPNSRecord", "dataForSignature", "ipnsRecordDataForV1Sig", "error", "log", "SignatureCreationError", "key", "IPNSPublisher", "components", "init", "keyName", "value", "options", "key", "#loadOrCreateKey", "digest", "routingKey", "multihashToIPNSRoutingKey", "sequenceNumber", "record", "unmarshalIPNSRecord", "ttlNs", "DEFAULT_TTL_NS", "lifetime", "createIPNSRecord", "marshaledRecord", "marshalIPNSRecord", "r", "base36", "err", "CustomProgressEvent", "pDefer", "deferred", "resolve", "reject", "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", "TimeoutError", "_TimeoutError", "message", "options", "getAbortedReason", "signal", "pTimeout", "promise", "milliseconds", "fallback", "customTimers", "timer", "abortHandler", "cancelablePromise", "resolve", "reject", "timeoutError", "error", "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", "defaultTranslate", "signal", "raceSignal", "promise", "opts", "translateError", "listener", "resolve", "reject", "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", "repeatingTask", "fn", "interval", "options", "timeout", "shutdownController", "running", "runTask", "opts", "signal", "anySignal", "runTaskDebounced", "debounce", "started", "ms", "IPNSRepublisher", "components", "init", "DEFAULT_REPUBLISH_CONCURRENCY", "repeatingTask", "#republish", "options", "queue", "Queue", "recordsToRepublish", "listed", "routingKey", "record", "metadata", "created", "ipnsRecord", "unmarshalIPNSRecord", "err", "shouldRepublish", "sequenceNumber", "ttlNs", "DEFAULT_TTL_NS", "privKey", "updatedRecord", "createIPNSRecord", "marshaledRecord", "marshalIPNSRecord", "r", "Record", "_codec", "message", "obj", "w", "opts", "reader", "length", "alloc", "end", "tag", "prefix", "encode", "encodeMessage", "decode", "buf", "decodeMessage", "stream", "streamMessage", "toRFC3339", "time", "year", "month", "day", "hour", "minute", "seconds", "milliseconds", "nanoseconds", "parseRFC3339", "rfc3339Matcher", "m", "date", "second", "millisecond", "Libp2pRecord", "_Libp2pRecord", "key", "value", "timeReceived", "Record", "toRFC3339", "raw", "rec", "obj", "receivedTime", "parseRFC3339", "EventTypes", "IPNSPublishMetadata", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "prefix", "encode", "encodeMessage", "decode", "buf", "decodeMessage", "stream", "streamMessage", "localStore", "datastore", "log", "routingKey", "marshalledRecord", "options", "key", "dhtRoutingKey", "existingBuf", "existingRecord", "Libp2pRecord", "equals", "err", "record", "CustomProgressEvent", "batch", "ipnsMetadataKey", "IPNSPublishMetadata", "buf", "value", "DHT_RECORD_PREFIX", "libp2pRecord", "routingKeyBase32", "fromString", "metadataKey", "metadata", "metadataBuf", "HeliaRouting", "routing", "routingKey", "marshaledRecord", "options", "err", "CustomProgressEvent", "helia", "LocalStoreRouting", "localStore", "routingKey", "marshaledRecord", "options", "record", "localStoreRouting", "IPNS", "components", "init", "localStore", "localStoreRouting", "helia", "IPNSPublisher", "IPNSRepublisher", "IPNSResolver", "component", "isLibp2p", "service", "isKadDHT", "key", "values", "records", "buf", "unmarshalIPNSRecord", "ipnsSelector", "value", "record", "ipnsValidator", "keyName", "options", "normalizeValue", "digest", "normalizeKey", "obj", "ipns", "components", "options", "IPNS", "ipnsResolver", "store", "localStore", "routers", "localStoreRouting", "helia", "IPNSResolver"]
7
7
  }